我有一个 Arduino 通过 USB 连接到我的电脑。我尝试从中读取 COM 端口。
谁能看看这是否有什么明显的错误???
void main()
{
int exitStatus;
unsigned int bytesToRead = 1;
unsigned char *buffer = (unsigned char*) malloc(sizeof(unsigned char) + 1);
Serial *connection = new Serial("COM3");
if(connection->IsConnected()){
exitStatus=connection->ReadData(buffer, bytesToRead);
if( *buffer > 0)
<statement I'm trying to hit>
}
}
现在它总是命中“我正在尝试命中的声明”,即使它不应该命中。调试它总是显示缓冲区的内容是很多垃圾。我知道来自串行输入的内容应该是正确的,因为从我在串行监视器中看到的内容来看,一切看起来都不错。
想法?
最佳答案
您没有评估 exitStatus
变量,这可能表明读取成功。
此外,如果您只想读取一个字节,则不需要 malloc 内存,只需将指针传递给本地 char 变量即可。
虽然我在这里,但 main 的类型是 int main()
或 int main(int argc, char** argv)
int main()
{
int exitStatus;
unsigned int bytesToRead = 1;
unsigned char buffer;
Serial *connection = new Serial("COM3");
if(connection->IsConnected()){
exitStatus=connection->ReadData(&buffer, 1);
if((exitStatus == <Insert the value for a correct read status>) && (buffer != '0'))
<statement I'm trying to hit>
}
return 0;
}
更新 将 != 0 检查更改为 != '0',因为我怀疑有一个 '0' 字符 (=0x30) 来自串行接口(interface)。
关于c++ - 无法读取串行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7777131/