我需要将数据从计算机传输到Arduino Uno,然后从Arduino接收其他数据到计算机。我在 Arduino 和使用 C++ 的计算机上编写了实现此逻辑的代码。不幸的是,代码只有在刷新 Arduino Uno 固件后才能立即正常工作。但是,如果您断开Arduino与COM端口的连接,然后再次连接,计算机将无法将数据传输到开发板。可能是什么原因?计算机代码
#include <windows.h>
#include <iostream>
using namespace std;
HANDLE serial;
char outData[] = "s";
DWORD outDataSize = sizeof(outData);
DWORD outBytesWritten;
void SerialRead() {
DWORD inputDataSize;
char receivedChar;
while (true) {
ReadFile(serial, &receivedChar, 1, &inputDataSize, 0);
if (inputDataSize > 0) cout << receivedChar;
}
}
int main(){
cout << ">> begin\n";
LPCTSTR name = L"COM4";
DCB sParams;
serial = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (serial == INVALID_HANDLE_VALUE){
if (GetLastError() == ERROR_FILE_NOT_FOUND){
cout << ">> serial port does not exist\n";
CloseHandle(serial);
return 0;
}
cout << ">> some other error occurred\n";
CloseHandle(serial);
return 0;
}
if (!GetCommState(serial, &sParams)) {
cout << ">> getting state error\n";
CloseHandle(serial);
return 0;
}
sParams.BaudRate = CBR_9600;
sParams.ByteSize = 8;
sParams.StopBits = ONESTOPBIT;
sParams.Parity = NOPARITY;
if (!SetCommState(serial, &sParams)) {
cout << ">> error setting serial port state\n";
CloseHandle(serial);
return 0;
}
BOOL write = WriteFile(serial, outData, outDataSize, &outBytesWritten, NULL);
cout << write;
cout << ">> reading\n";
while (true) SerialRead();
return 0;
}
Arduino Uno 代码
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.read() == 's') Serial.print('e');
}
在从计算机发送数据之前添加了三秒的暂停
Sleep(3000)。一切顺利。