Serial Communication – UART

The Universal Asynchronous Receiver/Transmitter (UART) takes bytes of data and transmits the individual bits in a sequential fashion. At the destination, a second UART re-assembles the bits into complete bytes. Each UART contains a shift register, which is the fundamental method of conversion between serial and parallel forms. Serial transmission of digital information (bits) through a single wire or other medium is less costly than parallel transmission through multiple wires.

Character framing

The right-most (least significant) data bit is always transmitted first. If parity is present, the parity bit comes after the data bits but before the stop bit(s).
Bit number 1 2 3 4 5 6 7 8 9 10 11
  Start bit 5–8 data bits Stop bit(s)
  Start Data 0 Data 1 Data 2 Data 3 Data 4 Data 5 Data 6 Data 7 Stop

The idle, no data state is high-voltage, or powered. This is a historic legacy from telegraphy, in which the line is held high to show that the line and transmitter are not damaged. Each character is sent as a logic low start bit, a configurable number of data bits (usually 8, but legacy systems can use 5, 6, 7 or 9), an optional parity bit, and one or more logic high stop bits.

The start bit signals the receiver that a new character is coming. The next five to eight bits, depending on the code set employed, represent the character. Following the data bits may be a parity bit. The next one or two bits are always in the mark (logic high, i.e., ‘1’) condition and called the stop bit(s). They signal the receiver that the character is completed. Since the start bit is logic low (0) and the stop bit is logic high (1) there are always at least two guaranteed signal changes between characters.

If the line is held in the logic low condition for longer than a character time, this is a break condition that can be detected by the UART.

 

Arduino has a class for serial communication called Serial.

 

Serial – 

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): Serial. It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via USB. Thus, if you use these functions, you cannot also use pins 0 and 1 for digital input or output.

 

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().

 

Commonly used MEMBER FUNCTIONS of Serial class

begin() – 

Sets the data rate in bits per second (baud) for serial data transmission. For communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200. You can, however, specify other rates – for example, to communicate over pins 0 and 1 with a component that requires a particular baud rate.

An optional second argument configures the data, parity, and stop bits. The default is 8 data bits, no parity, one stop bit.

Syntax

Serial.begin(speed)
Serial.begin(speed, config)

Parameters

speed: in bits per second (baud) – long
config: sets data, parity, and stop bits. Valid values are :

 

available() – 

Get the number of bytes (characters) available for reading from the serial port. This is data that’s already arrived and stored in the serial receive buffer (which holds 64 bytes). available() inherits from the Stream utility class.

Syntax

Serial.available()

Returns

the number of bytes available to read

 

Serial.find() – 

Serial.find() reads data from the serial buffer until the target string of given length is found. The function returns true if target string is found, false if it times out.

Syntax

Serial.find(target)

Parameters

target : the string to search for (char)

Returns

boolean

 

print() – 

Prints data to the serial port as human-readable ASCII text. This command can take many forms. Numbers are printed using an ASCII character for each digit. Floats are similarly printed as ASCII digits, defaulting to two decimal places. Bytes are sent as a single character. Characters and strings are sent as is. For example:

  • Serial.print(78) gives “78”
  • Serial.print(1.23456) gives “1.23”
  • Serial.print(‘N’) gives “N”
  • Serial.print(“Hello world.”) gives “Hello world.”

 

An optional second parameter specifies the base (format) to use; permitted values are BIN (binary, or base 2), OCT (octal, or base 8), DEC (decimal, or base 10), HEX (hexadecimal, or base 16). For floating point numbers, this parameter specifies the number of decimal places to use. For example:

  • Serial.print(78, BIN) gives “1001110”
  • Serial.print(78, OCT) gives “116”
  • Serial.print(78, DEC) gives “78”
  • Serial.print(78, HEX) gives “4E”
  • Serial.println(1.23456, 0) gives “1”
  • Serial.println(1.23456, 2) gives “1.23”
  • Serial.println(1.23456, 4) gives “1.2346”

Syntax

Serial.print(val) 
Serial.print(val, format) 

Parameters

val: the value to print – any data type

format: specifies the number base (for integral data types) or number of decimal places (for floating point types)

Returns

size_t (long): print() returns the number of bytes written, though reading that number is optional

 

println() – 

Prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or ‘\r’) and a newline character (ASCII 10, or ‘\n’). This command takes the same forms as Serial.print().

Syntax

Serial.println(val) 
Serial.println(val, format)

Parameters

val: the value to print – any data type 

format: specifies the number base (for integral data types) or number of decimal places (for floating point types)

Returns

size_t (long): println() returns the number of bytes written, though reading that number is optional

 

read() – 

Reads incoming serial data. read() inherits from the Stream utility class.

Syntax

Serial.read()

Parameters

None

Returns

the first byte of incoming serial data available (or -1 if no data is available) – int

 

Serial.readBytes() – 

Serial.readBytes() reads characters from the serial port into a buffer. The function terminates if the determined length has been read, or it times out

Serial.readBytes() returns the number of characters placed in the buffer. A 0 means no valid data was found.

Syntax

Serial.readBytes(buffer, length)

Parameters

buffer: the buffer to store the bytes in (char[] or byte[])
length : the number of bytes to read (int)

Returns

byte

 

Serial.readBytesUntil() – 

Description

Serial.readBytesUntil() reads characters from the serial buffer into an array. The function terminates if the terminator character is detected, the determined length has been read, or it times out .

Serial.readBytesUntil() returns the number of characters read into the buffer. A 0 means no valid data was found.

Syntax

Serial.readBytesUntil(characterbufferlength)

Parameters

character : the character to search for (char)
buffer: the buffer to store the bytes in (char[] or byte[]) length : the number of bytes to read (int)

Returns

byte

 

write() – 

Writes binary data to the serial port. This data is sent as a byte or series of bytes; to send the characters representing the digits of a number use the print() function instead.

Syntax

Serial.write(val) 
Serial.write(str) 
Serial.write(buf, len) 

Parameters

val: a value to send as a single byte

str: a string to send as a series of bytes

buf: an array to send as a series of bytes

len: the length of the buffer

Returns

byte
write() will return the number of bytes written, though reading that number is optional

 

end() – 

Disables serial communication, allowing the RX and TX pins to be used for general input and output. To re-enable serial communication, call Serial.begin().

Syntax

Serial.end()

Parameters

none

Returns

nothing

 

serialEvent() – 

Called when data is available. Use Serial.read() to capture this data. 

Syntax

void serialEvent(){
//statements
}

 

EXAMPLE

This example shows you how to use switch to turn on one of several different LEDs based on a byte of data received serially. The sketch listens for serial input, and turns on a different LED for the characters a, b, c, d, or e.

Hardware Required

  • Arduino Board
  • (5) LEDs
  • (5) 220 ohm resistors
  • breadboard
  • hook-up wire

Circuit

Five LEDs are attached to digital pins 2, 3, 4, 5, and 6 in series through 220 ohm resistors.

To make this sketch work, your Arduino must be connected to your computer. Open the Serial Monitor, and send the characters a, b, c, d, or e, or anything else.

switchCase2_bb

Schematic:

switchcase2forLoop2_schem

Code /*

 Switch statement with serial input

 Demonstrates the use of a switch statement. The switch
 statement allows you to choose from among a set of discrete values
 of a variable. It's like a series of if statements.

 To see this sketch in action, open the Serial monitor and send any character.
 The characters a, b, c, d, and e, will turn on LEDs. Any other character will turn
 the LEDs off.
*/
void setup() {
 // initialize serial communication:
 Serial.begin(9600); 
 // initialize the LED pins:
 for (int thisPin = 2; thisPin < 7; thisPin++) {
 pinMode(thisPin, OUTPUT);
 } 
}
void loop() {
// read the sensor:
 if (Serial.available() > 0) {
 int inByte = Serial.read();
 // do something different depending on the character received. 
 // The switch statement expects single number values for each case;
 // in this exmaple, though, you're using single quotes to tell
 // the controller to get the ASCII value for the character. For 
 // example 'a' = 97, 'b' = 98, and so forth:
switch (inByte) {
 case 'a': 
 digitalWrite(2, HIGH);
 break;
 case 'b': 
 digitalWrite(3, HIGH);
 break;
 case 'c': 
 digitalWrite(4, HIGH);
 break;
 case 'd': 
 digitalWrite(5, HIGH);
 break;
 case 'e': 
 digitalWrite(6, HIGH);
 break;
 default:
 // turn all the LEDs off:
 for (int thisPin = 2; thisPin < 7; thisPin++) {
 digitalWrite(thisPin, LOW);
 }
 } 
 }
} 

Demo Project Using UART

Share