我想製作一個程序,它可以從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
感謝您的超快反應! 我剛剛更改了我的代碼,現在我遇到了與以前相同的問題(之前我遇到了我在此處發佈的問題)。當我現在使用我的終端時,我可以寫一些東西,它只返回兩個一組的第一個字母。所以當我寫這個: abcdef 它返回這個: 王牌 – user1442205
問題解決! 我的getstring函數有i ++ 2次! int getstr(char * buf,int size) { int i;對於(i = 0; i
user1442205