Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rs232 string comparison in C

I am trying to make a programm which can read commands from a RS232 port and use them for the next action.

I am using a string compare command to compare the desired 'action' string with the RS232 string. Something goes wrong with the string conversions somewhere. I used a putstr commando to see what my microcontroller is getting from my computer but it doesn't work propperly. It returns the last two chars of my string with a dot or a 'd' in the middle. (I have absolutely no clue where the dot/d come from..)

So this is my main code:

int length;
char *str[20];
while(1)
{
    delayms(1000);
    length = 5; //maximum length per string
    getstr(*str, length); //get string from the RS232
    putstr(*str); //return the string to the computer by RS232 for debugging
    if (strncmp (*str,"prox",strlen("prox")) == 0) //check wether four letters in the string are the same as the word "prox"
    {
        LCD_clearscreen(0xF00F);
        printf ("prox detected");
    }
    else if (strncmp (*str,"AA",strlen("AA")) == 0) //check wether two letters in the string are the same as the chars "AA"
    {
        LCD_clearscreen(0x0F0F);
        printf ("AA detected");
    }
}

These are the used RS232 functions:

/*
 * p u t s t r
 *
 *  Send a string towards the RS232 port
 */
void putstr(char *s)
{
    while(*s != '\0')
    {
            putch(*s);
            s++;
    }
}

/*
 * p u t c h
 *
 *  Send a character towards the RS232 port
 */
void putch(char c)
{
    while(U1STAbits.UTXBF);     // Wait for space in the transmit buffer
    U1TXREG=c;
    if (debug) LCD_putc(c);
}

/*
 * g e t c
 *
 *  Receive a character of the RS232 port
 */
char getch(void)
{
    while(!has_c());    // Wait till data is available in the receive buffer
    return(U1RXREG);
}

/*
 * g e t s t r
 *
 * Receive a line with a maximum amount of characters
 * the line is closed with '\0'
 * the amount of received characters is returned
 */
 int getstr(char *buf, int size)
 {
    int i;

    for (i = 0 ; i < size-1 ; i++)
    {
        if ((buf[i++] = getch()) == '\n') break;
    }
    buf[i] = '\0';

    return(i);
}

When I use this programm with my Microchip hooked up to a terminal I get something like this:

What I send:
abcdefgh

What I get back (in sets of 3 characters):
adbc.de.fg.h
like image 965
user1442205 Avatar asked Jul 21 '26 01:07

user1442205


1 Answers

The problem is how you declare your string. As it is now, you declare an array of 20 char pointers. I think you should probably declare it as a normal char array:

char str[20];

When you then pass the array to the functions, just use e.g. getstr(str, length);.

like image 52
Some programmer dude Avatar answered Jul 23 '26 18:07

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!