在C语言中比较RS232字符串

3
我正在尝试制作一个程序,该程序可以从RS232端口读取命令并将其用于下一步操作。我使用字符串比较命令将所需的“操作”字符串与RS232字符串进行比较。但是,在某个地方,字符串转换出现了问题。我使用putstr命令来查看我的微控制器从计算机接收到的内容,但它不能正常工作。它会返回我的字符串的最后两个字符,并带有一个点或一个“d”。(我绝对不知道这个点/ d来自哪里..)
以下是我的主要代码:
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");
    }
}

以下是常用的RS232函数:

/*
 * 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);
}

当我将我的Microchip连接到终端并使用此程序时,我会得到类似于以下的输出:
What I send:
abcdefgh

What I get back (in sets of 3 characters):
adbc.de.fg.h
2个回答

3
问题在于如何声明字符串。目前你声明了一个包含20个char指针的数组。我认为你应该将其声明为普通的char数组:
char str[20];

当您将该数组传递给函数时,只需使用例如getstr(str, length);

谢谢您的超快速响应!我刚刚更改了我的代码,现在我遇到了与之前相同的问题(在我在这里发布问题之前)。现在当我使用终端时,我可以输入一些内容,但它只会以两个字母为一组返回第一个字母。所以当我输入这个:abcdef它会返回这个: ace - user1442205
问题解决了!我的getstring函数中i++出现了两次!int getstr(char *buf, int size) { int i;for (i = 0 ; i < size-1 ; i++) { if ((buf[i] = getch()) == '\n') break; i++; } buf[i] = '\0'; return(i);} - user1442205

2
据我所知,strcmp函数在传递指向字符串的指针时起作用,而不是字符串本身。
当您使用时,
char *str[20];

你正在声明一个指针数组,名为“str”,而不是字符数组。
你的问题在于你将指针数组传递给了strcmp函数。你可以通过将字符串声明为以下形式来解决它:
 char string[20];

如果出于某种奇怪的原因需要使用 char *,则以下声明是等效的:
   char * str = malloc(20*sizeof(int)) 

希望这能帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接