我正在尝试使用原始WinAPI命令通过USB将串行消息发送到Arduino Uno。当使用小于115200的波特率时,它工作得非常好。但是,当我以115200波特率发送时,会在我发送的数据前面发送两个额外的字节,但仅限于连接到Arduino后的第一条消息。例如,如果我连接到Arduino并发送两个字节“Hi”,则Arduino会收到“ððHi”。如果我再次发送“Hi”,Arduino就会收到“Hi”。 (额外的字节通常是ð(0xF0),但并非总是如此。)
我知道我的电脑和Arduino能够以115200波特进行通信,因为其他程序如avrdude和Arduino IDE的串口监听器都可以做得很好。
我尝试清除两侧的RX和TX缓冲区,并且还搞乱了DCB设置,没有任何效果。有谁知道可能导致这种情况的原因?
谢谢!
以下是重现问题的代码:
电脑方:
#include <Windows.h>
int main()
{
// Open device as non-overlapped
HANDLE device = CreateFile(L"COM6",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
// Make sure the device is valid
if(device == INVALID_HANDLE_VALUE)
return 0;
DCB dcb;
if(!GetCommState(device, &dcb))
return 0;
dcb.fOutX = 0;
dcb.fInX = 0;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fNull = 0;
dcb.BaudRate = CBR_115200;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if(!SetCommState(device, &dcb))
return 0;
COMMTIMEOUTS Timeouts = { 0 };
Timeouts.ReadTotalTimeoutConstant = 1000;
Timeouts.WriteTotalTimeoutConstant = 1000;
if(!SetCommTimeouts(device, &Timeouts))
return 0;
char *buf = "abcdef";
DWORD written;
WriteFile(device, buf, 6, &written, NULL);
DWORD read;
char inbuf[100];
ReadFile(device, inbuf, 100, &read, NULL);
// When I get the result inbuf, it has 8 bytes: {0xF0, 0xF0, a, b, c, d, e, f}
// Doing a 2nd set of Write/ReadFile, with the same message, gives the correct response
return 0;
}
Arduino方面:
void setup()
{
Serial.begin(115200);
}
void loop()
{
if(Serial.available())
Serial.write(Serial.read());
}