In the previous laboratory lesson, we saw how to use our ros2 topic to turn on or off a lead that is
embedded on the Arduino board.
And we also enable the communication between Ros two and Arduino using the serial port.
In this lesson, we are going to develop a simple Arduino script that instead sends messages over the
serial port.
In the next lesson, we will develop our Ros two node in both Cplusplus and Python that reads these
comments that are received from the serial port by the Arduino and republish them on a Ros two topic.
And this way we will have enabled also the reverse communication that is the communication between Arduino
and Ros two.
And so basically Arduino will be able to publish messages within our Ros two topic.
Let's start by opening the Arduino ID, and here let's create a new sketch.
So a new script.
So let's close the old one.
And here in the setup function, which is called only once when the Arduino boots up.
Let's initialize the communication with the serial port as we did in the previous lesson by using the
function, begin from the serial library and let's begin this communication by using about rate of 115
200.
And also in this case, let's use a timeout.
So let's set a timeout.
Of one.
In the loop function instead, which is the one that is executed repeatedly in each cycle of the microcontroller.
We want to send a new message.
So a new integer variable called X.
So let's create this X variable as a global variable and let's initialize this 1 to 0.
And so we want to publish this variable.
So the this integer value in this serial port.
To do so.
In Arduino, we can use serial print line.
So the print line function and let's publish the X variable.
And then at the end of each loop, let's also increase this variable.
So let's increment its value.
Then in order to avoid executing this loop function too fast, let's also insert a small delay of 0.1.
With this, we have completed our very simple script for Arduino that publish a message.
So a counter on the serial port.
At this point, we can save this script.
So let's save it.
And again, let's save it within our workspace and within the Arduino boot firmware and within the firmware
sub folder.
And let's call this one simple serial transmitter.
And so let's save this script.
Let's conclude this lesson by compiling this file in order to see that actually there are no errors.
And so let's upload it into our Arduino board.
So let's connect the board to the PC using an USB cable.
And let's go to the tools here.
The port.
Let's select the port of your PC to which the Arduino board is connected and then click on upload.
So this will compile again and upload the code into the Arduino.