码迷,mamicode.com
首页 > Windows程序 > 详细

Win32 API UART编程

时间:2016-08-07 18:31:43      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

    下面是一个使用Win32 API进行UART编程的简单示例。

 1 #include <windows.h>
 2 #include <stdio.h>
 3 
 4 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
 5 {
 6     HANDLE hCom;
 7     DWORD dwError;
 8     BYTE buf;
 9     DWORD nBytes;
10     
11     printf("%s\n", lpCmdLine);
12     
13     hCom = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
14     
15     if (hCom == (HANDLE)-1) {
16         dwError = GetLastError();
17         printf("Error = %d\n", dwError);
18         return 0;
19     }
20     
21     DCB dcb;
22     GetCommState(hCom, &dcb);
23     dcb.BaudRate = 9600;
24     dcb.ByteSize = 8;
25     dcb.Parity = NOPARITY;
26     dcb.StopBits = 1;
27     dcb.fBinary = TRUE;
28     dcb.fParity = TRUE;
29     SetCommState(hCom, &dcb);
30     SetupComm(hCom, 1024, 1024);
31     PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
32     
33     COMMTIMEOUTS to;
34     memset(&to, 0, sizeof(to));
35     to.ReadIntervalTimeout = 10;
36     SetCommTimeouts(hCom, &to);
37     
38     WriteFile(hCom, &buf, sizeof(buf), &nBytes, NULL);
39     ReadFile(hCom, &buf, sizeof(buf), &nBytes, NULL);
40 
41     CloseHandle(hCom);
42     return 0;
43 }

 

Win32 API UART编程

标签:

原文地址:http://www.cnblogs.com/lyuyangly/p/5746515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!