cserialport类源代码
时间: 2023-08-22 12:02:52 浏览: 153
cserialport类是用于在计算机与串行端口之间进行数据通信的一个类。以下是该类的源代码:
```cpp
class CSerialPort {
public:
CSerialPort();
~CSerialPort();
BOOL OpenPort(int portNum, int baudRate);
void ClosePort();
BOOL WriteData(const unsigned char* pData, int dataSize);
BOOL ReadData(unsigned char* pData, int bufferSize, int& bytesRead);
private:
HANDLE m_hSerialPort;
BOOL m_isOpen;
};
CSerialPort::CSerialPort()
{
m_hSerialPort = NULL;
m_isOpen = FALSE;
}
CSerialPort::~CSerialPort()
{
ClosePort();
}
BOOL CSerialPort::OpenPort(int portNum, int baudRate)
{
if (m_isOpen)
return FALSE;
char portName[10];
sprintf(portName, "COM%d", portNum);
m_hSerialPort = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (m_hSerialPort == INVALID_HANDLE_VALUE)
return FALSE;
DCB dcb;
memset(&dcb, 0, sizeof(DCB));
dcb.DCBlength = sizeof(DCB);
dcb.BaudRate = baudRate;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if (!SetCommState(m_hSerialPort, &dcb))
return FALSE;
m_isOpen = TRUE;
return TRUE;
}
void CSerialPort::ClosePort()
{
if (m_isOpen)
{
CloseHandle(m_hSerialPort);
m_isOpen = FALSE;
}
}
BOOL CSerialPort::WriteData(const unsigned char* pData, int dataSize)
{
if (!m_isOpen)
return FALSE;
DWORD bytesWritten;
if (!WriteFile(m_hSerialPort, pData, dataSize, &bytesWritten, NULL))
return FALSE;
return TRUE;
}
BOOL CSerialPort::ReadData(unsigned char* pData, int bufferSize, int& bytesRead)
{
if (!m_isOpen)
return FALSE;
DWORD bytesToRead;
if (!PeekNamedPipe(m_hSerialPort, NULL, 0, NULL, &bytesToRead, NULL))
return FALSE;
if (bytesToRead > 0)
{
if (!ReadFile(m_hSerialPort, pData, bufferSize, (LPDWORD)&bytesRead, NULL))
return FALSE;
return TRUE;
}
bytesRead = 0;
return TRUE;
}
```
以上是CSerialPort类的源代码。此类提供了打开和关闭串行端口的功能,并可以通过WriteData和ReadData函数分别写入和读取数据。OpenPort函数用于打开指定端口号和波特率的串行端口。ClosePort函数用于关闭串行端口。WriteData函数用于向串行端口写入数据,并返回是否写入成功。ReadData函数用于从串行端口读取数据,并返回是否读取成功,并将读取的字节数存储在bytesRead参数中。
阅读全文