c++ - Windows 上的 C++ 串行通信问题
问题描述
我正在尝试在 Windows 上使用 C++ 与 Arduino 通信。
Arduino 正在等待一个数字,并将点亮接收到的数字指定的 LED 数量。我可以成功打开一个端口并将数据发送到 Arduino,但是有一些奇怪的行为。
当我使用 Arduino IDE 中的内置串行控制台并发送例如“8”时,Arduino 会做出正确反应。(发送的数据是38 0A
根据串行嗅探器)。
当我运行我的 C++ 代码时,发送的数据也是,38 0A
但是 Arduino 不会对它做出反应。
我的 PC 端 C++ 代码:
#include <Windows.h>
#include <iostream>
bool write(void* data, int len)
{
HANDLE hPort;
hPort = CreateFile("\\\\.\\COM4", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DCB dcb = { 0 };
dcb.DCBlength = sizeof(dcb);
DWORD byteswritten;
if (!GetCommState(hPort, &dcb)) return false;
dcb.BaudRate = CBR_115200;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if (!SetCommState(hPort, &dcb)) return false;
bool retVal = WriteFile(hPort, data, len, &byteswritten, NULL);
CloseHandle(hPort);
return retVal;
}
int main()
{
char lpBuffer[] = "8\n";
if (write(lpBuffer, strlen(lpBuffer))) {
std::cout << "Success" << std::endl;
}
else {
std::cout << "Error" << std::endl;
}
return 0;
}
这是Arduino代码,虽然我认为问题出在PC端......
#define BAUD 115200
int pins[] = {A5, A4, A3, 2, 4, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int count = 0;
void setup() {
Serial.begin(BAUD);
for(int pin : pins) {
pinMode(pin, OUTPUT);
}
}
void updateLeds(int cnt) {
if(cnt > sizeof(pins)) cnt = sizeof(pins);
for(int pin : pins) {
digitalWrite(pin, LOW);
}
for(int i = 0; i < cnt; i++) {
digitalWrite(pins[i], HIGH);
}
}
void loop() {
if(Serial.available() > 0) {
Serial.println("[RECV]");
count = Serial.parseInt();
Serial.read();
}
updateLeds(count);
delay(50);
}
解决方案
正如 Julian 在评论中提到的那样,启用 DTR 就可以了。
...
dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
...
推荐阅读
- firebase - 带有来自 firestore 的子集合的 Flutter 显示集合
- java - 如何编写面向对象的程序来实例化具有超类、子类和接口的对象和接口
- ansible - 使用jinja2模板时ansible中的未定义变量错误
- puppeteer - puppeteer semantic-ui-react 下拉菜单如何选择选项
- gnuradio - GNU Radio Companion & multimon-ng:标识符和有用的信号静音
- python - 在 Python 中使用语音识别时出错
- unity3d - Unity 中的黑色暂存屏幕
- iis - iis 将 PDF URL 重定向到另一个 URL - 空格问题
- mysql - Laravel Eloquent 关系 Empty 和 JSON
- javascript - Puppeteer 不断出现错误:超过导航超时:超过 30000 毫秒