我正在尝试制作一个可以从 RS232 端口读取命令并将其用于下一步操作的程序。
我正在使用字符串比较命令将所需的“操作”字符串与 RS232 字符串进行比较。某处的字符串转换出了点问题。我使用 putstr commando 来查看我的微控制器从我的计算机中得到了什么,但它不能正常工作。它返回我的字符串的最后两个字符,中间有一个点或一个“d”。(我完全不知道 dot/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