2012-06-07 192 views
3

我想制作一个程序,它可以从RS232端口读取命令并将它们用于下一个动作。rs232字符串比较C

我正在使用字符串比较命令来比较所需的'行动'字符串与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); 
} 

当我使用这个程序与我的微芯片连接到一个终端我得到这样的东西:

What I send: 
abcdefgh 

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

回答

3

问题是如何你声明你的字符串。就像现在一样,您声明了一个包含20个指针的数组。我想你也许应该声明它作为一个正常的char阵列:

char str[20]; 

然后,当您将数组传递给函数,只是使用如getstr(str, length);

+0

感谢您的超快反应! 我刚刚更改了我的代码,现在我遇到了与以前相同的问题(之前我遇到了我在此处发布的问题)。当我现在使用我的终端时,我可以写一些东西,它只返回两个一组的第一个字母。所以当我写这个: abcdef 它返回这个: 王牌 – user1442205

+0

问题解决! 我的getstring函数有i ++ 2次! int getstr(char * buf,int size) { int i;对于(i = 0; i user1442205

2

据我所知,strcmp函数在将指针传递给字符串时起作用,而不是字符串本身。

当您使用

char *str[20]; 

您声明名为“STR”,而不是一个字符数组指针数组。

你的问题是你传递了一个指向strcmp函数的数组。您可以通过声明你的字符串为解决这个问题:

char string[20]; 

如果你需要使用的char *一些奇怪的原因,下面的声明是等价的:

char * str = malloc(20*sizeof(int)) 

希望帮助。