串口通讯类CSerialPort的使用

CSerialPort是一个基于MFC的串口通信类,作者是Remon Spekreijse,地址在这里

http://www.codeguru.com/cpp/i-n/network/serialcommunications/article.php/c2483/A-communication-class-for-serial-port.htm

如何使用

将 SerialPort.cpp SerialPort.h 加入工程,包含头文件

#include "SerialPort.h"

声明CSerialPort对象

CSerialPort Port;

声明消息响应函数

afx_msg LRESULT OnComm(WPARAM ch, LPARAM port);

添加消息映射

ON_MESSAGE(ON_COM_RECEIVE, OnComm)

消息响应函数实现,接收数据

LRESULT CDemoDlg::OnComm(WPARAM ch, LPARAM port)
{
    char chData = (char)ch;
    
    return 0;
}

打开串口

void CDemoDlg::OpenPort(void)
{
    UINT  nPortNo = 1;
    UINT  nBaudrate = 115200;
    char  chParity = 'N';
    UINT  nDataBits = 8;
    UINT  nStopBits = 1;
    DWORD dwCommEvent = EV_RXFLAG | EV_RXCHAR;
    UINT  nBufferSize = 1024;

    BOOL ret = Port.InitPort(this, nPortNo, nBaudrate, chParity, nDataBits, nStopBits, dwCommEvent, nBufferSize);

    if(ret)
    {
        Port.StartMonitoring();
    }
}

关闭串口

void CDemoDlg::ClosePort(void)
{
    Port.ClosePort();
}

发送数据

void CDemoDlg::SendData(void)
{
    char buffer[128] = {0};
    
    Port.WriteToPort(buffer, 128);
}

参考资料

1. Remon Spekreijse的示例程序
http://www.codeguru.com/code/legacy/network/serialport_demo.zip

2. CSerialPort原始版本
http://blog.libsd.org/download/CSerialPort_original.7z

2. CSerialPort改进版本
https://github.com/liquanhai/CSerialPort
http://blog.libsd.org/download/CSerialPort_revised.7z

添加新评论