LibSerial 1.0.0
LibSerial provides a convenient, object oriented approach to accessing serial ports on POSIX systems.
Loading...
Searching...
No Matches
serial_stream_read.cpp
1
5#include <libserial/SerialStream.h>
6
7#include <cstdlib>
8#include <iostream>
9#include <unistd.h>
10
11constexpr const char* const SERIAL_PORT_1 = "/dev/ttyUSB0" ;
12
17int main()
18{
19 using namespace LibSerial ;
20
21 // Instantiate a SerialStream object.
22 SerialStream serial_stream ;
23
24 try
25 {
26 // Open the Serial Port at the desired hardware port.
27 serial_stream.Open(SERIAL_PORT_1) ;
28 }
29 catch (const OpenFailed&)
30 {
31 std::cerr << "The serial port did not open correctly." << std::endl ;
32 return EXIT_FAILURE ;
33 }
34
35 // Set the baud rate of the serial port.
36 serial_stream.SetBaudRate(BaudRate::BAUD_115200) ;
37
38 // Set the number of data bits.
39 serial_stream.SetCharacterSize(CharacterSize::CHAR_SIZE_8) ;
40
41 // Turn off hardware flow control.
42 serial_stream.SetFlowControl(FlowControl::FLOW_CONTROL_NONE) ;
43
44 // Disable parity.
45 serial_stream.SetParity(Parity::PARITY_NONE) ;
46
47 // Set the number of stop bits.
48 serial_stream.SetStopBits(StopBits::STOP_BITS_1) ;
49
50 // Wait for data to be available at the serial port.
51 while(serial_stream.rdbuf()->in_avail() == 0)
52 {
53 usleep(1000) ;
54 }
55
56 // Keep reading data from serial port and print it to the screen.
57 while(serial_stream.IsDataAvailable())
58 {
59 // Variable to store data coming from the serial port.
60 char data_byte ;
61
62 // Read a single byte of data from the serial port.
63 serial_stream.get(data_byte) ;
64
65 // Show the user what is being read from the serial port.
66 std::cout << data_byte ;
67
68 // Wait a brief period for more data to arrive.
69 usleep(1000) ;
70 }
71
72 // Successful program completion.
73 std::cout << "Done." << std::endl ;
74 return EXIT_SUCCESS ;
75}
Exception error thrown when the serial port could not be opened.
SerialStream is a stream class for accessing serial ports on POSIX operating systems....
void SetCharacterSize(const CharacterSize &characterSize)
Sets the character size for the serial port.
void SetBaudRate(const BaudRate &baudRate)
Sets the baud rate for the serial port to the specified value.
bool IsDataAvailable()
Checks if data is available at the input of the serial port.
void SetFlowControl(const FlowControl &flowControlType)
Sets flow control for the serial port.
void SetStopBits(const StopBits &stopBits)
Sets the number of stop bits to be used with the serial port.
void Open(const std::string &fileName, const std::ios_base::openmode &openMode=std::ios_base::in|std::ios_base::out)
Opens the serial port associated with the specified file name and the specified mode.
void SetParity(const Parity &parityType)
Sets the parity type for the serial port.