简体   繁体   English

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

[英]Issue with C++ Serial Communication on Windows

I'm trying to communicate with an Arduino using C++ on windows.我正在尝试在 Windows 上使用 C++ 与 Arduino 通信。

The Arduino is waiting for a number and will light up an amount of LEDs specified by the received number. Arduino 正在等待一个数字,并将点亮由接收到的数字指定的 LED 数量。 I can successfully open a port and send data to the Arduino, however there is some strange behavior.我可以成功打开一个端口并将数据发送到 Arduino,但是有一些奇怪的行为。

When I use the built-in serial console in the Arduino IDE and send, for example, "8" the Arduino reacts correctly.例如,当我在 Arduino IDE 中使用内置串行控制台并发送“8”时,Arduino 会做出正确反应。 (The data sent is 38 0A according to a serial sniffer). (根据串行嗅探器发送的数据为38 0A )。

When I run my C++ code, the data sent is also 38 0A however the Arduino does not react to it.当我运行我的 C++ 代码时,发送的数据也是38 0A但是 Arduino 没有反应。

My PC side C++ code:我的 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;
}

And here is the Arduino code although I assume the problem will be on the PC side...这是 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);
}

As Julian mentioned in the comments, enabling DTR did the trick.正如朱利安在评论中提到的,启用 DTR 可以解决问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM