RS232异步通信实例

最近这几天在研究RS232串口通信,看了很多网上的资料,解释RS232引脚或者同步异步的文字描述很多,案例很少,而且感觉很乱,所以就自己弄出来,然后发出来一起学习,这个案例主要是异步通信的设置上,下一篇等我把串口的硬件流控研究透就会发出来。读写是两个线程,有一些判断返回值的语句没有加上来

1、打开串口
hComm = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
2、串口初始化
SetupComm(hComm, 1024, 1024);
GetCommState(hComm, &dcb);
dcb.BaudRate = 115200;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
SetCommState(hComm, &dcb);
3、添加串口事件
memset(&ov, 0, sizeof(OVERLAPPED));
ov.hEvent = CreateEvent(NULL, FALSE, TRUE, NULL);
ov.Offset = 0;
ov.OffsetHigh = 0;

memset(&comstat, 0, sizeof(comstat));
ClearCommError(hComm, &dwErrorFlags, &comstat);
4、创建线程
hThread = CreateThread(NULL, 0, ThreadRead, 0, 0, &threadID);
5、写函数
n1 = WriteFile(hComm, buf, sizeof(buf), &dwWritenSize, &ov);
if(GetLastError() != 997)
{
printf("%d ", GetLastError());
printf("ERROR: WriteFile error !!!\n");
}

wait = WaitForSingleObject(ov.hEvent, 1000);
switch(wait)
{
case WAIT_OBJECT_0:
case WAIT_TIMEOUT:
break;
case WAIT_FAILED:
printf("嬪暱澷澚両\n");
break;
Default:
break;
}
6、读函数
ReadFile(hComm, buffer, wCount, &read, &ov);
if(GetLastError() != 997)
{
printf("%d ", GetLastError());
printf("ERROR ReadFile error\n");
}

wait = WaitForSingleObject(ov.hEvent, 1000);
switch(wait)
{
case WAIT_OBJECT_0:
printf("%s\n", buffer);
memset(buffer, 0, sizeof(buffer));
break;

case WAIT_TIMEOUT:
break;

case WAIT_FAILED:
printf("嬪暱澷澚両\n");
break;

Default:
break;
}

if(0 == comstat.cbInQue)
{
continue;
}

你可能感兴趣的:(RS232异步通信)