c++ - 从 com 端口 rs232 读取阻塞模式

标签 c++ windows serial-port

我在 C++ 中有一段代码可以读写数据 rs232,但我希望它是阻塞模式,即我希望它在读取行上等待,直到收到一个字符。这是我的代码:

#include <windows.h>
#include <stdio.h>
#include <string.h>

HANDLE hPort;

BOOL WriteByte(BYTE bybyte)
{
    DWORD iBytesWritten=0;
    DWORD iBytesToRead = 1;
    if(WriteFile(hPort,(LPCVOID) 
        &bybyte,iBytesToRead,&iBytesWritten,NULL)==0)
        return FALSE;
    else return TRUE;
}


BOOL ReadByte(BYTE  &resp)
{
    BOOL bReturn = TRUE;
    BYTE rx;
    DWORD dwBytesTransferred=0;

    if (ReadFile (hPort, &rx, 1, &dwBytesTransferred, 0)> 0)
    {
        if (dwBytesTransferred == 1)
        {
            resp=rx;
            bReturn  = TRUE;
        }
        else bReturn = FALSE;
    }
    else    bReturn = FALSE;
    return bReturn;
}


void ClosePort()
{
    CloseHandle(hPort);
    return;
}

HANDLE ConfigureSerialPort(LPCSTR  lpszPortName)
{
    HANDLE hComm = NULL;
    DWORD dwError;
    DCB PortDCB;
    COMMTIMEOUTS CommTimeouts;
    // Open the serial port.
    hComm = CreateFile (lpszPortName, // Pointer to the name of the port
        GENERIC_READ | GENERIC_WRITE,
        // Access (read-write) mode
        0,              // Share mode
        NULL,           // Pointer to the security attribute
        OPEN_EXISTING,  // How to open the serial port
        0,              // Port attributes
        NULL);          // Handle to port with attribute
    // to copy

    // Initialize the DCBlength member.
    PortDCB.DCBlength = sizeof (DCB);
    // Get the default port setting information.
    GetCommState (hComm, &PortDCB);
    // Change the DCB structure settings.
    PortDCB.BaudRate = 9600;              // Current baud
    PortDCB.fBinary = TRUE;               // Binary mode; no EOF check
    PortDCB.fParity = TRUE;               // Enable parity checking
    PortDCB.fOutxCtsFlow = FALSE;         // No CTS output flow control
    PortDCB.fOutxDsrFlow = FALSE;         // No DSR output flow control
    PortDCB.fDtrControl = DTR_CONTROL_ENABLE;
    // DTR flow control type
    PortDCB.fDsrSensitivity = FALSE;      // DSR sensitivity
    PortDCB.fTXContinueOnXoff = TRUE;     // XOFF continues Tx
    PortDCB.fOutX = FALSE;                // No XON/XOFF out flow control
    PortDCB.fInX = FALSE;                 // No XON/XOFF in flow control
    PortDCB.fErrorChar = FALSE;           // Disable error replacement
    PortDCB.fNull = FALSE;                // Disable null stripping
    PortDCB.fRtsControl = RTS_CONTROL_ENABLE;
    // RTS flow control
    PortDCB.fAbortOnError = FALSE;        // Do not abort reads/writes on
    // error
    PortDCB.ByteSize = 8;                 // Number of bits/byte, 4-8
    PortDCB.Parity = NOPARITY;            // 0-4=no,odd,even,mark,space
    PortDCB.StopBits = ONESTOPBIT;        // 0,1,2 = 1, 1.5, 2

    // Configure the port according to the specifications of the DCB
    // structure.
    if (!SetCommState (hComm, &PortDCB))
    {
        printf("Could not configure serial port\n");
        return NULL;
    }
    // Retrieve the time-out parameters for all read and write operations
    // on the port.
    GetCommTimeouts (hComm, &CommTimeouts);
    // Change the COMMTIMEOUTS structure settings.
    CommTimeouts.ReadIntervalTimeout = MAXDWORD;
    CommTimeouts.ReadTotalTimeoutMultiplier = 0;
    CommTimeouts.ReadTotalTimeoutConstant = 0;
    CommTimeouts.WriteTotalTimeoutMultiplier = 0;
    CommTimeouts.WriteTotalTimeoutConstant = 0;
    if (!SetCommTimeouts (hComm, &CommTimeouts))
    {
        printf("Could not set timeouts\n");
        return NULL;
    }
    return hComm;
}

int main(void)
{
    //  Can also use COM2, COM3 or COM4 here
    hPort = ConfigureSerialPort("\\\\.\\COM12");
    if(hPort == NULL)
    {
        printf("Com port configuration failed\n");
        return -1;
    }
    // Call your ReadString and WriteString functions here
    BYTE b = 'm';
    WriteByte(b);
    ReadByte(b); //read line i want the program wait on this line until at least one character came(was not pooling).


    ClosePort();
    return 0;
}

有什么想法吗?

最佳答案

阻塞读取是 ReadFile 的正常行为,但您已通过将 ReadTotalTimeoutConstant 设置为 MAXDWORD 来更改它。研究 COMMTIMEOUTS 的 MSDN 页面。改用零。

关于c++ - 从 com 端口 rs232 读取阻塞模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17217032/

相关文章:

windows - 将 Apache 2.2 作为单个 httpd.exe 运行以进行调试

c++ - DeleteIPAddress 和 AddIpAddress 问题

windows - 批处理脚本帮助清除历史记录不是 cls 的问题

c++ - cmake,无法将静态库链接到共享库

c++ - const 转发引用给出错误 C2440 : 'initializing' : cannot convert from 'const std::string' to 'const std::string &&'

c# - 使用 SerialPort.ReadByte 优于 ReadChar 的优势?

serial-port - - qemu中的串行pty,如何打开?

c# - 在真实和虚拟串行端口之间创建一对

c++ - iostream和命名空间std有什么关系?

c++ - sfinae 关于在类主体外部定义的成员函数