2012-06-07 195 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)) 

希望幫助。