C++ 串口通信程序

C++ 串口通信程序

#include "windows.h"
#include   
#include    
#include 

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; //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_open(_T("COM1"), 9600); //打开串口,波特率
	serial_read_write(); //接收发送字符
	serial_close(); //关闭串口
	system("pause");
	return 0;
}

你可能感兴趣的:(C++,c++,串口通信)