首页 > 解决方案 > 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);
}

标签: c++windowsarduinoserial-port

解决方案


正如 Julian 在评论中提到的那样,启用 DTR 就可以了。

...
dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
...

推荐阅读