Windows 上的 C++ 串行通信问题

Issue with C++ Serial Communication on Windows

我正尝试在 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;
...