0% found this document useful (0 votes)
20 views51 pages

5 - Serial Library

The document provides an overview of serial communication using the Arduino platform, detailing the Serial Library and its functions for data transmission between microcontrollers. It explains the concepts of asynchronous communication, UART devices, and various functions like Serial.begin(), Serial.available(), and Serial.print() for managing serial data. Additionally, it covers the differences between Arduino Uno and Mega in terms of serial communication capabilities and includes examples of code for practical implementation.

Uploaded by

Sandiswa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views51 pages

5 - Serial Library

The document provides an overview of serial communication using the Arduino platform, detailing the Serial Library and its functions for data transmission between microcontrollers. It explains the concepts of asynchronous communication, UART devices, and various functions like Serial.begin(), Serial.available(), and Serial.print() for managing serial data. Additionally, it covers the differences between Arduino Uno and Mega in terms of serial communication capabilities and includes examples of code for practical implementation.

Uploaded by

Sandiswa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Arduino

Arduino Uno ATmega328 Arduino Mega ATmega2560

Serial Library
Created by: Dr. Daniel van Niekerk
Introduction
̶ Serial communication is a method of sending and receiving data one bit at a time.
̶ The Serial Library uses TTL (Transistor-Transistor-Logic) serial communication method
via a UART (Universal Asynchronous Receive Transmit) device.
̶ Synchronous serial communication uses a clock signal to known when to read data bits.
̶ Asynchronous serial communication doesn't used a clock signal and therefore, requires
a baud-rate that transmitter and receiver operate at, to know when to read data bits.
̶ The UART device is build into micro-controllers and therefore, can be used to serially
communicate with each other as shown:
UART1 UART2
Send Char ‘E’ Send Char ‘Q’
01000101 Tx Tx 01010001

Receive Char Receive Char


01010001 Rx Rx 01000101

GND GND
Micro-controller1 Micro-controller2

̶ Each UART has a Tx (transmit), Rx (receive) and ground pin that must be connected to
allow for bidirectional communication using the following TTL serial protocol:
PACKET
0 to1
1 5 to 9 data bits 1 to 2
Parity
Start Stop
(Often 8 bits of data) Bit
Bit Bits
(High or
(Low) DATA FRAME (High)
Low)
Introduction
̶ Example, when serially sending 'G' with ASCII code '0b01000111' using Serial.write('G'):
HIGH 1 1 1 0 0 0 1 0
S
S
T
T
A
S0 O
R S1 S2 S3 S4 S5 S6 S7 S8 P
T
LOW

̶ The Tx pin goes low to tell the Rx pin that data is about to be serially transmitted.
̶ The Rx pin based on the set baud-rate then waits one and a half cycles (S0 to S1) before
it starts to sample the incoming serial data bits.
̶ Thereafter, the time between two consecutive samples (e.g. S1 to S2) is the baud-rate
period, so that it is able to sample in the middle of each data bit in order to obtain the
correct transmitted data signal.
̶ The TTL serial protocol always transmits the data byte Least Significant Bit (LSB) first.
̶ After data bits, an optional EVEN or ODD parity bit can be send for error checking.
̶ For example, if EVEN parity is selected then:
> 00011100 + parity bit set to 1 results in an even number of set data bits, data okay.
> 00011101 + parity bit set to 1 results in an odd number of set data bits, data error.
̶ The Tx pin then goes high to indicate the stop bit that ends the serial communication.
̶ The baud-rate is how many times per second the signal can change and therefore, 9600
bits per second means that the signal changes every (1/9600) = 104.16 us/bit.
̶ This is the period time that each data bit is available for in the serial stream.
Introduction
• Arduino Uno Serial
̶ Is used to communication between Arduino board and a computer or other devices.
̶ Arduino boards have at least one build-in serial UART device.
̶ It serially communicates via RX pin 0 and TX pin 1 as well as with a computer via USB cable.
̶ By using serial functions, the RX pin 0 and Tx pin 1 cannot be used for digital input or output.
̶ Arduino development environment software on the computer has a build-in serial monitor
that can be used to communicate with an Arduino board.
̶ Click serial monitor button and select the same baud-rate used in the begin() function.
• Arduino Mega Serial
̶ Has three additional serial UART devices:
> Serial1 on pins 19 (RX) and 18 (TX).
> Serial2 on pins 17 (RX) and 16 (TX).
> Serial3 on pins 15 (RX) and 14 (TX).
̶ To use these pins to communicate with a computer, an additional USB-to-serial adaptor is
required because these pins are not connected to the onboard USB-to-serial micro-controller.
̶ These pins can be use to communicate with external TTL serial devices.
̶ Connect TX pin to device's RX pin and RX pin to device's TX pin with the ground of Arduino
board connected to the device's ground.
̶ Do not connect these pins directly to a computer RS232 serial port because it operates at
voltages of +/- 12V and can damage the Arduino microcontroller RX and TX pins.
̶ Use an RS232 converter device, to converter RX and TX signals to the correct voltage levels.
Function: Serial.begin()
• Description
̶ Sets the serial data baud-rate (bits per second), for RX & TX pins and returns nothing.
̶ An optional second argument configures the data, parity and stop bits.
̶ The default is 8 data bits, no parity and one stop bit.
̶ Other conventional baud-rates can also be specified to serially communicate.
̶ Possible baud-rates are: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400,
57600, or 115200.
• Syntax
̶ Serial.begin(speed) or Serial.begin(speed, config)
• Arduino Mega only:
̶ Serial1.begin(speed) or Serial1.begin(speed, config)
̶ Serial2.begin(speed) or Serial2.begin(speed, config)
̶ Serial3.begin(speed) or Serial3.begin(speed, config)
• Parameters
̶ Serial: serial port object.
̶ speed: baud rate in bits per second (long).
̶ config: sets the data bits, parity bit and stop bits, valid settings are:
> SERIAL_5N1, SERIAL_6N1, SERIAL_7N1, SERIAL_8N1, SERIAL_5N2, SERIAL_6N2,
> SERIAL_7N2, SERIAL_8N2, SERIAL_5E1, SERIAL_6E1, SERIAL_7E1,SERIAL_8E1,
> SERIAL_5E2, SERIAL_6E2, SERIAL_7E2, SERIAL_8E2, SERIAL_5O1, SERIAL_6O1,
> SERIAL_7O1, SERIAL_8O1, SERIAL_5O2, SERIAL_6O2, SERIAL_7O2, SERIAL_8O2
̶ A parity bit is a single bit that can be appended to data bits that can be set to a 1 or 0 in
order to make the total number of 1-bits either “even parity” or “odd parity”.
Function: if (Serial)
• Description
̶ Indicates if the specified serial port is ready.
• Syntax
̶ All boards:
> if (Serial)
̶ Arduino Mega specific:
> if (Serial1), if (Serial2) or if (Serial3)
• Parameters
̶ Serial: serial port object.
• Returns
̶ true if the specified serial port is available (boolean).
• Example
void setup() {
Serial.begin(9600); //Initialize serial port
}

void loop(){
while(!Serial); // wait until serial port is ready
...
}
Example: Serial.begin()
// Enabling Arduino Uno main serial port
void setup(){
Serial.begin(9600, SERIAL_8N1); // opens serial port at 9600bps
while(!Serial); // wait until serial port is ready
Serial.println("Hello Computer");
}
void loop() {}

// Arduino Mega using all four of its Serial ports


// (Serial, Serial1, Serial2, Serial3) with different baud rates:
void setup(){
Serial.begin(9600); // default SERIAL_8N1 set if not specified
Serial1.begin(38400); // opens serial port at 38400bps
Serial2.begin(19200); // opens serial port at 19200bps
Serial3.begin(4800); // opens serial port at 4800bps
while(!Serial); // wait until serial port is ready
Serial.println("Hello Computer");
Serial1.println("Hello Serial 1");
Serial2.println("Hello Serial 2");
Serial3.println("Hello Serial 3");
}
void loop() {}
Function: Serial.end()
• Description
̶ This function disables serial communication, thereby allowing the pin0-RX and pin1-TX
to be used as general purpose input and output digital pins.
̶ To re-enable serial communication, call Serial.begin() again.
• Syntax
̶ Serial.end()
• Arduino Mega only:
̶ Serial1.end()
̶ Serial2.end()
̶ Serial3.end()
• Parameters
̶ Serial: serial port object.
• Returns
̶ Nothing
Function: Serial.available()
• Description
̶ Gets the number of bytes or characters available for reading from the serial port.
̶ This is data that's already arrived and stored in the internal serial receive buffer.
̶ The internal serial receive buffer can hold up-to 64 bytes.
• Syntax
̶ Serial.available()
• Arduino Mega only:
̶ Serial1.available()
̶ Serial2.available()
̶ Serial3.available()
• Parameters
̶ Serial: serial port object.
• Returns
̶ The number of bytes or characters available to read.
Example: Serial.available()
/* routine to serially transmit back a data byte when it is received */

unsigned char ucByteIn = 0; // for incoming serial data

void setup()
{
Serial.begin(9600); // open serial port and set data rate
}

void loop()
{
// send data only when data received
if(Serial.available() > 0) // or use if(Serial.avalible())
{
// read single incoming byte
ucByteIn = Serial.read();
// send decimal ASCII value of received byte
Serial.print("I received: ");
Serial.println(ucByteIn, DEC);
}
}
Arduino Mega Example: Serial.available()
// Serial pin1-TX connected to Serial1 pin19-RX and,
// Serial1 pin18-TX connected to Serial pin0-RX

void setup(){
Serial.begin(9600); // opens serial port at 9600bps
Serial1.begin(9600); // also open serial1 port at 9600bps
Serial1.write(65); // send single ASCII code byte for character ‘A’
}

void loop()
{
// read Serial and then send to Serial1:
if(Serial.available())
{
byte ByteIn = Serial.read(); // receive a single byte
Serial.write(ByteIn); // send a single byte
}

// read Serial1 and then send to Serial:


if(Serial1.available())
{
byte ByteIn = Serial1.read(); // receive a single byte
Serial1.write(ByteIn); // send a single byte
}
}
Function: Serial.availableForWrite()
• Description
̶ Gets the number of bytes or characters available for writing in the serial buffer,
without blocking the write operation.
̶ This is data that's already stored in the internal serial transmit buffer that must still be
sent.
• Syntax
̶ Serial.availableForWrite()
• Arduino Mega only:
̶ Serial1.availableForWrite()
̶ Serial2.availableForWrite()
̶ Serial3.availableForWrite()
• Parameters
̶ Serial: serial port object.
• Returns
̶ The number of bytes or characters available to write.
ASCII Table
̶ ASCII stands for “American Standard Code for Information Interchange”.
̶ It is a character encoding standard for electronic communication ranging from 00H-FFH.
ASCII and BCD Code
̶ Computers only understand numbers, ASCII - (American Standard Code for Information Interchange)
so ASCII code represents an alphabetic, Hex 0X 1X 2X 3X 4X 5X 6X 7X
numerical or special character including X0 NUL DLE Space 0 @ P ' p
non-printable characters. X1 SOH DC1 ! 1 A Q a q
̶ ASCII was developed a long time ago X2 STX DC2 " 2 B R b r
and now the first 32 non-printing X3 ETX DC3 # 3 C S c s
characters are rarely used for their
original purpose. X4 EOT DC4 $ 4 D T d t
X5 ENQ NAK % 5 E U e u
̶ ASCII was actually designed for use
with teletypes and so the descriptions X6 ACK SYN & 6 F V f v
are somewhat obscure. X7 Bell ETB ' 7 G W g w
̶ ASCII code is the raw format that any X8 BS CAN ( 8 H X h x
computer can understand and is often X9 HT EM ) 9 I Y i y
used for digital communication XA LF SUB * : J Z j z
between machines. XB VT ESC + ; K [ k {
̶ The ASCII code takes up one byte for XC FF FS , < L \ l |
each character and an ASCII byte can XD CR GS - = M ] m }
only represent one BCD digit (nibble). XE SO RS . > N ^ n ~
̶ Therefore, for packed BCD numbers in XF SI US / ? O _ o DEL
one byte, each digit has to be isolated
and converted separately to ASCII.
̶ Also, two ASCII bytes must be BCD - (Binary Code Decimal)
converted to BCD and then combined 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001
to form a single packed BCD byte. 0 1 2 3 4 5 6 7 8 9
How to include ASCII Special Characters in Strings

• Note
̶ The old HyperTerminal program responds to: ‘\a’, ‘\b’, ‘\t’, ‘\n’, ‘\v’, ‘\f’ and ‘\r’.
̶ The Arduino serial monitor only responds to: ‘\t’ and ‘\n’.
Function: Serial.print()
• Description
̶ Prints data to the serial port as human-readable ASCII character text.
̶ Numbers are printed using an ASCII byte code character, for each number digit.
̶ Floats are also printed as ASCII byte code digits with two decimal places by default.
̶ Characters ('a') and strings ("abc") are also send as ASCII byte code character text.
> Serial.print(78) // sends "78" (ASCII code for 7 and then 8)
> Serial.print(1.23456) // sends "1.23"
> Serial.print('N') // sends 'N' (ASCII code for capital letter ‘N’)
> Serial.print("Hello world.") // sends ASCII code for all letters of the string

• Note:
̶ ASCII byte code number sent with Serial.write(), displays a single ASCII character.
̶ Optional second parameter specifies base format to use, such as BIN (binary-base 2),
OCT (octal-base 8), DEC (decimal-base 10) and HEX (hexadecimal-base 16).
̶ For floating point numbers, this second parameter specifies number of decimal places.
> Serial.print(78, BIN) // sends "1001110"
> Serial.print(78, OCT) // sends "116"
> Serial.print(78, DEC) // sends "78", same as “Serial.print(78)”
> Serial.print(78, HEX) // sends "4E" (sends ASCII code for 4 and then E)
> Serial.print(1.23456, 0) // sends "1"
> Serial.print(1.23456, 3) // sends "1.234"
Function: Serial.print()
• Syntax
̶ Serial.print(val)
̶ Serial.print(val, format)
• Parameters
̶ Serial: serial port object.
̶ val: the value to print - any data type.
̶ format: specifies number base for integer data types (BIN, OCT, DEC & HEX).
Or the number of decimal places for floating point data types.
• Returns
̶ The number of bytes written (long), though reading that number is optional.
• Note
̶ Serial transmission is asynchronous, therefore Serial.print() will return before any
characters have been transmitted (can use Serial.flush() to wait for outgoing serial data
transmission to complete).
̶ Flash-memory (program storage space) strings can be printed, by wrapping it with “F()”:
> Serial.print(F("Hello World"));
̶ To send a single byte, use Serial.write():
> Serial.write(65); // sends single character ‘A’ and not ASCII code for 6 and then 5
Function: Serial.flush()
• Description
̶ Waits for the transmission of outgoing serial data to complete.
• Syntax
̶ Serial.flush()
• Arduino Mega only:
̶ Serial1.flush()
̶ Serial2.flush()
̶ Serial3.flush()
• Parameters
̶ Serial: serial port object.
Example: Serial.print()
/* prints ASCII byte codes from 'A' to 'Z' in various formats */

byte bChr; // variable for ASCII byte codes

void setup()
{
Serial.begin(9600); // open serial port at 9600 bps
}

void loop()
{
// prints "CHAR DEC HEX OCT BIN" tab spaced
// and then moves cursor to the next or new line.
Serial.print("CHAR \t");
Serial.print("DEC \t");
Serial.print("HEX \t");
Serial.print("OCT \t");
Serial.print("BIN \n");
Example: Serial.print()
for(bChr = 65; bChr <= 90; bChr++) //only 'A' to 'Z' ASCII characters
{
/* print it out in many formats: */
Serial.write(bChr); // prints ASCII character letter
Serial.print('\t'); // prints a tab space

Serial.print(bChr, DEC); // print as an ASCII-encoded decimal


Serial.print('\t'); // prints a tab space

Serial.print(bChr, HEX); // print as an ASCII-encoded hexadecimal


Serial.print('\t'); // prints a tab space

Serial.print(bChr, OCT); // print as an ASCII-encoded octal


Serial.print('\t'); // prints a tab space

Serial.println(bChr, BIN); // prints as an ASCII-encoded binary


// then adds new line with “println"
delay(250); // delay between printed lines
}
while(true); // wait forever
}
// Prints:
// CHAR DEC HEX OCT BIN
// A 65 41 101 1000001
Function: Serial.println()
• Description
̶ Prints data to the serial port as human-readable ASCII character text, followed by a
newline ASCII character (10) or '\n'.
̶ This command takes the same formats as Serial.print().
• Syntax
̶ Serial.println(val)
̶ Serial.println(val, format)
• Parameters
̶ Serial: serial port object.
̶ val: the value to print - any data type.
̶ format: specifies number base for integer data types (BIN, OCT, DEC & HEX).
Or the number of decimal places for floating point data types.
• Returns
̶ The number of bytes written (long), though reading that number is optional.
Example: Serial.println()
/* Reads analog input on A0, prints the value in different formats */

int iAnalogVal = 0; // variable to hold the analog value

void setup()
{
Serial.begin(9600); // open the serial port at 9600 bps
}

void loop()
{
iAnalogVal = analogRead(A0); // read analog input on pin A0

/* print it out in many formats: */


Serial.print(iAnalogVal); // print ASCII-encoded decimal
Serial.print('\t'); // prints a tab space
Serial.print(iAnalogVal, HEX); // print ASCII-encoded hexadecimal
Serial.print('\t'); // prints a tab space
Serial.print(iAnalogVal, OCT); // print ASCII-encoded octal
Serial.print('\t'); // prints a tab space
Serial.println(iAnalogVal, BIN); // ASCII-encoded binary & new line
delay(500); // delay 500ms before next reading
}
Function: Serial.write()
• Description
̶ Writes binary data to the serial port and this data is sent as a byte or series of bytes.
̶ To send characters representing the digits of a number, use print() function instead.
• Syntax
̶ Serial.write(val)
̶ Serial.write(str)
̶ Serial.write(buf, len)
• Parameters
̶ val: a value to send as a single byte (byte, char or unsigned char).
̶ str: a string to send as a series of bytes (char).
̶ buf: an array to send as a series of bytes (byte, char or unsigned char).
̶ len: the number of bytes of the array to send.
• Returns
̶ The number of bytes written (int), though reading that number is optional.
• Note
̶ If there is enough empty space in the transmit buffer, Serial.write() will return before
any characters are transmitted over serial. If the transmit buffer is full then Serial.write()
will block or wait until there is enough space in the buffer. To avoid blocking or wait calls
to Serial.write(), first check the amount of free space in the transmit buffer by using
availableForWrite() function.
Example: Serial.write()
/* example showing how Serial.write() works */
byte bytArr[10] = {0x30,0x31,0x32,0x33}; // represents ASCII code “0-3”

void setup(){
Serial.begin(9600); // open the serial port at 9600 bps
}

void loop() {
// send a byte with the value 97, equivalent to ASCII code ‘a’
Serial.write(97); //same as using Serial.print('a') or
//same as using Serial.print(char(97))

// send the string and return length of the string excluding NULL
int iBytesSent = Serial.write("hello, bytes sent: "); //19 bytes sent

// display ASCII character text representing number of bytes sent


Serial.print(iBytesSent);

// send only the first two elements of byte array


Serial.write(bytArr, 2);

// wait forever
while(true);
}
Function: Serial.read()
• Description
̶ This function will read one byte at a time of the incoming serial data, by removing it
from the internal serial 64-byte buffer.
• Syntax
̶ Serial.read()
• Arduino Mega only:
̶ Serial1.read()
̶ Serial2.read()
̶ Serial3.read()
• Parameters
̶ Serial: serial port object.
• Returns
̶ A single byte, if incoming serial data is available (byte, char or unsigned char),
̶ Or a “-1” if no serial data is available (int).
• Note
̶ The “read()” comes from the “Stream” utility class.
Example1: Serial.read()
// code to serially receive up to four digits and a new line char
const int MAX_DIGITS = 5; // 4 digits plus NUL ('\0' -> null)
char cNumArr[MAX_DIGITS];
char cIndPos = 0;
void setup() {
Serial.begin(9600);
}
void loop()
{
while(Serial.available()>0)
{
char cByte = Serial.read();
if(cByte == '\n' || cIndPos == (MAX_DIGITS-1))
{
cNumArr[cIndPos] = '\0'; // add NULL to create a string
int iNum = atoi(cNumArr); // convert ASCII to integer number
Serial.println(iNum);
cIndPos = 0; // reset array index for next number
}
else
cNumArr[cIndPos++] = cByte; // save digit to number array
}
}
Example2: Serial.read()
// routine to control LED on pin 13 and PWM Duty Cycle on pin 3
char cCMD; // for command character
int iDC; // for PWM duty cycle
void setup(){
pinMode(LED_BUILTIN,OUTPUT);
Serial.begin(9600); // open serial port at 9600bps
Serial.println("Char 'A' followed by 'H' or 'L', controls D13 LED");
Serial.println("Char 'B' followed by an integer, sets D3 PWM DC");
}
void loop(){
while(!Serial.available());
cCMD = Serial.read();
if(cCMD == 'A'){
while(!Serial.available()); //must check again, for read() to work
cCMD = Serial.read();
if(cCMD == 'H') digitalWrite(LED_BUILTIN, HIGH);
else if(cCMD == 'L') digitalWrite(LED_BUILTIN, LOW);
}
else if(cCMD == 'B'){
iDC = Serial.parseInt();
if(iDC >= 0 && iDC <= 255) analogWrite(3, iDC);
else Serial.println("Duty Cycle not between 0 and 255");
}
}
Function: Serial.parseInt()
• Description
̶ Looks for the next valid integer in the incoming byte stream received in serial buffer.
̶ The function terminates if it times-out, as set by the Serial.setTimeout() function.
̶ Parsing stops if no characters or non-digits have been read for a configurable time-out.
̶ If no valid digits were read when the time-out occurs, 0 (zero) is returned.
• Syntax
̶ Serial.parseInt() // defaults to: Serial.parseInt(SKIP_ALL, NO_IGNORE_CHAR)
̶ Serial.parseInt(lookahead)
̶ Serial.parseInt(lookahead, ignore)
• Parameters
̶ lookahead: searches serial receive buffer for an integer number using following modes:
• SKIP_ALL: all characters other than a minus sign or digits are ignored when scanning the
serial receive buffer for an integer, this is the default mode.
• SKIP_NONE: nothing is skipped and the serial receive buffer is not touched unless the
first waiting character is a valid digit or minus sign.
• SKIP_WHITESPACE: only tabs, spaces, line feeds (NL), and carriage returns (CR) are
skipped.
̶ ignore: used to skip the indicated char in the serial receive buffer.
• For example, used to skip thousands divider (e.g. Serial.parseInt(SKIP_ALL, ',')).
• Returns
̶ The next valid integer or long number (long).
Example1: Serial.parseInt()
// Number received can be a long value because parseInt() returns long.
// Serial.parseInt() times-out after a default setting of 1s (1000 ms).
// Can adjust the time-out using Serial.setTimeout() function.
void setup(){
Serial.begin(9600);
//Serial.setTimeout(250); // adjust default time-out from 1s to 250ms
}
void loop(){
while(Serial.available()>0){
int iData = Serial.parseInt(); // SKIP_ALL and NO_IGNORE_CHAR
Serial.println(iData);
}
}

// Note -> if the following streams are receive in serial buffer:

// 3 <300ms> 1 <300ms> 4 <300ms> 5 -> 3145 obtained after 900ms


int iData = Serial.parseInt(); // 1st call -> iData holds 3145

// 3 <400ms> 1 <400ms> 4 <400ms> 5 -> 3145 obtained after 1200ms


int iData = Serial.parseInt(); // 1st call -> iData holds 314
int iData = Serial.parseInt(); // 2st call -> iData holds 5
Example1: Serial.parseInt()
// serial receive buffer -> "My name is Daniel"
int iData = Serial.parseInt(); // iData holds 0
// now serial receive buffer -> "My name is Daniel"
// serial receive buffer -> "2147483647"
long lData = Serial.parseInt(); // lData holds 2147483647
// parseInt() can return -2147483648 to 2147483647 long data type
// serial receive buffer -> "-4215"
int iData = Serial.parseInt(); // iData holds -4215
// serial receive buffer -> "I ate 15 apples"
int iData = Serial.parseInt(); // iData holds 15
// now serial receive buffer -> " apples"
// serial receive buffer -> "I ate 15 apples"
int iData = Serial.parseInt(SKIP_NONE); // iData holds 0
// now serial receive buffer -> "I ate 15 apples“
// serial receive buffer -> " 15 apples"
int iData = Serial.parseInt(SKIP_WHITESPACE); // iData holds 15
// now serial receive buffer -> " apples"
// serial receive buffer -> "Value: 3,142"
int iData = Serial.parseInt(SKIP_ALL, ','); // iData holds 3142
// Once parsing commences, ',' will be skipped or ignored in buffer
Example2: Serial.parseInt()
/* This code demonstrates the “Serial.parseInt()” function.
It looks for an ASCII string of comma-separated numeric values.
It parses them into integers and uses those to fade an RGB LED.
Example of received command string: “125,65,255\n”

Circuit, common-anode RGB LED wired with:


- Red cathode leg in series with a 220R connected to digital pin 3
- Green cathode leg in series with a 220R to connected digital pin 5
- Blue cathode leg in series with a 220R to connected digital pin 6
- Anode RGB leg connected directly to +5V */

// pins for the LEDs:


const int pinRed = 3;
const int pinGreen = 5;
const int pinBlue = 6;

void setup()
{
// open the serial port at 9600 bps
Serial.begin(9600);

// make the pins outputs


pinMode(pinRed, OUTPUT);
pinMode(pinGreen, OUTPUT);
pinMode(pinBlue, OUTPUT);
}
Example2: Serial.parseInt()
void loop()
{
// if there's any serial data available, read it
while(Serial.available() > 0)
{
// get valid integer for red setting in the incoming serial stream
int iRed = Serial.parseInt();
// get next valid integer for green setting
int iGreen = Serial.parseInt();
// get next valid integer for blue setting
int iBlue = Serial.parseInt();

// Check for newline character, indicates end of serial command


while(Serial.read() != '\n')

// if common-cathode LED, just use "constrain(color, 0, 255);"


// else constrain values to 0-255 and invert for common anode LED
iRed = 255 - constrain(iRed, 0, 255);
iGreen = 255 - constrain(iGreen, 0, 255);
iBlue = 255 - constrain(iBlue, 0, 255);
Example2: Serial.parseInt()
// fade red, green and blue legs of RGB LED
analogWrite(pinRed, iRed);
analogWrite(pinGreen, iGreen);
analogWrite(pinBlue, iBlue);

// send back three settings in comma separated hexadecimal string


Serial.print(iRed, HEX);
Serial.print(',');
Serial.print(iGreen, HEX);
Serial.print(',');
Serial.println(iBlue, HEX);

} //end of while(Serial.available()) statement

} // end of Loop()
Function: Serial.parseFloat()
• Description
̶ Looks for next valid floating point number in the byte stream received in serial buffer.
̶ The function terminates if it times-out, as set by the Serial.setTimeout() function.
̶ Parsing stops if no characters or non digits have been read for a configurable time-out.
̶ If no valid digits were read when the time out occurs , 0.0 (zero) is returned.
• Syntax
̶ Serial.parseFloat() // defaults to: Serial.parseFloat(SKIP_ALL, NO_IGNORE_CHAR)
̶ Serial.parseFloat(lookahead)
̶ Serial.parseFloat(lookahead, ignore)
• Parameters
̶ lookahead: searches serial receive buffer for a floating point number using modes:
• SKIP_ALL: all characters other than a minus sign, digits or decimal point are ignored
when scanning serial buffer for a floating point number (default mode).
• SKIP_NONE: nothing is skipped and the serial receive buffer is not touched unless the
first waiting character is valid digit, minus or decimal point.
• SKIP_WHITESPACE: only tabs, spaces, line feeds and carriage returns are skipped.
̶ ignore: used to skip the indicated char in the serial receive buffer.
• For example, used to skip thousands divider (e.g. Serial.parseFloat(SKIP_ALL, ',')).
• Returns
̶ The next valid floating point number (float).
Example: Serial.parseFloat()
// serial receive buffer -> "My name is Daniel"
float fData = Serial.parseFloat(); // fData holds 0.00
// now serial receive buffer -> "My name is Daniel"

// serial receive buffer -> "-215.45"


float fData = Serial.parseFloat(); // fData holds -215.45

// serial receive buffer -> "Result is 15.45 degrees"


float fData = Serial.parseFloat(); // fData holds 15.45
// now serial recive buffer -> " degrees"

// serial receive buffer -> "Result is 15.45 degrees"


float fData = Serial.parseFloat(SKIP_NONE); // fData holds 0.00
// now serial receive buffer -> "Result is 15.45 degrees"

// serial receive buffer -> " 58.76 degrees"


float fData = Serial.parseFloat(SKIP_WHITESPACE); // fData holds 58.76
// now serial receive buffer -> " degrees"

// serial receive buffer -> "Value: 3,142.67"


float fData = Serial.parseFloat(SKIP_ALL, ','); // fData 3142.67

// serial receive buffer -> "3,142.67"


float fData = Serial.parseFloat(SKIP_NONE, ','); // fData 3142.67
Function: Serial.peek()
• Description
̶ This function will read one byte of incoming serial data, without removing it from the
internal serial 64-byte buffer.
• Syntax
̶ Serial.peek()
• Arduino Mega only:
̶ Serial1.peek()
̶ Serial2.peek()
̶ Serial3.peek()
• Parameters
̶ Serial: serial port object.
• Returns
̶ A copy of the first byte, if incoming serial data is available (byte, char or unsigned char),
̶ Or a “-1” if no serial data is available (int).
• Note
̶ Successive calls to peek() will return the same byte, as will the next call using read().
Function: Serial.readBytes()
• Description
̶ Reads bytes from the incoming serial byte stream into a buffer array.
̶ The function terminates if:
> the determined byte length has been read into the buffer array,
> or a configurable timeout occurs, as set by Serial.setTimeout() function.
• Syntax
̶ Serial.readBytes(buffer, length)
• Parameters
̶ Serial: serial port object.
̶ buffer: the buffer to store the bytes in (char[ ] or byte[ ]).
̶ length: the number of bytes to read (int).
• Returns
̶ The number of bytes read into the buffer array.
̶ Or if no valid data was found, a zero is return.
Function: Serial.readBytesUntil()
• Description
̶ Reads bytes or characters from the serial receive buffer into an array buffer.
̶ The function terminates in this order:
> if the determined byte length has been read into the array buffer,
> if it times out, as set by Serial.setTimeout() function,
> or if the specified terminator byte or character is detected.
̶ The function will return bytes up to the last byte before the terminator character.
̶ The terminator byte or character itself is not returned in the array buffer.
• Syntax
̶ Serial.readBytesUntil(terminator, buffer, length)
• Parameters
̶ Serial: serial port object.
̶ terminator: the byte to search for (char or byte) to stop reading bytes.
̶ buffer: the buffer to store the bytes in (array of char[ ] or byte[ ]) .
̶ length: the number of bytes to read (int).
• Returns
̶ The number of bytes read into the array buffer.
̶ Or a zero is return because no bytes was received so a time-out occurred, or a
termination character was found before any data byte was received.
Example: Serial.readBytesUntil()
/* example to show how Serial.readBytesUntil() works */
char cName[11]; // stores 10 chars (0 to 9) plus null
int iLastChar;
void setup(){
Serial.begin(9600); // open the serial port at 9600 bps
}
void loop() {
Serial.println("\nEnter your name (Max 10 char)");
while(!Serial.available());
// receive up to 10 chars (0 to 9) accept '\n' that is not counted
iLastChar = Serial.readBytesUntil('\n', cName, 10);
cName[iLastChar] = '\0'; // add null to form a string
Serial.print("The name you entered is: ");
Serial.println(cName);
delay(500);
}
Make sure to select the
“NewLine” so that every time
you press the send button,
your string plus a ‘\n’ char will
be send serially to the Arduino
UNO.
Function: Serial.readString()
• Description
̶ Reads characters from the incoming serial byte stream into a String data type.
̶ The function terminates if:
> a configurable timeout occurs, as set by Serial.setTimeout() function.
• Note
̶ Used with the String data type,
̶ For example: String strBuff = Serial.readString();
• Syntax
̶ Serial.readString()
• Parameters
̶ Serial: serial port object.
• Returns
̶ A string read from the serial port buffer into a String data type.
Example: Serial.readString()
/* code to shows how to receive a string using Serial.readString() */
void setup(){
Serial.begin(9600);
}

void loop()
{
Serial.println("guess a primary color:");
while(Serial.available() == 0); // wait for data available
String strMsg = Serial.readString(); // read until timeout

// remove any \r, \n or whitespace at the end of String Message


strMsg.trim();

if(strMsg == "red")
Serial.println("red is a primary color \n");
else if(strMsg == "green")
Serial.println("green is a primary color \n");
else if(strMsg == "blue")
Serial.println("blue is a primary color \n");
else
{
Serial.print(strMsg);
Serial.println(" is not a primary color \n");
}
}
Function: Serial.readStringUntil()
• Description
̶ Reads characters from the incoming serial byte stream into a String data type.
̶ The function terminates if:
> a specified termination character is detected,
> or a configurable timeout occurs, as set by Serial.setTimeout() function.
• Note
̶ Used with the String data type,
̶ For example: String strBuff = Serial.readStringUntil('\n');
• Syntax
̶ Serial.readStringUntil(terminator)
• Parameters
̶ Serial: serial port object.
̶ terminator: the character to search for (char) to stop reading characters.
• Returns
̶ A string read from the serial port buffer, until the termination character is detected.
Example: Serial.readStringUntil()
/* shows how to compare strings using Serial.readStringUntil()*/
void setup()
{
Serial.begin(9600); // open the serial port at 9600 bps
pinMode(LED_BUILTIN,OUTPUT);
Serial.println("Send LED_ON or LED_OFF Command");
}

void loop()
{
while(!Serial.available());
// make sure to select send with ‘NewLine’ option in serial monitor
String strCmd = Serial.readStringUntil('\n');

if(strCmd.equals("LED_ON"))
digitalWrite(LED_BUILTIN, HIGH);
else if(strCmd.equals("LED_OFF"))
digitalWrite(LED_BUILTIN, LOW);
else
Serial.print(String("Incorrect Command: ") + strCmd);
}
Function: Serial.find()
• Description
̶ Reads data from the serial port buffer until the target string of given length is found.
• Syntax
̶ Serial.find(target)
• Parameters
̶ Serial: serial port object.
̶ target: the string to search for, to stop reading (char).
• Returns
̶ true, if the target string is found (boolean).
̶ false, if it times-out, as set by Serial.setTimeout() function.
• Example
void setup(){
Serial.begin(9600); // initialize serial communication
Serial.println("Only prints text after a received STX target");
}

void loop(){
while(!Serial.available() > 0);
if(Serial.find("STX")){
String strMsg = Serial.readStringUntil('\n');
if(strMsg.length() > 0) Serial.println(strMsg);
}
Function: Serial.findUntil()
• Description
̶ Reads data from the serial buffer until the target string of given length is found or a
specified termination string is found.
• Syntax
̶ Serial.findUntil(target, terminator)
• Parameters
̶ Serial: serial port object.
̶ target: the main string to search for, to stop reading (char).
̶ terminator: the other string to search for, to stop reading (char).
• Returns
̶ true, if the target string is found or a specified termination string is found (boolean).
̶ false, if it times-out, as set by Serial.setTimeout() function.
Function: Serial.setTimeout()
• Description
̶ Serial.setTimeout() sets the maximum milliseconds to wait for serial data when using:
> Serial.parseInt(),
> Serial.parseFloat(),
> Serial.readBytes(),
> Serial.readBytesUntil(),
> Serial.readString(),
> Serial.readStringUntil(),
> Serial.find() or
> Serial.findUntil()
̶ The function default timeout is 1000 milliseconds (one second).
• Syntax
̶ Serial.setTimeout(time)
• Parameters
̶ Serial: serial port object.
̶ time: timeout duration in milliseconds (long).
Function: serialEvent()
• Description
̶ Called at the end of loop() when serial data is available.
̶ Use Serial.read() to capture this data.
• Syntax
void serialEvent(){
//statements
}
• Arduino Mega only:
void serialEvent1(){
//statements
}

void serialEvent2(){
//statements
}

void serialEvent3(){
//statements
}
Example: serialEvent()
String strInput = ""; // string to hold incoming serial data
volatile boolean strComplete = false; // string received complete flag
void setup() {
Serial.begin(9600); // initialize serial to 9600 bits/second
strInput.reserve(50); // reserve 50 bytes for the strInput
}

void loop() {
if(strComplete) {
Serial.print(strInput); // print string when complete
strInput = ""; // clear the string
strComplete = false; // Reset complete flag
}
}
// serialEvent occurs whenever a new data byte comes into hardware serial RX.
// Routine is executes between each time loop() run, so using delay inside loop()
// can delay response and multiple bytes of serial data may be available.
void serialEvent() {
while(Serial.available()) {
char inChar = (char)Serial.read(); // get the new byte
strInput += inChar; // add it to the strInput
// if incoming character is a newline, set flag so main loop knowns
if(inChar == '\n') strComplete = true;
}
}
EXERCISE
1. Discuss the purpose and default operation of the Arduino “Serial.begin()” library function?
2. Describe the operation of the Arduino “Serial.end()” library function?
3. Describe the operation of the Arduino “Serial.available()” library function?
4. Create an Arduino C program without comments that serially transmits back a byte of
data at 9600 bits/s baud rate, when it is serially received. The transmitted message must
display “Received data is: xxx”, where “xxx” represents the decimal ASCII value of the
received byte number.
5. Design an Arduino C program without comments that serially transmits back a byte of
data at 115200 bits/s baud rate, when it is serially received. The transmitted line message
must display “Received hex byte: xx”, where “xx” represents the hexadecimal value of the
received byte followed by “ Binary: xxxxxxxx”, where “xxxxxxxx” represents the binary
value of the received byte number.
6. Explain how are numbers, floats, characters and string data printed to the serial port
when using the Arduino “Serial.print()” library function?
7. What will the following Arduino “Serial.print()” functions, print to the serial port:
a) Serial.write(65);
b) Serial.print(65);
c) Serial.print(65, DEC)
d) Serial.print(65, HEX)
e) Serial.print(65, BIN)
f) Serial.print(9.25, 3);
EXERCISE
8. Design an Arduino C program without comments to serial print at 9600 bits/s baud rate, a
tab spaced text heading of: “CHAR DEC HEX BIN”. Then print a tab spaced line with the
four different number formats for ASCII code 48 (‘0’) to 57 (‘9’) under the relevant
heading on each separated line. Once this table has been printed, stop code execution.
9. Develop an Arduino C program without comments to serial print at 38400 bits/s the
analog obtained value on pin A5, every two and a half seconds. On each separate line
print the analog obtained result as a hexadecimal value and then after a tab space the
binary equivalent value.
10. Explain the operation of the Arduino “Serial.read()” library function and discuss what it
returns?
11. Explain the operation of the Arduino “Serial.peek()” library function and discuss what it
returns?
12. Elaborate on the operation of the Arduino “Serial.parseInt()” function including when the
function terminates and discuss what it returns?
13. Design an Arduino C program without comments to retrieve two comma separated
integer values from an incoming serial byte stream using the “Serial.parseInt()” function.
Thereafter wait until a new line termination character (‘\n’) in the serial byte stream is
received and then send the two retrieved integer values back on two separated lines, at
57600 bits/s baud rate.
14. Create an Arduino C program without comments to retrieve two comma separated
floating point numbers from an incoming serial byte stream using the “Serial.parseFloat()”
function. Thereafter wait until a new line termination character (‘\n’) is received in the
serial byte stream then send the sum of the two retrieved floating point numbers with
one decimal place, back at 9600 bits/s baud rate.
EXERSICE
15. Describe the functionality and difference between the Arduino “Serial.readBytes()” and
the “Serial.readBytesUntil()” library functions?
16. Describe the functionality and difference between the Arduino “Serial.readString()” and
the “Serial.readStringUntil()” library functions?
17. Develop an Arduino C program without comments to serially send at 9600 bit/s the
following string “Please enter your name” and then use the “Serial.readStringUntil()”
function to retrieve the returned serial transmitted string name after a newline char (‘\n’)
is detected. Afterwards, serially send the following string “The name you entered is: ”
followed by the retrieved name on a new line. The Arduino C program must then repeat
this process again after half a second on the next line.
18. Describe the functionality and difference between the Arduino “Serial.find()” and the
“Serial.findUntil()” library functions?
19. State which Arduino functions the “Serial.setTimeout()” function is used to set the
maximum milliseconds to wait for serial data and the default timeout of this function?
20. Design an Arduino C program that uses the “serialEvent()” function to capture incoming
serial byte stream and save it into a “String” datatype variable called “strInput”. The
“strInput” variable must have space for 100 characters. When the newline termination
character (‘\n’) in the serial byte stream is received, the program in the “loop()” function
must know and then send out the received string, at 9600 bits/s baud rate. The Arduino C
program must then be ready to receive the next incoming serial byte stream string.

You might also like