我为微控制器编程串行通信,并使用UART进行编程。要连接到UART,请使用包含FTDI芯片的USB转串口转换器。问题是TX 和RX 正在发送字节(使用Salea Logic进行测试)。这怎么可能?对于发送字节,我使用了WriteFile,如MSDN中所述。
感谢您的帮助!
char bytes_to_send[5];
bytes_to_send[0] = 0x48;
bytes_to_send[1] = 31;
bytes_to_send[2] = 31;
bytes_to_send[3] = 31;
bytes_to_send[4] = 13;
HANDLE hComm;
hComm = CreateFile(L"COM4", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hComm == INVALID_HANDLE_VALUE) {
std::cout << "error\n";
}
else {
std::cout << "connected \n";
DCB dcbParams = { 0 };
dcbParams.BaudRate = CBR_115200;
dcbParams.ByteSize = 8;
dcbParams.fParity = NOPARITY;
dcbParams.StopBits = ONESTOPBIT;
dcbParams.fDtrControl = DTR_CONTROL_ENABLE;
if (!SetCommState(hComm, &dcbParams))
{
printf("ALERT: Could not set Serial Port parameters");
}
else
{
//Flush any remaining characters in the buffers
PurgeComm(hComm, PURGE_RXCLEAR | PURGE_TXCLEAR);
//We wait 2s as the arduino board will be reseting
Sleep(4000);
std::cout << "everything is ok... \n";
DWORD bytes_written, total_bytes_written = 0;
fprintf(stderr, "Sending bytes...");
if (!WriteFile(hComm, bytes_to_send, 5, &bytes_written, NULL))
{
fprintf(stderr, "Error\n");
CloseHandle(hComm);
return 1;
}
std::cout << "all bytes sent" << std::endl;
//Flush any remaining characters in the buffers
PurgeComm(hComm, PURGE_RXCLEAR | PURGE_TXCLEAR);
char buffer[255];
DWORD bytesRead;
/*while (int i=ReadFile(hComm, buffer, 1, &bytesRead, NULL)) {
std::cout << "Bytes read" + (char)i << std::endl;
std::cout << buffer << std::endl;
}*/
}
}