read_port.cpp

来自「linux下串口通讯用的类库 c++编写」· C++ 代码 · 共 85 行

CPP
85
字号
#include <iostream>#include <SerialStream.h>intmain( int    argc,      char** argv  ){    //    // Open the serial port.    //    using namespace LibSerial ;    SerialStream serial_port ;    serial_port.Open( "/dev/ttyS0" ) ;    if ( ! serial_port.good() )     {        std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] "                  << "Error: Could not open serial port."                   << std::endl ;        exit(1) ;    }    //    // Set the baud rate of the serial port.    //    serial_port.SetBaudRate( SerialStreamBuf::BAUD_57600 ) ;    if ( ! serial_port.good() )     {        std::cerr << "Error: Could not set the baud rate." << std::endl ;        exit(1) ;    }    //    // Set the number of data bits.    //    serial_port.SetCharSize( SerialStreamBuf::CHAR_SIZE_8 ) ;    if ( ! serial_port.good() )     {        std::cerr << "Error: Could not set the character size." << std::endl ;        exit(1) ;    }    //    // Disable parity.    //    serial_port.SetParity( SerialStreamBuf::PARITY_NONE ) ;    if ( ! serial_port.good() )     {        std::cerr << "Error: Could not disable the parity." << std::endl ;        exit(1) ;    }    //    // Set the number of stop bits.    //    serial_port.SetNumOfStopBits( 1 ) ;    if ( ! serial_port.good() )     {        std::cerr << "Error: Could not set the number of stop bits."                  << std::endl ;        exit(1) ;    }    //    // Turn on hardware flow control.    //    serial_port.SetFlowControl( SerialStreamBuf::FLOW_CONTROL_HARD ) ;    if ( ! serial_port.good() )     {        std::cerr << "Error: Could not use hardware flow control."                  << std::endl ;        exit(1) ;    }    //    // Do not skip whitespace characters while reading from the    // serial port.    //    // serial_port.unsetf( std::ios_base::skipws ) ;    //    // Keep reading data from serial port and print it to the screen.    //    while( serial_port.rdbuf()->in_avail() > 0  )     {        char next_byte;        serial_port.get(next_byte);        std::cerr << std::hex << (int)next_byte << " ";    }     std::cerr << std::endl ;    return EXIT_SUCCESS ;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?