// CSerialPort.h
#pragma once
#include <windows.h>
class CSerialPort {
public:
CSerialPort();
~CSerialPort();
BOOL Open(LPCTSTR lpszPortName, DWORD dwBaudRate, BYTE byDataBits, BYTE byParity, BYTE byStopBits);
void Close();
BOOL Write(const BYTE* pBuffer, DWORD dwBytesToWrite, DWORD* pdwBytesWritten);
BOOL Read(BYTE* pBuffer, DWORD dwBytesToRead, DWORD* pdwBytesRead);
private:
HANDLE m_hComm;
};
// CSerialPort.cpp
#include "stdafx.h"
#include "CSerialPort.h"
CSerialPort::CSerialPort() : m_hComm(INVALID_HANDLE_VALUE) {}
CSerialPort::~CSerialPort() {
Close();
}
BOOL CSerialPort::Open(LPCTSTR lpszPortName, DWORD dwBaudRate, BYTE byDataBits, BYTE byParity, BYTE byStopBits) {
m_hComm = CreateFile(lpszPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (m_hComm == INVALID_HANDLE_VALUE) {
return FALSE;
}
DCB dcbSerialParams = { 0 };
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(m_hComm, &dcbSerialParams)) {
CloseHandle(m_hComm);
return FALSE;
}
dcbSerialParams.BaudRate = dwBaudRate;
dcbSerialParams.ByteSize = byDataBits;
dcbSerialParams.Parity = byParity;
dcbSerialParams.StopBits = byStopBits;
if (!SetCommState(m_hComm, &dcbSerialParams)) {
CloseHandle(m_hComm);
return FALSE;
}
COMMTIMEOUTS timeouts = { 0 };
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(m_hComm, &timeouts)) {
CloseHandle(m_hComm);
return FALSE;
}
return TRUE;
}
void CSerialPort::Close() {
if (m_hComm != INVALID_HANDLE_VALUE) {
CloseHandle(m_hComm);
m_hComm = INVALID_HANDLE_VALUE;
}
}
BOOL CSerialPort::Write(const BYTE* pBuffer, DWORD dwBytesToWrite, DWORD* pdwBytesWritten) {
return WriteFile(m_hComm, pBuffer, dwBytesToWrite, pdwBytesWritten, NULL);
}
BOOL CSerialPort::Read(BYTE* pBuffer, DWORD dwBytesToRead, DWORD* pdwBytesRead) {
return ReadFile(m_hComm, pBuffer, dwBytesToRead, pdwBytesRead, NULL);
}