Communicating with Arduino by USB

posted in: Arduino, Guides | 0


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.

sketch_apr30a | Arduino 1.5.6-r2_049

In the “tools” menu, click “Serial monitor”:


This window should pop:

-dev-ttyACM0 (Arduino Mega or Mega 2560)_051


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)



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.



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.



In order to retrieve information from the serial port, we will use the functions  Serial.available()  and .

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:

For  Arduino Mgea, use:


To write on the serial port, use Serial.write(). The function is available for characters or Strings.


Leave a Reply