C++ 串行通信问题

标签 c++ console arduino readfile serial-communication

我正在尝试制作一个控制台 C++ 程序,该程序将能够通过串行端口与我的 Arduino 微 Controller 进行通信,但是我遇到了 ReadFile() 函数的问题:

这是来 self 的 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

最佳答案

The ReadFile function is consistently returning the "False" value, meaning it is not finding anything

不,那不是它的意思。 FALSE 返回值表示它失败。这绝非正常,您必须实现错误报告代码以便诊断原因。并结束程序,因为几乎没有理由继续运行。除非您通过设置读取超时将串行端口设置为故意失败。

使用 GetLastError() 获取底层 Windows 错误代码。

关于C++ 串行通信问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27864062/

相关文章:

windows - 从代码创建另一个窗口?

c# - 如何通过读取用户输入将变量添加到我的列表中?

c++ - 程序无法在 Linux 中运行

c++ - 如何返回可变数量的各种类型的容器?

c++ - 如何使 map::find 操作不区分大小写?

javascript - Array.prototype.concat() 底层

c - 解析传入的数据包

c++ - Arduino 中带有构造函数的对象组合

c - 在 Arduino 中转换有符号/无符号 int 变量时出现问题

c++ - gcc:错误:在 MacOS 上构建 openjdk 9 时无法识别的命令行选项 '-mstack-alignment=16'