我正在尝试做一个程序员,可以从RS232端口读取命令,并使用它们进行下一步的行动。
我使用字符串比较命令将所需的'action‘字符串与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发布于 2012-06-07 21:07:55
问题是你如何声明你的字符串。现在,您声明了一个由20个char指针组成的数组。我认为你应该将它声明为一个普通的char数组:
char str[20];然后,当您将数组传递给函数时,只需使用getstr(str, length);。
发布于 2012-06-07 21:22:18
据我所知,strcmp函数在传递指向字符串的指针时起作用,而不是字符串本身。
当您使用
char *str[20];您声明的是名为"str“的指针数组,而不是char数组。
您的问题是您正在传递一个指向strcmp函数的指针数组。您可以通过将字符串声明为:
char string[20];如果出于某种奇怪的原因需要使用char *,则以下声明是等效的:
char * str = malloc(20*sizeof(int)) 希望这能有所帮助。
https://stackoverflow.com/questions/10932317
复制相似问题