串口通信一般为三步:打开串口,串口设置,向串口发送数据或者向串口接受数据:
void OpenComm()
{
hCom=CreateFile("COM3",GENERIC_READ|GENERIC_WRITE,0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
NULL);
}
void SetComm()
{
SetupComm(hCom,1024,1024);
DCB dcb;
dcb.BaudRate=115200;
dcb.fParity=NOPARITY;
dcb.ByteSize=8;
dcb.StopBits=ONESTOPBIT;
GetCommState(hCom,&dcb);
if(!GetCommState(hCom,&dcb)){
std::cerr<
return;
}
if(!SetCommMask(hCom,EV_RXCHAR|EV_TXEMPTY)){
std::cerr<
}
}
void SendMessageOut(const BYTE snd[],int len)
{
DWORD factdata=100;
DWORD res=0;
wOverLapped.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL); //创建事件
BOOL tempflag = WriteFile(hCom,snd,len,&factdata,&wOverLapped);//在数据缓冲Ipbuffer不知道是否有问题
if(tempflag!=0)
{
std::cerr<
res=WaitForSingleObject(wOverLapped.hEvent,5000);
WriteFile(hCom,snd,len,&factdata,&wOverLapped);
}
if(res!=WAIT_OBJECT_0)
std::cout<
}
这是向串口发送数据的,主要函数为WriteFile();读取ReadFile(),具体用法 百度一下