我正在使用C,它读取串口ok上的数据。但与串行端口一样,数据长度并不总是相同。我想读到\n\r
。在程序顶部声明的缓冲区char szBuff[10]
包含来自Readfile()
方法的串行端口的数据。
我打算用(while != "\n")
来填充一个临时缓冲区但不起作用。我还试图打印出szBuff
的各个元素,看看发生了什么)但是这会使程序崩溃。
void ReadSerialPort (void){
strcpy(szBuff, "");
dwBytesRead = 0;
char temp;
//printf("Reading Port %s...", portName);
if(!ReadFile(hSerial, szBuff, bufSize, &dwBytesRead, NULL)){
// Error occurred. Inform user
printf("Error occurred during read\n");
}
if((int) dwBytesRead == 0)
printf("0 Characters Read\n");
else
//printf("Read String: %s, Number of Characters: %d\n\n", szBuff, (int) dwBytesRead);
// printf("%s ", szBuff, (int) dwBytesRead);
while(szBuff != "\n")
fill buffer
temp = szBuff[1];
printf( szBuff);
printf( temp);
}
为什么不能打印出单个元素,为什么不能在搜索\n
时进行搜索,或者有更好的方法来实现这一目标吗?
答案 0 :(得分:0)
您的代码中有一些内容可以阻止您查看打印出来的数据。
1) 读取 How to create a Minimal, Complete, and Verifiable example ,因为您的代码将无法编译,并且使用其当前格式,很难读
2) 在您的示例中使用{}
也是一种改进。因为,你的意图是模棱两可的。例如,围绕if...else
以防止执行流程直接跳转到while
语句:
if((int) dwBytesRead == 0)
{
printf("0 Characters Read\n");
}
else
{
//printf("Read String: %s, Number of Characters: %d\n\n", szBuff, (int) dwBytesRead);
// printf("%s ", szBuff, (int) dwBytesRead);
}
3) 我没有足够的编译,我假设你已经发布了一些伪代码,但在声明中:
while(szBuff != "\n")
fill buffer //pseudo code?
使用szBuff
进行测试的字符串缓冲区!=
将无效,这可能不是您想要的,但以防万一:
使用 strstr() 确定字符串是否包含换行符。
while(strstr(szBuff, "\n") == NULL)
fill buffer //pseudo code?
或者,(根据评论中的建议)使用 strchr() :
char *tmp = NULL;
while(strchr(szBuff, '\n') == NULL)
fill buffer //pseudo code?
可能更好的方法(以及您可能想要的)可能是使用字符形式:\n
(单引号)和dwBytesRead
变量,并进行比较。
for(i=0;i<dwBytesRead;i++)
{
if(szBuf[i] != '\n')
{
temp = szBuff[i];
printf("%c", temp);//note format string
}
printf("%s\n", szBuff);
...
注意,需要告诉printf
如何解释您想要打印的内容。因为szBuff
是类型char *
(或应该是),语句:
printf( szBuff); // will likely show results in this case but...
printf("%s\n", szBuff); //an explicit format specifier is recommended.
并且
printf( temp ); // needs a format string to tell printf temp is type char
答案 1 :(得分:0)
感谢您提供了明确的建议,这确实帮助我解决了编码方面的问题。关于来自串口的“字符溢出”(如果存在这样的术语),它与读取的字节数有关,并且由于数据长度是交替的,固定数据缓冲器将不起作用。我决定一次做一个字节并检查终止字符是什么。我放了一个while循环来确定行尾。还有一个循环可以永久运行,每秒都会有样本进入。它很安静。
<iframe>
}