我正在尝试制作一个程序,该程序可以从RS232端口读取命令并将其用于下一步操作。我使用字符串比较命令将所需的“操作”字符串与RS232字符串进行比较。但是,在某个地方,字符串转换出现了问题。我使用putstr命令来查看我的微控制器从计算机接收到的内容,但它不能正常工作。它会返回我的字符串的最后两个字符,并带有一个点或一个“d”。(我绝对不知道这个点/ d来自哪里..)
以下是我的主要代码:
当我将我的Microchip连接到终端并使用此程序时,我会得到类似于以下的输出:
以下是我的主要代码:
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
for (i = 0 ; i < size-1 ; i++) { if ((buf[i] = getch()) == '\n') break; i++; } buf[i] = '\0'; return(i);
} - user1442205