#include <windows.h>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
const char* StopBitsFromInt(int s) {
switch (s) {
case ONESTOPBIT:
return "1 stop bits";
case ONE5STOPBITS:
return "5 stop bits";
case TWOSTOPBITS:
return "2 stop bits";
}
return "Unknown stop bits";
}
const char* ParityFromInt(int s) {
switch (s) {
case NOPARITY:
return "no-parity";
}
return "other parity";
}
HANDLE MustOpenCommport() {
HANDLE hComm = CreateFile(L"\\\\.\\COM4", //port name
GENERIC_READ | GENERIC_WRITE, //Read/Write
0, // No Sharing
NULL, // No Security
OPEN_EXISTING,// Open existing port only
0, // Non Overlapped I/O
NULL); // Null for Comm Devices
if (hComm == INVALID_HANDLE_VALUE) {
std::cerr << "Error in opening serial port" << std::endl;
ExitProcess(-1);
} else {
//std::cout << "opening serial port successful" << std::endl;
}
//CloseHandle(hComm);//Closing the Serial Port
return hComm;
}
void ShowCommStatus(HANDLE hComm) {
DCB dcbParams = { sizeof(DCB) };
BOOL status = GetCommState(hComm, &dcbParams);
std::cout << "Baudrate:" << dcbParams.BaudRate << std::endl;
std::cout << "Parity:" << ParityFromInt(dcbParams.fParity) << std::endl;
std::cout << "ByteSize:" << int(dcbParams.ByteSize) << std::endl;
std::cout << "StopBit:" << StopBitsFromInt(dcbParams.StopBits) << std::endl;
}
int main() {
HANDLE hComm = MustOpenCommport();
DCB dcbParams = { sizeof(DCB) };
//std::cout << "setting ...\n\n" << std::endl;
dcbParams.BaudRate = CBR_128000;// CBR_256000;// CBR_9600;
dcbParams.ByteSize = 8;
dcbParams.StopBits = ONESTOPBIT; // 1
dcbParams.Parity = NOPARITY;
BOOL setOK = SetCommState(hComm, &dcbParams);
if (!setOK) {
std::cerr << "error setting comm-state" << std::endl;
ExitProcess(-1);
}
//ShowCommStatus(hComm);
if (!SetCommMask(hComm, EV_RXCHAR)) {
std::cerr << "error_category set-comm mask" << std::endl;
ExitProcess(-1);
}
while (1) {
DWORD dwEventMask = 0;
DWORD status = WaitCommEvent(hComm, &dwEventMask, NULL);
if (!(dwEventMask&EV_RXCHAR)) {
std::cout << "Unknown event" << std::endl;
continue;
}
std::cout << "-->>" << std::endl;
DWORD bytesRead = 0;
//std::string buffer;
char tempChar;
do {
if (!ReadFile(hComm, &tempChar, sizeof(tempChar), &bytesRead, NULL)) {
std::cerr << "read failed" << std::endl;
break;
}
if (bytesRead > 0) {
//buffer += tempChar;
std::cout << tempChar;
} else {
break;
}
//std::cout << buffer;
} while (1);
}
CloseHandle(hComm);
}
参考链接:
http://xanthium.in/Serial-Port-Programming-using-Win32-API
这里有一个问题就是 一旦进入ReadFile的那个while循环, 只要不是让设备关闭(如掉电), ReadFile就不会失败。