For a school project: OCADrone, I’m coding a protocol to communicate between an Arduino and a computer (Raspberry Pi) over the USB connection. In order to communicate, the two parts establish a serial communication. I will explain step by steps how it works and how I decided to implement it.
For this project, I use C++ on Arduino and C on Raspberry Pi. As it is not the goal of this article, I won’t explain in details how the read(), write() operations works in those language and focus more on the specific thing about Arduino.
Computer Side (CLIENT)
Connect your computer to the Arduino, open the arduino IDE.
In the “tools” menu, click “Serial monitor”:
This window should pop:
Select seperate line: “New Line” and the appropriate baud rate.
You can see what the serial port receive and send messages with the text box at the bottom.
Arduino Side (HOST)
Initialization
In order to implement the host, we will use the Arduino serial library. In order to be able to communicate, you have to initialize the serial connection using the begin() function.
1 2 3 4 5 6 |
#define SERIAL_BAUDRATE 9600 void setup() { Serial.begin(SERIAL_BAUDRATE); } |
The baudrate is the bits per seconds that will be sent by the serial communication, as explained in the first part of the guide.
Note 1 : Serial.begin() can be called wherever you want in your code, not only in the setup(). However you have to call begin() before reading or writing on the serial.
Note2 : On some boards like Mega, you have 4 serial objects that are: Serial, Serial1, Serial2 and Serial3. Each can be initialized with a different baudrate if needed.
Reading
In order to retrieve information from the serial port, we will use the functions Serial.available() and Serial.read() .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// Buffer to store incoming commands from serial port String inData; void setup() { Serial.begin(9600); } void process(String data) { //Do whatever you want on data } void loop() { while (Serial.available() > 0) { char recieved = Serial.read(); inData += recieved; // Process message when new line character is recieved if (recieved == '\n') { process(inData); inData = ""; // Clear recieved buffer } } } |
In this code, we receive every characters, append them to a string and trigger process() when encountering a new line.
If you don’t want to loop in the code, you can implement the reading in this callback:
1 2 3 |
void serialEvent(){ //statements } |
For Arduino Mgea, use:
1 |
serialEvent1() |
1 |
serialEvent2() |
1 |
serialEvent3() |
Writing
To write on the serial port, use Serial.write(). The function is available for characters or Strings.
1 2 3 4 5 6 7 8 |
//character Serial.write('c'); //byte / ASCII Serial.write(42); // String Serial.write("Test"); |
Leave a Reply