windows串口通讯(读和写,很方便!!)

来源:互联网 发布:词典软件 推荐 编辑:程序博客网 时间:2024/06/08 17:08

太忙太忙了,正好有需要,把代码贴上来备用,也给大家参考参考,实现了windows串口通讯的读和写


字符类型转换喝了一壶(大概五分钟吧....)




#include <iostream>#include <Windows.h>#include<string>#include<thread>  using namespace std;HANDLE 初始化串口(char *szStr) {//const char temp[5]="COM4";WCHAR wszClassName[5];memset(wszClassName, 0, sizeof(wszClassName));MultiByteToWideChar(CP_ACP, 0, szStr, strlen(szStr) + 1, wszClassName,sizeof(wszClassName) / sizeof(wszClassName[0]));HANDLE hCom1 = CreateFile(wszClassName,//COM1口GENERIC_READ | GENERIC_WRITE, //允许读和写0, //独占方式NULL,OPEN_EXISTING, //打开而不是创建0, //同步方式NULL);//if (hCom1 == (HANDLE)-1)if (hCom1 == INVALID_HANDLE_VALUE){printf("打开COM失败!\n");//return FALSE;}else{printf("COM打开成功!\n");}SetupComm(hCom1, 1024, 1024); //输入缓冲区和输出缓冲区的大小都是1024COMMTIMEOUTS TimeOuts;//设定读超时TimeOuts.ReadIntervalTimeout = 100;TimeOuts.ReadTotalTimeoutMultiplier = 5000;TimeOuts.ReadTotalTimeoutConstant = 5000;//设定写超时TimeOuts.WriteTotalTimeoutMultiplier = 500;TimeOuts.WriteTotalTimeoutConstant = 2000;SetCommTimeouts(hCom1, &TimeOuts); //设置超时DCB dcb;GetCommState(hCom1, &dcb);dcb.BaudRate = 9600; //波特率为9600dcb.ByteSize = 8; //每个字节有8位dcb.Parity = NOPARITY; //无奇偶校验位dcb.StopBits = ONESTOPBIT; //1个停止位SetCommState(hCom1, &dcb);return hCom1;}int main() {/*发送模块string result="233";WriteFile(hCom1, result.data(), result.size(), NULL, NULL);*/HANDLE hCom1 = 初始化串口("COM4");char 缓冲[1000];DWORD readsize;int n = 100;while(n--){ReadFile(hCom1, 缓冲, 13, &readsize, NULL);cout <<"重量为:"<< 缓冲;}system("pause");}


原创粉丝点击