LibSerial 1.0.0
LibSerial provides a convenient, object oriented approach to accessing serial ports on POSIX systems.
Loading...
Searching...
No Matches
main_page_example.cpp
1
5#include <libserial/SerialPort.h>
6#include <libserial/SerialStream.h>
7
8#include <iostream>
9
10constexpr const char* const SERIAL_PORT_1 = "/dev/ttyUSB0" ;
11constexpr const char* const SERIAL_PORT_2 = "/dev/ttyUSB1" ;
12
13int main()
14{
17
18 // Instantiate a Serial Port and a Serial Stream object.
19 SerialPort serial_port ;
20 SerialStream serial_stream ;
21
22 // Open the hardware serial ports.
23 serial_port.Open( SERIAL_PORT_1 ) ;
24 serial_stream.Open( SERIAL_PORT_2 ) ;
25
26 // Set the baud rates.
27 using LibSerial::BaudRate ;
28 serial_port.SetBaudRate( BaudRate::BAUD_115200 ) ;
29 serial_stream.SetBaudRate( BaudRate::BAUD_115200 ) ;
30
31 char write_byte_1 = 'a' ;
32 char write_byte_2 = 'b' ;
33
34 char read_byte_1 = 'A' ;
35 char read_byte_2 = 'B' ;
36
37 // Write a character.
38 serial_port.WriteByte(write_byte_1) ;
39 serial_stream << write_byte_2 ;
40
41 size_t timeout_milliseconds = 5 ;
42
44 try
45 {
46 // Read a character.
47 serial_port.ReadByte(read_byte_1, timeout_milliseconds) ;
48 serial_stream >> read_byte_2 ;
49 }
50 catch (const ReadTimeout&)
51 {
52 std::cerr << "The Read() call has timed out." << std::endl ;
53 }
54
55 std::cout << "serial_port read: " << read_byte_1 << std::endl ;
56 std::cout << "serial_stream read: " << read_byte_2 << std::endl ;
57
58 // Close the Serial Port and Serial Stream.
59 serial_port.Close() ;
60 serial_stream.Close() ;
61}
Exception error thrown when data could not be read from the serial port before the timeout had been e...
SerialPort allows an object oriented approach to serial port communication. A serial port object can ...
Definition SerialPort.h:56
SerialStream is a stream class for accessing serial ports on POSIX operating systems....
void Open(const std::string &fileName, const std::ios_base::openmode &openMode=std::ios_base::in|std::ios_base::out, bool exclusive=true)
Opens the serial port associated with the specified file name and the specified mode.