Used for communication between the Arduino board and a computer or other devices. All Arduino boards have at least one serial port (also known as a UART or USART), and some have several.
USB CDC name
Leonardo, Micro, YГєn
Connected to USB
Connected to NINA
SerialUSB (Native USB Port only)
Connected to Programming Port
SerialUSB (Native USB Port only)
On Uno, Nano, Mini, and Mega, pins 0 and 1 are used for communication with the computer. Connecting anything to these pins can interfere with that communication, including causing failed uploads to the board.
You can use the Arduino environment’s built-in serial monitor to communicate with an Arduino board. Click the serial monitor button in the toolbar and select the same baud rate used in the call to begin() .
Serial communication on pins TX/RX uses TTL logic levels (5V or 3.3V depending on the board). Don’t connect these pins directly to an RS232 serial port; they operate at +/- 12V and can damage your Arduino board.
To use these extra serial ports to communicate with your personal computer, you will need an additional USB-to-serial adaptor, as they are not connected to the Mega’s USB-to-serial adaptor. To use them to communicate with an external TTL serial device, connect the TX pin to your device’s RX pin, the RX to your device’s TX pin, and the ground of your Mega to your device’s ground.
Как мы с вами знаем из урока “Что умеет микроконтроллер“, у многих микроконтроллеров есть интерфейс UART, позволяющий передавать и принимать различные данные. У интерфейса есть два вывода на плате – пины TX и RX. На большинстве Arduino-плат к этим пинам подключен USB-UART преобразователь (расположен на плате), при помощи которого плата может определяться компьютером при подключении USB кабеля и обмениваться с ним информацией. На компьютере создаётся виртуальный COM порт (последовательный порт), к которому можно подключиться при помощи программ-терминалов и принимать-отправлять текстовые данные. Таким же образом кстати работают некоторые принтеры и большинство станков с ЧПУ.
В самой Arduino IDE есть встроенная “консоль” – монитор порта, кнопка с иконкой лупы в правом верхнем углу программы. Нажав на эту кнопку мы откроем сам монитор порта, в котором будут настройки:
Если с отправкой, автопрокруткой, отметками времени и кнопкой очистить вывод всё и так понятно, то конец строки и скорость мы рассмотрим подробнее:
Конец строки: тут есть несколько вариантов на выбор, чуть позже вы поймёте, на что они влияют. Лучше поставить нет конца строки, так как это позволит избежать непонятных ошибок на первых этапах знакомства с платформой.
Нет конца строки – никаких дополнительных символов в конце введённых символов после нажатия на кнопку отправка или клавишу Enter.
NL – символ переноса строки в конце отправленных данных.
CR – символ возврата каретки в конце отправленных данных.
NL+CR – и то и то.
Скорость – тут на выбор нам даётся целый список скоростей, т.к. общение по Serial может осуществляться на разных скоростях, измеряемых в бод (baud), и если скорости приёма и отправки не совпадают – данные будут получены некорректно. По умолчанию скорость стоит 9600, её и оставим.
Начнём знакомство с одним из самых полезных инструментов Arduino-разработчика – Serial, который идёт в комплекте со стандартными библиотеками. Serial позволяет как просто принимать и отправлять данные через последовательный порт, так и наследует из класса Stream кучу интересных возможностей и фишек, давайте сразу их все рассмотрим, а потом перейдём к конкретным примерам.
Запустить связь по Serial на скорости speed (измеряется в baud, бит в секунду). Скорость можно поставить любую, но есть несколько “стандартных” значений. Список скоростей для монитора порта Arduino IDE:
9600 чаще всего используется, можно назвать стандартной
115200 тоже часто встречается
2000000 – максимальная скорость, не работает на некоторых китайских платах
Are you trying to use Serial.read() to get data from a serial port to your Arduino? Maybe you’re using the Arduino Serial Monitor window and sending in data, or maybe you’ve got a program running on your raspberryPi sending data via serial to your Arduino board.
How do you use serial.read() to receive the data, and piece it together correctly? In this lesson you will learn exactly how to use Serial.read() to receive data from the serial port and stitch it together as one value.
The big picture of serial communication
The serial buffer
Serial.read and Serial.available
Developing a protocol and strategy for reading in data from the serial port
Implement the strategy in Arduino code
BONUS: How to convert the serial data from a string to an integer
The big picture of serial communication
Let’s take a step back from Serial.read(), and talk about Serial Communication.
Serial communication is the process of sending one bit of data at a time, sequentially, from one place to another. Like say, sending data from your raspberryPi to a connected Arduino, or vice versa.
USB is one of the most common methods used for serial communication, hence the name Universal Serial Bus. Using Arduino we can easily send and receive data over a USB cable with the built-in Arduino Serial Library.
Now if you don’t know what an Arduino library is, it’s basically a bunch of code that has been bundled together, because it is often used together.
Imagine you were a barber, maybe you have a specific drawer in your barber shop for all your hair cutting tools. Every time somebody walks in for a haircut, you know exactly where to look, in that hair cutting drawer, and all your tools are right there.
Maybe you have another drawer with all the stuff you need for dying peoples hair, when someone walks in and asks to get their hair dyed red, you know exactly which drawer to open. Same thing with Arduino libraries. Arduino libraries put together a bunch of software functions that help you with specific tasks.
Serial Library Functions
For serial communication, we can use the built-in Arduino Serial library.
The Serial library has functions like:
OK, we know that Serial Communication over USB is how we can talk between one device and another, and we know that the Arduino Serial library is the set of tools we’ll use for serial communication. But where does the data that comes from another device actually go on the Arduino?
The Serial Buffer
The answer is the serial buffer, or perhaps more precisely, the serial receive buffer. When bits of data start streaming in from your computer, a piece of hardware on your Arduino called a UART will assemble each of the 8 bits into a byte, and store those bytes for you in the Serial Receive Buffer.
The serial receive buffer can hold 64 bytes.
The data you send from your computer, to your Arduino, will end up in the serial receive buffer.
How do you get this data? That is where Serial.read() comes in.
Serial.read() is a function of the Serial library. What it does is read out the first available byte from the serial receive buffer. When it reads it out, it removes that byte from the buffer.
Say you had sent the phrase “Sub Sandwich” to your Arduino. This means you had put 12 bytes into your serial receive buffer.
Then Serial.read() will return the first value available in the serial receive buffer, which in this case is “S”, and it will leave “ub Sandwich” in the Serial receive buffer. Now the value “S” will be stored in the variable myFirstCharacter, and there will only be 11 bytes left in the serial buffer….
If we did this again…
Then mySecondCharacter would be holding the value “u”, and “b Sandwich” would be left in the serial receive buffer. Serial.read() takes one byte at a time from the serial receive buffer.
Now there is a little gotcha here that you need to look out for. Often when sending data over serial, there will be an invisible terminating character added to the end of the transmission.
This could be a CR (Carriage Return) or a LF (Line Feed) – which would add an additional byte to the serial receive buffer, or even both could be added CR+LF which would add two additional bytes to the buffer!
If you’re sending data over the serial monitor widow, on the bottom right you’ll see options to add these terminating characters every time you press the send button. Choosing No Line Ending will send just your characters.
Serial.available() – the Serial Spy
We can use another Serial library function, Serial.available(), to check to see if there is anything available to be read in the serial receive buffer.
Serial.available will return the number of bytes currently stored in the serial receive buffer. Say the phrase “Sub Sandwich” was in the serial receive buffer, then serial.available() would return the number 12. If “andwich” was in the serial receive buffer, then serial.available() would return the value 7.
Serial.available doesn’t affect the contents of the Serial receive buffer – it just reports back to us how full it is.
So IF the return value of Serial.available() is greater than 0, we know part of our message is still sitting in the serial receive buffer.
OK, all this Serial.read and Serial.available stuff is great, but what if I want to send the entire phrase “sub sandwich” to my Arduino and save it to a string, or say the value 462, and save it to an integer.
How do I corral all these bytes together into one string variable, or an integer, or whatever datatype for that matter?!
How to send integers, strings, or whatever over serial
OK, let’s roll up our sleeves and come up with a strategy…
Things are about to get a little technical here – I think it’s going to be a blast!
Now If you are new to Arduino programming and want to learn how to do stuff just like this, then make sure to check out the Programming Electronics Academy membership. In our membership we have video courses that walk you step by step on how to program Arduino so that you can prototype your own projects.
OK, back to our strategy…
First, we need to decide how we are going to send our data (which I will be calling “messages”) – that is, we need to decide on a protocol to follow.
Our Serial.read() protocol
Let’s make these the protocol rules that we’ll enforce in our Arduino program.
New messages will be read as soon as they arrive
Messages will be no longer than 12 bytes
Every message will end with a newline character ‘\n’ – which we will call out terminating character
This is a pretty basic protocol, but it will help us with our strategy.
First we need a place to store the incoming bytes from the serial receive buffer – we can use a char array for that. Then we need to check if anything is even available in the serial receive buffer – we can use Serial.available for that. Then we need to actually read in a byte – we can use Serial.read() for that.
Before we put the byte into our char array, we’ll need to check the incoming byte to make sure it is not a terminating character.
Create a character array to store incoming bytes
Check to see if there is anything in the serial receive buffer to be read – Serial.available()
While there is something to be read then…
Read in the byte to a temporary variable – Serial.read()
Check to see if what we read is part of our message OR a terminating character
If it is part of our message, then save it to a character array
If it is a terminating character, then output the message and prepare for the next message
If the message has exceeded the max message length in the protocol, then stop reading in more bytes and output the message (or doing something else with it)
Bare Minimum Arduino Sketch
Let’s get a bare minimum Arduino program started with setup() and loop(). We’ll add Serial.begin() to the loop to establish Serial Communication.
Notice in Serial.begin() we pass in the value 9600. This is called the baud rate – it sets the speed of the serial communication, and represents bits per second. Both devices must have the same baud rate selected in order for Serial Communication to work. If you’re using the Arduino IDE Serial Monitor window to send data, the baud rate can be set using a drop down menu.
Now let’s tackle the first step of our algorithm – we create a character array to hold the incoming message and a position variable to help us move through each element in the array. We’ll also create a constant to hold the max length of our message and use this to initialize the character array.
Now we need to check if any bytes are available in the serial receive buffer and while there are we need to read in the bytes in and save them to a temporary variable. We can use a while loop, Serial.available, Serial.read() to make this happen.
Now we need to check to see if the byte we read is a terminating character or not… We can use an if-else statement for that. If it’s not a terminating character we’ll do one thing, and if it is a terminating character we’ll do something else.
If it is part of our message, then save it to a character array. We’ll also need to increment our position in the char array for the next byte.
Now if we do get the terminating character that means we have received our entire message and we can actually do something with the message or data we received. In this case we’ll print the message to the Serial Monitor window. We’ll also need to reset our character array to prepare for the next message.
Before we can call this complete, we need to enforce the max message length in the protocol. This will prevent us from exceeding the space that we allotted in our character array. We can add this guard to our existing if statement.
Full Serial.read() Code
Here is the complete code to use Serial.read() to read in the entire message:
OK. This feels like a ton – I know!
But before we call it quits I want to show you a way to return this c string into an integer.
How to Convert a char to an Int with Arduino
What if instead of sending words or letters with the serial port, perhaps you are sending numerical values, like 42, or 314. How can you convert these digits into integers?
Well there’s a super cool function called atoi() – this will take a null-terminated string and convert it to an integer.
Strings in the c programming language are null-terminated – they end with the character ‘\0’. The atoi() function will not work unless the string you pass in has the null-terminating character!
So in our current code all we would have to do is add something like this:
That’s it, now the serial message has been converted from a c string into an integer!
Review of Serial.read() Lesson
Let’s do a quick review.
First, we talked generally about Serial Communication – it’s a means of sending data ______________ . We talked about the Serial Receive Buffer – do you remember how many bytes it can hold?
We discussed the basics of Serial.read() and Serial.available().
Serial.read() removes a byte from the ________________. The function _________________ returns how many bytes are in the serial receive buffer.
We developed a simple _____________ and strategy for getting messages from our serial port.
Then we implemented the strategy in Arduino code. Finally, we talked about using the function atoi() to convert from a c string to an integer.
If you liked this – you are going to love the next lesson! In the next lesson of this series you will learn how to cut this code down to just a couple lines using some other built in Serial library functions.