我从 arduino 的串口读取数据。我在互联网上找到了代码,但它的工作原理很奇怪。
读取时触发读取数据条件,否则不触发。
while(1)
{
// memset(szBuff,0,sizeof(szBuff));
if( ReadFile(hSerial, LPVOID(szBuff), 1, &dwBytesRead, NULL))
{
cout << szBuff;
}
else
cout << "noooooooo";
}
==================================
#include<Windows.h>
#include<stdio.h>
#include<iostream>
using namespace std;
void main()
{
HANDLE hSerial;
hSerial = CreateFile(TEXT("COM3"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
//FILE_FLAG_OVERLAPPED,
NULL);
if ( hSerial == INVALID_HANDLE_VALUE)
{
printf("Error initializing handler");
}
else
{
// Set the parameters of the handler to the serial port.
DCB dcb = {0};
dcb.DCBlength = sizeof(dcb);
if ( !GetCommState(hSerial, &dcb) )
{
printf("Error setting parameters");
}
//FillMemory(&dcb, sizeof(dcb), 0);
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity = NOPARITY;
if ( !SetCommState(hSerial, &dcb) )
{
// error setting serial port state.
}
// Tell the program not to wait for data to show up
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 0;//20;
timeouts.ReadTotalTimeoutConstant = 0;//20;
timeouts.ReadTotalTimeoutMultiplier = 0;//50;
timeouts.WriteTotalTimeoutConstant = 0;//100;
timeouts.WriteTotalTimeoutMultiplier = 0;//100;
//if ( !SetCommTimeouts(hSerial, &timeouts) )
//{
// printf("Error setting the timeouts");
//}
char szBuff[2] = "";
DWORD dwBytesRead = 0;
int i = 0;
char test[] = "B\n";
// int maxSamples = 10;
// DWORD dwCommStatus;
// WriteFile(hSerial, test, 2, &dwBytesRead, NULL);
// SetCommMask(hSerial,EV_RXCHAR);
// WaitCommEvent (hSerial, &dwCommStatus, 0);
// if (dwCommStatus & EV_RXCHAR)
{
while(1)
{
// memset(szBuff,0,sizeof(szBuff));
if( ReadFile(hSerial, LPVOID(szBuff), 1, &dwBytesRead, NULL))
{
cout<<szBuff;
}
else
cout << "noooooooo";
}
}
CloseHandle(hSerial);
}
}
如果成功,该函数
ReadFile
返回 TRUE,如果在读取文件时发生错误,则返回 FALSE。 ReadFile 函数,文件 API