The explanation with the level of detail you are seeking would take hours to formulate. Perhaps it is best to investigate the material that other people are recommending.
A quick solution in C ++ would be to use a read / write library on the serial. If this is acceptable to you, the Qt framework brings a cross-platform solution for very interesting serial communication.
The Qt documentation provides an example called Terminal >, which shows how to identify the serial ports on the computer, connect to one of them, and print the data on the console. Unfortunately, this example features a Graphical User Interface (GUI), and this causes the sample code to become a bit bloated.
A few months ago I decided to remove all this part of UI and ended up providing a simpler and simpler example in GitHub called < strong> QtSerial .
Basically, the process to read from a serial port using Qt consists of:
-
List the computer's serial ports : class QSerialPortInfo
provides static methods for this and provides information about each serial port found, such as location, manufacturer identification, product identification, etc.
-
Connect to a serial port : simply instantiate an object of type % , if it has parity or not, the type of flow control and other things.
li>
- Read from serial port : To accomplish this task you need to monitor 2 signals of the
QSerialPort
instantiated object: QSerialPort
and readyRead()
. To do this you must declare a subclass of error(QSerialPort::SerialPortError)
and implement the two 2 slots that will be triggered automatically when these signals happen.
In other words, QObject
is the signal sent by the readyRead()
object when there is data from the serial to be received by your program. The QSerialPort
sign, of course, is issued only in case of failure during communication.
An essential operation to ensure reading success is invoking error()
. There are several questions in the OS of people who can not make the reading work correctly because they forgot to call this method.
Well, to do the reverse and send data by serial the process is easier. Just adjust the call of the setDataTerminalReady(true)
method to request permission to read and write to the serial port:
serial.open(QIODevice::ReadWrite);
To send data, run QSerialPort::open()
or QSerialPort:write()
. Meanwhile , QSerialPort:putChar()
does not block execution and therefore returns immediately. Thus, when the data is actually sent by the serial port the signal write()
is issued. So do not forget to implement a slot to connect to this signal and ensure that everything your program tried to send was actually submitted to the serial.
Well, I tested QtSerial with more than one Arduino and other devices. Please take a fork from my repository and when encountering problems in this application request a bytesWritten()
. I'll be happy to add your changes to this project.