我正在尝试制作一个能够通过串口与我的Arduino微控制器通信的Console C程序,但是我遇到了ReadFile()函数的问题:
这是我的C控制台程序中的ReadFile()函数代码:
if(ReadFile(myPortHandle, &szBuf, 1, &dwIncommingReadSize, NULL) != 0)
{
cout<<"FOUND IT!"<<endl;
Sleep(100);
}
else
{
cout<<".";
Sleep(100);
}
ReadFile函数始终返回“False”值,这意味着它没有在串行端口中找到任何内容 . 在串口的另一端,我使用以下代码将Arduino连接起来:
int switchPin = 4; // Switch connected to pin 4
void setup() {
pinMode(switchPin, INPUT); // Set pin 0 as an input
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
if (digitalRead(switchPin) == HIGH) { // If switch is ON,
Serial.write(1); // send 1 to Processing
} else { // If the switch is not ON,
Serial.write(0); // send 0 to Processing
}
delay(100); // Wait 100 milliseconds
}
每次按下按钮,我都会向串口发送一个“1”值,每次不按下按钮就会发出“0”值 . 基本上,我从一个教程中获得了Arduino代码,我看过如何与程序Processing进行串行通信(这完美地工作),虽然我无法对我用C编写的简单控制台应用程序做同样的事情,因为出于某种原因ReadFile()函数未在串行端口中查找任何信息 .
有人碰巧知道为什么吗?
P.S . :C控制台程序中的完整代码可以在这里找到:https://stackoverflow.com/questions/27844956/c-console-program-serial-communication-arduino
2 回答
不,这不是它的意思 . FALSE返回值表示它是 failed . 这绝不正常,您必须实现错误报告代码,以便您可以诊断原因 . 由于没有理由继续运行,因此结束该计划 . 除非您通过设置读取超时将串行端口设置为故意失败 .
使用GetLastError()获取基础Windows错误代码 .
您希望使用MS Windows,因此首先尝试使用portmon捕获arduino输出,然后您可以调试您的C代码 .