首页 > 代码库 > WindowsAPI操作串口
WindowsAPI操作串口
#include <windows.h> #include <stdio.h> int main() { //1.打开串口 HANDLE hCom; hCom = CreateFile("COM1", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hCom ==(HANDLE)-1 ) printf("打开串口失败!\n"); else printf("打开串口成功!\n"); //2.初始化串口 DCB dcb; GetCommState(hCom, &dcb); dcb.BaudRate = 9600;//波特率 //dcb.fParity = 0;//奇偶校验使能 dcb.ByteSize = 8;//数据位 dcb.Parity = NOPARITY;//奇偶校验 dcb.StopBits = ONESTOPBIT;//停止位 SetCommState(hCom, &dcb); SetupComm(hCom, 1024, 1024); COMMTIMEOUTS TimeOuts; //设定读超时 TimeOuts.ReadIntervalTimeout = 1000; TimeOuts.ReadTotalTimeoutConstant = 5000; TimeOuts.ReadTotalTimeoutMultiplier = 500; //设定写超时 TimeOuts.WriteTotalTimeoutConstant = 2000; TimeOuts.WriteTotalTimeoutMultiplier = 500; SetCommTimeouts(hCom, &TimeOuts); //清空缓冲区 PurgeComm(hCom, PURGE_TXCLEAR|PURGE_RXCLEAR); Sleep(500); //3.读写串口 unsigned char buf[10] = {0x00, 0x06, ‘D‘, ‘A‘, ‘T‘, ‘A‘}; BOOL bWriteStat; DWORD dwBytesWrite = 6; bWriteStat = WriteFile(hCom, buf, dwBytesWrite, &dwBytesWrite, NULL); if (!bWriteStat) { printf("写串口失败!\n"); } else printf("写串口成功!\n"); unsigned char rBuf[1024]; BOOL bReadStat; DWORD dwBytesRead; bReadStat = ReadFile(hCom, rBuf, 1024, &dwBytesRead, NULL); if (!bReadStat) { printf("读串口失败!\n"); } else { printf("读串口成功!\n"); } for (DWORD j = 0; j < dwBytesRead; j++) { printf("%x ", rBuf[j]); } printf("\n"); //4.关闭串口 CloseHandle(hCom); return 0; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。