C++ 串口通信程序
#include "windows.h"
#include <iostream>
#include <TCHAR.H>
#include <string.h>
using namespace std;
HANDLE handle_file;
int serial_open(LPCWSTR COMx, int baudrate)
{
handle_file = CreateFile(COMx, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (handle_file == INVALID_HANDLE_VALUE)
{
printf("打开串口失败!\n");
return FALSE;
}
SetupComm(handle_file, 1024, 1024);
COMMTIMEOUTS TimeOuts;
TimeOuts.ReadIntervalTimeout=1000;
TimeOuts.ReadTotalTimeoutMultiplier=500;
TimeOuts.ReadTotalTimeoutConstant=5000;
TimeOuts.WriteTotalTimeoutMultiplier=500;
TimeOuts.WriteTotalTimeoutConstant = 2000;
SetCommTimeouts(handle_file, &TimeOuts);
DCB device_control_block;
GetCommState(handle_file, &device_control_block);
device_control_block.BaudRate = baudrate;
device_control_block.ByteSize = 8;
device_control_block.Parity = NOPARITY;
device_control_block.StopBits = ONESTOPBIT;
SetCommState(handle_file, &device_control_block);
PurgeComm(handle_file, PURGE_TXCLEAR | PURGE_RXCLEAR);
return TRUE;
}
int serial_read_write()
{
COMSTAT com_start;
DWORD errors;
ClearCommError(handle_file, &errors, &com_start);
char buffer[128];
DWORD buffer_bytes = sizeof(buffer);
memset(buffer, 0, sizeof(buffer));
int result = 0;
printf("请输入需要发送的数据:");
gets_s(buffer);
result = WriteFile(handle_file, buffer, buffer_bytes, &buffer_bytes, NULL);
if (!result)
{
printf("写串口失败!\n");
return FALSE;
}
printf("发送数据:%s。\n", buffer);
memset(buffer, 0, sizeof(buffer));
Sleep(100);
result = ReadFile(handle_file, buffer, buffer_bytes, &buffer_bytes, NULL);
if (!result)
{
printf("读串口失败!\n");
return FALSE;
}
printf("接收数据:%s\n", buffer);
memset(buffer, 0, sizeof(buffer));
Sleep(100);
PurgeComm(handle_file, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
return TRUE;
}
void serial_close(void)
{
CloseHandle(handle_file);
}
int main()
{
char serial_port[20];
memset(serial_port, 0, sizeof(serial_port));
printf("请输入串口号:");
gets_s(serial_port);
printf("串口设置为:%s\n", serial_port);
serial_open(LPCWSTR(serial_port), 9600);
serial_read_write();
serial_close();
system("pause");
return 0;
}