27,374
社区成员
发帖
与我相关
我的任务
分享
#include<windows.h>
#include<stdio.h>
#include<stdlib.h>
HANDLE hComm;
BOOL openport(char*portname)
{
HANDLE hComm;
hComm = CreateFileA(portname, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
if (hComm == INVALID_HANDLE_VALUE)
{
CloseHandle(hComm);
return FALSE;
}
else
return TRUE;
}
BOOL DBC_set()
{
SetupComm(hComm, 1024, 1024) ;// 通信设备的句柄, 输入缓冲区的大小(字节数)unsigned long, 输出缓冲区的大小(字节数)unsigned long
//设置缓冲区大小
DCB ComDCB; //串口设备控制块
GetCommState(hComm, &ComDCB);
ComDCB.BaudRate = 9600; //波特率为9600
ComDCB.ByteSize = 8; //每个字节有8位
ComDCB.Parity = EVENPARITY; //偶校验
ComDCB.StopBits = ONESTOPBIT; //一个停止位
BOOL result = SetCommState(hComm,&ComDCB);//重新写入
PurgeComm(hComm, PURGE_TXCLEAR | PURGE_RXCLEAR);//清空读写缓冲区
if ( !result )
return FALSE;
else
return TRUE;
}
BOOL Timeouts_set()
{
COMMTIMEOUTS TimeOuts;
GetCommTimeouts(hComm, &TimeOuts);
//重设读超时
TimeOuts.ReadIntervalTimeout = 1000;
TimeOuts.ReadTotalTimeoutMultiplier = 500;
TimeOuts.ReadTotalTimeoutConstant = 5000;
//设定写超时
TimeOuts.WriteTotalTimeoutMultiplier = 500;
TimeOuts.WriteTotalTimeoutConstant = 2000;
BOOL result = SetCommTimeouts(hComm, &TimeOuts);
if (!result)
return FALSE;
else
return TRUE;
}
int read()
{
COMSTAT ComStat;
DWORD dwError = 0; ClearCommError(hComm, &dwError, &ComStat);
//上式执行完后,ComStat.cbInQue就是串口中当前含有的数据字节个数,我们利用此数值就可以用ReadFile()函数去读串口中的数据了。
unsigned char ucRxBuff[1024];
DWORD dwRead;
OVERLAPPED osReader; memset(&osReader, 0, sizeof(OVERLAPPED));//定义一个OVERLAPPED结构,并清零
osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);//创建一个事件
// Create the overlapped event. Must be closed before exiting to avoid a handle leak.
BOOL bReadStatus = ReadFile(hComm, ucRxBuff,ComStat.cbInQue, &dwRead, &osReader);
/*ReadFile(hComm, ucRxBuff, ComStat.cbInQue,&dwRead, &osReader)
句柄hComm,存储读入数据的地址ucRxBuff,准备读入数据的字节数ComStat.cbInQue,实际读出的字节数的变量指针&dwRead,重叠结构指针&osReader。*/
if (osReader.hEvent == NULL)
{
printf(" Error creating overlapped event\n.");
return 0;
}
if (!bReadStatus) //如果ReadFile函数返回FALSE
{
if (GetLastError() == ERROR_IO_PENDING)
//GetLastError()函数返回ERROR_IO_PENDING,表明串口正在进行读操作
{
WaitForSingleObject(osReader.hEvent, 2000);
//使用WaitForSingleObject函数等待,直到读操作完成或延时已达到2秒钟
//当串口读操作进行完毕后,m_osRead的hEvent事件会变为有信号
PurgeComm(hComm, PURGE_TXABORT |
PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
return dwRead;
}
else
printf("ERROR in communications.\n");
return 0;
}
printf("Handle a successful read.\n");
PurgeComm(hComm, PURGE_TXABORT |
PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
return dwRead;
}
void main()
{
BOOL open;
open = openport("COM3");
if (open)
printf("open comport successfully.\n");
system("pause");
BOOL set;
set = DBC_set();
if (set)
printf("set DCB successfully.\n");
system("pause");
int byteread;
byteread = read();
printf("%d", byteread);
}