本程序采用简单的同步串行通信,分为几个阶段:
1、打开串口
2、配置串口
3、设置串口输入输出缓存区大小
4、设置串口读写超时(若不设置超时,读写时会等待读写函数返回)
5、发送字符串(每次发送前清空发送缓存区)
6、接收字符(每次接收前清空接收缓存区)
7、关闭串口
bmLightComm.h
1 #pragma once 2 #include "stdio.h" 3 #include "stdbool.h" 4 #include "windows.h" 5 #include "tchar.h" 6 7 class bmLightComm 8 { 9 public: 10 bmLightComm(); 11 ~bmLightComm(); 12 bool openPort(const char* portNum); 13 bool setupPort(DWORD baudrate, BYTE bytesize, BYTE stopbits, DWORD fparity, BYTE parity); 14 bool setBufferAreaSize(DWORD inQueue, DWORD outQueue); 15 bool setComTimeout(DWORD readinttim, DWORD readToltimM, DWORD readToltimC,DWORD writeToltimM, DWORD writeToltimC); 16 bool purgePort(DWORD flags); 17 bool closePort(); 18 19 bool sendBuff(const char* datas, unsigned int len); 20 char readBuff(); 21 22 private: 23 HANDLE mCom; 24 };
bmLightComm.cpp
1 #include "bmLightComm.h" 2 #include <iostream> 3 4 5 bmLightComm::bmLightComm() 6 { 7 } 8 9 10 bmLightComm::~bmLightComm() 11 { 12 } 13 14 bool bmLightComm::openPort(const char* portNum) 15 { 16 printf("open the com %s\n", portNum); 17 18 mCom = CreateFileA(portNum, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); 19 std::cout << GetLastError() << std::endl; 20 if (mCom == INVALID_HANDLE_VALUE) 21 { 22 printf("failed to open com %s %d\n", portNum, GetLastError()); 23 return false; 24 } 25 else 26 { 27 printf("cam %s opened\n", portNum); 28 return true; 29 } 30 } 31 32 bool bmLightComm::setupPort(DWORD baudrate, BYTE bytesize, BYTE stopbits, DWORD fparity, BYTE parity) 33 { 34 printf("set up port\n"); 35 36 DCB mDcb; 37 if (!GetCommState(mCom, &mDcb)) 38 { 39 printf("get com state failed %d\n", GetLastError()); 40 return false; 41 } 42 43 mDcb.BaudRate = baudrate; 44 mDcb.fParity = fparity; 45 mDcb.Parity = parity; 46 mDcb.StopBits = stopbits; 47 mDcb.ByteSize = bytesize; 48 49 if (!SetCommState(mCom, &mDcb)) 50 { 51 printf("failed to set up com state %d\n", GetLastError()); 52 return