用C++写一个串口的代码
时间: 2023-03-14 14:08:46 浏览: 90
#include <stdio.h>
#include <Windows.h>int main()
{
// 声明变量
HANDLE hComm;
BOOL Status;
DWORD dwEventMask;
char ComPortName[] = "COM1"; // 创建串口句柄
hComm = CreateFile( ComPortName,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0); // 设置串口的读写参数
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
Status=GetCommState(hComm, &dcbSerialParams); dcbSerialParams.BaudRate=CBR_9600;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
SetCommState(hComm, &dcbSerialParams); // 设置超时时间
COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=50;
timeouts.ReadTotalTimeoutConstant=50;
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.WriteTotalTimeoutConstant=50;
timeouts.WriteTotalTimeoutMultiplier=10;
SetCommTimeouts(hComm, &timeouts); // 设置串口事件
SetCommMask(hComm, EV_RXCHAR);
WaitCommEvent(hComm, &dwEventMask, NULL); // 关闭串口
CloseHandle(hComm); return 0;
}我用C语言写出了一个串口代码:#include <stdio.h>#include <Windows.h>int main() { // 声明变量HANDLE hComm;BOOL Status;DWORD dwEventMask;char ComPortName[] = "COM1"; // 创建串口句柄hComm = CreateFile(ComPortName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); // 设置串口的读写参数DCB dcbSerialParams = {0};dcbSerialParams.DCBlength = sizeof(dcbSerialParams);Status = GetCommState(hComm, &dcbSerialParams);dcbSerialParams.BaudRate = CBR_9600;dcbSerialParams.ByteSize = 8;dcbSerialParams.StopBits = ONESTOPBIT;dcbSerialParams.Parity = NOPARITY;SetCommState(hComm, &dcbSerialParams); // 设置超时时间COMMTIMEOUTS timeouts = {0};timeouts.ReadIntervalTimeout = 50;timeouts.ReadTotalTimeoutConstant = 50;timeouts.ReadTotalTimeoutMultiplier = 10;timeouts.WriteTotalTimeoutConstant = 50;timeouts.WriteTotalTimeoutMultiplier = 10;SetCommTimeouts(hComm, &timeouts); // 设置串口事件SetCommMask(hComm, EV_RXCHAR);WaitCommEvent(hComm, &dwEventMask, NULL); // 关闭串口CloseHandle(hComm);return 0;}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)