0% found this document useful (0 votes)
37 views73 pages

MODULE 2 - For - Programming - For - Iot - Boards

MODULE 2_for_Programming_for_iot_boards

Uploaded by

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

MODULE 2 - For - Programming - For - Iot - Boards

MODULE 2_for_Programming_for_iot_boards

Uploaded by

utkarshbmathur04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Module 2

The difference between Microcontroller and Microprocessor


• Microprocessors have the only CPU inside them and no in-
memory support
• Microcontrollers, on the other side, has CPU, RAM, ROM
and other peripherals which are all embedded on the chip.
Microcontroller
• A microcontroller is a small computer typically used to control electronic
devices. It is often used in Internet of Things (IoT) applications because it is
inexpensive, has low power consumption, and can easily integrate into
various devices.
• A microcontroller is a single chip that contains a processor, memory, and
input/output ports.
• The processor runs instructions, the memory stores data and programs, and
the I/O ports let the microcontroller communicate with the environment
using sensors and tools.
• Many different microcontrollers are available in the market, each with its
features and capabilities.
• Some common microcontrollers in IoT applications include Arduino,
Raspberry Pi, and ESP8266.
• A microcontroller needs to be given instructions, and programming
languages like C or C++ can be used in an IoT application. This can be done
with a computer and a USB or serial port connection.
The role of Microcontrollers in IoT
Systems
• Small computer chips called microcontrollers are often
used in Internet of Things (IoT) systems to control and
monitor different systems and devices.
• They help to manage how the devices (like sensors,
actuators, and other electronic parts) work and behave
while processing and sending data.
• Microcontrollers are essential for connecting to and
communicating with other systems and devices in an
IoT system.
• They gather sensor data, process it, and send it via
wired or wireless communication protocols to other
devices or systems.
Which microcontroller is suitable for IoT

• Several microcontrollers are suitable for use in IoT applications, including −


• ESP32 − This is a good choice for Internet of Things projects because it has WiFi and
Bluetooth, a fast processor, and uses little energy.
• Arduino − Arduino boards are popular for Internet of Things projects because they
are easy to use and not too expensive. They have many features, like digital and
analog inputs and outputs, and they support different programming languages.
• Raspberry Pi − The Raspberry Pi is a small, low-cost computer, popular in IoT
projects because of its versatility and ability to run a full operating system. It can
build many IoT devices, from simple sensors to complex systems.
• STM32 − The STM32 family of microcontrollers is widely used in IoT applications due
to their high-speed processing capabilities, low power consumption, and support for
various communication protocols.
• ATtiny − The ATtiny microcontroller is affordable for basic Internet of Things projects.
It has digital and analog inputs and outputs and can be programmed with Arduino.
Arduino Pin Diagram
Arduino Pin Diagram contd…
• Arduino Uno consists of 14 digital input/output pins (of which 6 can be used as
PWM outputs), 6 analog inputs, a 16 MHz crystal oscillator, a USB connection, a
power jack, an ICSP header, and a reset button
• Power Jack: Arduino can be powered either from the PC through a USB or
through an external source like an adaptor or a battery. It can operate on an
external supply of 3V to 5V. Power can be applied externally through the pin Vin.
• Digital Inputs: It consists of 14 digital inputs/output pins, each of which provides
or takes up 40mA current. Some of them have special functions like pins 0 and
1, which act as Rx and Tx respectively, for serial communication, pins 2 and 3-
which are external interrupts, pins 3,5,6,9,11 which provides pwm output and
pin 13 where the LED is connected.
• Analog inputs: It has 6 analog input/output pins, each providing a resolution of
10 bits.
• Reset: It resets the microcontroller when low.
IDE: Integrated Development
Environments
• there are several integrated development environments (IDEs) that
facilitate product development and enable teams to integrate
essential elements quickly, build, release and scale.
Features of IDE
• Device Management: Registering, configuring, and monitoring IoT devices, including
provisioning, firmware updates, and remote management.
• Data Visualization: Customizable dashboards for real-time monitoring and analysis of
IoT data, facilitating data-driven decisions.
• Connectivity and Integration: Support for various IoT protocols, cloud platforms, and
databases, enabling seamless communication between devices and services.
• Rule Engine and Automation: Definition of rules, triggering actions, and task
automation based on specific conditions or events in the IoT system.
• Security and Privacy: Authentication, access control, encryption, and secure
communication protocols to safeguard IoT devices and data.
• Scalability and Performance: Optimization for large-scale IoT deployments, managing
numerous devices and processing high volumes of data.
1. Arduino
• Arduino is a company based in Italy that manufactures
microcontroller boards, interactive objects, and kits that has created a
full IDE to work on the hardware that they manufacture.
• It is the most preferred IDEs among all on the list. It is a complete
package with many examples and pre-loaded libraries.
• This IDE includes support for the C and C++ programming languages
for programmable microcontrollers.
2. Raspbian
• Created specifically for raspberry pi boards.
• This IDE comes with many packages and examples.
• Unlike Arduino IDE, it is not a part of the parent organization “The
Raspberry Pi Foundation”, but was created by some enthusiasts.
• It is probably one of the best IDEs available for Raspberry Pi.
• It comes with over 35000 packages and pre-compiled software
bundled in for easy installation.
3. OpenSCADA 1.1
• Open SCADA is the companion project to Eclipse SCADA which is a
project as a part of the Eclipse IoT Industry Working Group.
• It is based on the modern system design that provides security as well
as flexibility.
• It provides a set of independent tools that can be combined in many
ways by providing several libraries, interface apps, configuration tools,
and front and back-end applications.
4. PlatformIO 5.2.0
• It is a cross-platform IDE with a unified debugger.
• PlatformIO is specifically used for IoT environment development.
• It contains over 400 embedded boards, 20+ development platforms,
and many frameworks to choose from.
• With its excellent interface and modern approach, it is easy to use
and update.
5. Eclipse IoT project (Kura) 5.0.0
• The Eclipse Kura is a Java-based open-source development framework
for applications on the Internet of Things.
• Exceptionally built for projects like Eclipse IoT challenge, Industrial
Equipment Monitoring, etc.
• It is perfectly inclined towards development in the IoT field.
• The best part of using Kura is that it aggregates the open-source
implementations for the least common applications applicable to
M2M (Machine to Machine) applications.
IoT shields
• Most IoT development boards include Wi-Fi and Bluetooth capabilities,
but if you want to add cellular connectivity to an IoT development board,
you might need an IoT shield.
• Breakout boards (sometimes called shields, HATs, or bonnets) are add-on
devices that make it possible to control an IoT device via cellular
protocols such as 4G.
• IoT shields are add-on boards that grant further connectivity capabilities
to microcontrollers and SBCs.
• For example, if you have a Raspberry Pi, you can purchase add-on cards
to allow your SBC to connect via different cellular protocols, such as
GPRS, 3G, 4G/LTE
IoT Shield Boards
1. Advanced BLE-CELL (ABC Board): The ABC Board from Contextual
Electronics builds out a Raspberry Pi HAT with Bluetooth and cellular on it.
2. Botletics SIM7000 Arduino Shield: This is an Arduino-compatible shield
providing 4G LTE-M, NB-IoT, and 2G connectivity along with LiPo/Solar
support, and GPS.
3. Mikroe LTE IoT 2 Click: The LTE IoT 2 Click is a Click Board™ built for
wireless connectivity, offering LTE Cat-M1 and NB-IoT functionality to
support a variety of M2M and IoT applications.
4. Hologram Nova: A cellular modem built for IoT development with single-
board computer compatibility, the Hologram Nova includes access to
Hologram developer tools for easy modem and data management.
Arduino Shields
• The Arduino shields are the boards, which
can be plugged on the top of the PCB. The
shields further extend the potential of the
PCB's. The production of shields is cheap. It is
also easy to use. There are various types of
Arduino shields that can be used for different
purposes. For example, the Xbee shield.
• The Xbee shield can be used for wireless
communication between multiple Arduino
boards over distances upto 300 feet using the
Zigbee Module.
Arduino IDE for Programming
Microcontrollers
• Arduino Integrated Development Environment (IDE) is a
cross-platform application used for coding and
uploading programs to Arduino boards as well as other
third-party microcontrollers available in the market.
• The Arduino IDE is an open-source software, which is
used to write and upload code to the Arduino boards.
• The IDE application is suitable for different operating
systems such as Windows, Mac OS, and Linux.
• It supports the programming languages C and C++.
IDE version Menu Bar

File Name
Tool Bar

Text Editor

Serial
Monitor
Connect
ed Board
and Port
Toolbar Button

• Upload
• The Upload button compiles and runs our code written on the screen. It further
uploads the code to the connected board. Before uploading the sketch, we
need to make sure that the correct board and ports are selected.
• Start Debugging
• It is used to debug the program.
• Verify
• The Verify button is used to check the compilation error of the sketch or the
written code.
• Serial Monitor
• The serial monitor button is present on the right corner of the toolbar. It opens
the serial monitor.
• Serial Plotter
• The serial Plotter is used to plot the graph on a Serial monitor.
5 Steps to program an Arduino
• Programs written in Arduino are known as sketches. A basic sketch
consists of 3 parts
a. Declaration of Variables
b. Initialization: It is written in the setup () function.
C. Control code: It is written in the loop () function.
• The sketch is saved with .ino extension. Any operations like verifying,
opening a sketch, saving a sketch can be done using the buttons on the
toolbar or using the tool menu.
• The sketch should be stored in the sketchbook directory.
• Choose the proper board from the tools menu and the serial port
numbers.
• Click on the upload button or chose upload from the tools menu. Thus
the code is uploaded by the bootloader onto the microcontroller.
Arduino Coding Basics
• Coding Screen: The coding
screen is divided into two
blocks.
• The setup is considered as
the preparation block,
• while the loop is
considered as the
execution block.
• The set of statements in the setup and loop blocks are enclosed with the
curly brackets. We can write multiple statements depending on the coding
requirements for a particular project.
For example:
void setup ( )
{
Coding statement 1;
Coding statement 2;
}
void loop ( )
{
Coding statement 1;
Coding statement 2;
}
• Setup:
• It contains an initial part of the code to be executed.
• The pin modes, libraries, variables, etc., are initialized in the setup section.
• It is executed only once during the uploading of the program and after reset
or power up of the Arduino board.

• Loop:
• The loop contains statements that are executed repeatedly.
• The section of code inside the curly brackets is repeated depending on the
value of variables.
Arduino Syntax
• The two functions that encapsulate the pieces of code in the Arduino program are
shown below:
• void setup ( )
• void loop ( )
• Functions:
• The setup and loop functions have void keywords hence these functions do not return any
value
• The multiple lines of code that a function encapsulates are written inside curly brackets.
• Every closing curly bracket ' } ' must match the opening curly bracket '{ ' in the code.
• We can also write our own functions.
• Spaces: Arduino ignores the white spaces and tabs in the coding statements.
• Semicolon: It is the statement terminator as in the C as well as C++
Program Flow
• Setup(): Acts as and entry point
• Here, the processor enters our code, and the
execution of the code begins.
• After the setup, the execution of the statement in
the loop begins.
• loop(): runs over and over again
Basic Arduino functions
• Time in Arduino: The time in Arduino programming is measured in a millisecond. Where,
1 sec = 1000 milliseconds.
• pinMode ( ): The specific pin number is set as the INPUT or OUTPUT in the pinMode ()
function. The Syntax is: pinMode (pin, mode) where:
• pin: It is the pin number. We can select the pin number according to the requirements.
• Mode: We can set the mode as INPUT or OUTPUT according to the corresponding pin number.
• pinMode (12, OUTPUT);
• digitalWrite( ): The digitalWrite ( ) function is used to set the value of a pin as HIGH or
LOW.
• The syntax is: digitalWrite( pin, value HIGH/LOW)
• digitalRead () function will read the HIGH/LOW value from the digital pin
• analogRead(pin): Reads and returns the analog value from that pin.
• analogWrite(pin, value): Writes the analog value to that pin.
• delay ( ): The delay () function is a blocking function to pause a program from doing a task
during the specified duration in milliseconds.
• serial.begin(bit-rate): Sets the beginning of serial communication by
setting the bit rate.
Functions
• Sometimes, we need to write our functions.
• Function return type: We need a return type for a function.
• For example, we can store the return value of a function in a variable.
• We can use any data type as a return type, such as float, char, etc.
• Function name: It consists of a name specified to the function. It
represents the real body of the function.
• Function parameter: It includes the parameters passed to the function.
• The parameters are defined as the special variables, which are used to pass
data to a function.
• The function must be followed by parentheses ( ) and the semicolon ;
• The actual data passed to the function is termed as an argument.
Example: Add two numbers
void setup()
{
Serial.begin(9600);
}
void loop() {
int a = 5; // initialization of values to the variables a and b
int b = 4;
int c;
c = myAddfunction(a, b); // c will now contains the value 9
Serial.println(c); // to print the resulted value
delay(1000); // time delay of 1 second or 1000 milliseconds
}
int myAddfunction(int i, int j)
{
int sum;
sum = i + j;
return sum;
}
Arduino Data Types byte
It is considered as an unsigned number of 8 bits or 1 byte,
which stores values from 0 to 255.
• The data types that we will use in The syntax is:
the Arduino are listed below: byte var = val;
where,
• void Data Type var is a variable and
• int Data Type val is the value assigned to the variable
For example: byte c=20;
• Char Data Type
• Float Data Type
word
• Double Data Type It is considered as an unsigned number of 16 bits or 2 bytes,
• Unsigned int Data Type which stores values from 0 to 65535.
The syntax is:
• short Data Type word var = val;
where,
• long Data Type var is a variable
• Unsigned long Data Type val is the value assigned to the variable
For example,
• byte data type word c = 2000;
• word data type
Arduino Variables
• Consider the example:
• int pin = 8;
• Here, the int data type is used to create a variable named pin that
stores the value 8. It also means that value 8 is initialized to the
variable pin.
• We can refer the declared variable further in our
program or code. //For example,
• For example, 1.int LEDpin = 7;
2.int pin1 = LEDpin;
• pinMode(pin, OUTPUT); 3.LEDpin = 13;
//The LEDpin now contains the value 13 instead of 7.
But, value of pin1 is still 7.
• Variables Scope: It means that in how many ways the variables can be
declared.
• The variables can be declared in two ways in Arduino, which are listed
below:
• Local variables
• Global variables
• Local Variables:
• The local variables are declared within the function.
• The variables have scope only within the function.
• Global Variables:
• The global variables can be accessed anywhere in the program.
• The global variable is declared outside the setup() and loop() functions.
//Local Variable //Global variable

void setup() int LEDpin = 8;


{ void setup()
Serial.begin(9600); {
} pinMode(LEDpin, OUTPUT);
void loop() }
{ void loop()
int x = 3; {
int b = 4; digitalWrite(LEDpin, HIGH);
int sum = 0; }
sum = x + b;
Serial.println(sum);
}
Constants
• Logical level Constants: true or false
• Pin level Constants: HIGH or LOW (high=3V or 5V, low=0V)
• LED_BUILTIN Constant: The Arduino boards have built-in LED
connected in series with the resistor. Most Arduino boards have the
LED_BUILTIN connected to Pin number 13
• Constant Keyword: The name const represents the constant keyword.
It modifies the behavior of the variables in our program.

1.const int a =2;


2.//....
3.a = 7; // illegal - we cannot write to or modify a con
stant
• #define: The #define in Arduino is used to give a name to the constant
value. It does not take any memory space on the chip.
• #define LEDpin = 12 // incorrect statement
• #define LEDpin 12; // incorrect statement

• #define LEDpin 12 // correct syntax


Arduino Operators
• The types of Operators classified in Arduino are:
• Arithmetic Operators
• Compound Operators
• Boolean Operators
• Comparison Operators
• Bitwise Operators
Constructs
• Arduino If statement: if ( ) statement checks for the condition and then executes a
statement or a set of statements.
• Arduino if-else and else-if: The condition in the else statement is executed if the
result of the If ( ) statement is false.
• Arduino for Loop: The statements inside the curly brackets under for loop are
executed repeatedly according to the specified condition.
• Arduino while loop: The while loop() is the conditional loop that continues to
execute the code inside the parentheses until the specified condition becomes
false.
• Arduino switch case: The switch case controls the flow of the program by
executing the code in various cases. The break keyword is used at the end of each
case.
Interfacing with sensors & actuators
• Sensors are…
• Electronic element
• Convert physical quantity/measurements into electrical signals
• Can be analog or digital
• Type of sensors
• Temperature
• Humidity
• Light
• Sound
• Accelerometer
• Etc.
Sensor interface with Arduino
• As an example, we will take
one sensor to demonstrate
the interfacing of sensor
• Digital Humidity and
Temperature sensor (DHT)
• Pins:
• Pin1: Data/signal
• Pin2: Vcc/Power supply
• Pin3: NC / not used
• Pin4: Ground
DHT Sensor Library
• Arduino supports a special
library for the DHT sensor
(DHT11 and DHT22)
• Provides the functions to read
the temperature and humidity
values from the data pin
• dht.readHumidity()
• dht.readTemperature()
Example: Install DHT Sensor Library

• Go to sketch-> Library
Manager->search for DHT->
Install.

• DHT= Digital Temperature


and Humidity
DHT Code
#include "DHT.h" void loop() {
#define DHTPIN 4
#define DHTTYPE DHT11 temp=Dht.readTemperature();

DHT Dht(DHTPIN, DHTTYPE); humidity=Dht.readHumidity();


float temp; Serial.print("Temprature = ");
float humidity; Serial.print(temp);
Serial.print("Humidity = ");
void setup() { Serial.println(humidity);
Dht.begin();
Serial.begin(9600); delay(2000);
}
}
Serial Monitor Display
Universal Asynchronous Receiver
Transmitter (UART) Protocol
• UART means Universal Asynchronous Receiver Transmitter Protocol
• UART is used for serial communication from the name itself we can
understand the functions of UART,
• where U stands for Universal which means this protocol can be applied to any
transmitter and receiver, and
• A is for Asynchronous which means one cannot use a clock signal for the
communication of data and
• R and T refers to Receiver and Transmitter hence UART refers to a protocol in
which serial data communication will happen without a clock signal.
UART Basics
• Serial Communication:
• Two wires are established here in which only
one wire is used for transmission whereas the
second wire is used for receiving.
• Data format and transmission speeds can be
configured here.
• So, before starting with the communication
define the data format and transmission
speed.
• Less complex as only two lines are there.
• Parallel Communication
• In parallel communication multiple buses are
required.
• Parallel communication is good in terms of
speed.
• More complex as more no of lines are there
How UART Works
• UART operates by transmitting data as a series of bits, including a
start bit, data bits, an optional parity bit, and stop bit(s).
• In parallel communication, multiple bits are transmitted
simultaneously. In UART data is sent serially, one bit at a time.
• As the name reveals the protocol operates asynchronous which
means that it doesn't rely on a shared clock signal. Instead, it uses
predefined baud rates to determine the timing of data bits.
• As seen in the image above when using parallel communication an 8-
bit message would require eight cables while serial communication
only requires one cable for sending messages and one for receiving.
• DEVICE A has transmitter PIN
and a receiver pin;
• DEVICE B has a receiver and
transmission pin.
• The Transmitter of DEVICE A
should be connected to the
receiver pin of DEVICE B and
• the transmitter pin of DEVICE
B should be connected to the
receiver pin of DEVICE A.
• If DEVICE A wants to send
data, then it will be sending
data on the transmitter’s pin
and here receiver of this
DEVICE B will receive it
• First, define the speed of both devices.
• Now, configure the speed of DEVICE A and B for data transmission
which is referred to as Baud Rate.
• So here Baud Rate will be the same for DEVICE A and B otherwise both
devices cannot understand at what speed data is coming.
• After that, configure the data length so here DEVICE A and DEVICE B
both are configured at fixed data length.
• If DEVICE A is transmitting data, then it is configured with fixed data.
Like if DEVICE A is configured with the eight-bit size of data then DEVICE
B should also be configured at the same size of data which is eight bits.
Components
• The key components of UART include the transmitter, receiver, and baud
rate.
• The transmitter collects data from a source, formats it into serial bits, and
sends it via a TX (Transmit) pin.
• The receiver receives it via an RX (Receive) pin, processes incoming serial
data, and converts it into parallel data for the host system.
• The baud rate determines the speed of data transmission.
• The baud rate is specified in bits per second (bps) and represents the number of bits
transmitted in one second.
• In UART, both the transmitting and receiving devices must agree on the same baud
rate to ensure successful communication.
• When programming your Arduino, common baud rates are 9600, 115200, 4800, and
57600.
• E.g.: Serial.begin(9600);
Flow Control in UART
• UART Flow Control is a method for slow and fast devices to communicate with each
other over UART without the risk of losing data.
• Consider the case where two units are communicating over UART. A transmitter T
sends a long stream of bytes to a receiver R.
• If R is a slower device than T, and R cannot keep up.
• It needs to either do some processing on the data or empty some buffers before it
can keep receiving data.

• R needs to tell T to stop transmitting for a while. This is where flow control comes in.
• Flow control provides extra signaling to inform the transmitter that it should stop
(pause) or start (resume) the transmission.
UART Messages
• In UART communication,
each data frame is
encapsulated by start and
stop bits.
• These bits serve a vital role in
establishing the boundaries
of data transmission and
ensuring synchronization
between the sender and
receiver.
UART Messages: Start Bit
• A single start bit is transmitted at the beginning of each UART frame.
• The primary purpose of the start bit is to indicate the start of the data
transmission and prepare the receiver for data reception.
• The start bit is always logic low (0) for UART communication.
UART Messages : Data Bits
• Data bits are a fundamental component of UART communication as
they carry the actual information to be transmitted.
• The number of data bits in a UART frame can vary, but a common and
widely used configuration is 8 bits.
UART Messages: Character Size
• The character size in UART communication is defined by the number of
data bits within a frame.
• It's essential to choose the appropriate character size to match the
requirements of the data being transmitted. Here are some common
character size configurations:
• 8-Bit: This is the most prevalent character size in UART communication. It allows for
the transmission of a byte of data, which can represent a wide range of values,
including ASCII characters, numerical values, and more.

• 7-Bit: In cases where data size needs to be smaller, 7-bit character size is utilized.
It's suitable for applications that require less data overhead.

• 6-Bit: For even more compact data representation, 6-bit character size can be used.
UART Messages: Data Integrity
• The accuracy of data transmission in UART communication relies on
the proper configuration of data bits.
• It's essential that both the transmitter and receiver agree on the
number of data bits and their encoding.
• If the configuration is incorrect, data can be corrupted.
• For example, if the transmitter sends data as 8-bit characters, but the
receiver is configured to expect 7-bit characters, data may be
misinterpreted, leading to errors in the received information.
UART Messages: Parity
• In addition to data bits, UART communication may include a parity bit
as part of the data frame for error checking.
• Parity can be set to "odd" or "even," and it ensures that the total
number of "1" in a data is either even or odd.
• If the number of "1" bits doesn’t match the expected parity, an error
is detected.
UART Messages: Stop Bits
• One or more stop bits are sent after the data bits within each UART
frame to indicate the end of data.
• The most common configuration is to use 1 stop bit, but in situations
where added reliability is required, 2 stop bits can be employed.
Serial USB To send data from a computer to an Arduino (from
the Serial Monitor), we can make use of the
Examples Serial.available() and Serial.read() functions. First,
• This example will send the string we check if there's any data available, and if so, we
Hello World! from an Arduino to read it and print it.
a computer, using the int incomingByte = 0; // for incoming serial data
Serial.println() function. Data will void setup() {
be sent every one second. Serial.begin(9600)
void setup(){ }
void loop() {
Serial.begin(9600); // send data only when you receive (or have) data:
} if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
void loop(){
// say what you got:
Serial.println("Hello world!"); Serial.print("I received: ");
delay(1000); Serial.println(incomingByte, DEC);
} } }
RX/TX Pin Examples
• To set it up, connect the TX with RX pins on both boards.
UART in Arduino: Serial Class
• With the Serial class, you can send / receive data to and from your computer over USB, or to a
device connected via the Arduino's RX/TX pins.
• When sending data over USB, we use Serial. This data can be viewed in the Serial Monitor in
the Arduino IDE.
• When sending data over RX/TX pins, we use Serial1.
• The Serial class has several methods with some of the essentials being:
• begin() - begins serial communication, with a specified baud rate (many examples use either 9600 or
115200).
• print() - prints the content to the Serial Monitor.
• println() - prints the content to the Serial Monitor and adds a new line.
• available() - checks if serial data is available (if you send a command from the Serial Monitor).
• read() - reads data from the serial port.
• write() - writes data to the serial port.
• For example, to initialize serial communication on both serial ports, we would write it as:
• Serial.begin(9600); //init communication over USB (opens the serial port on USB and sets data rate)
• Serial1.begin(9600); //communication over RX/TX pins (opens the serial port on UART and sets data rate)
Transmit / Receive Messages example: Send
messages (strings) back and forth between
String devices.
sendMessage; if (Serial.available() > 0) {
String receivedMessage; char inputChar = Serial.read();
void setup() { if (inputChar == '\n') {
Serial.begin(9600); // Initialize the Serial monitor for debugging Serial1.println(sendMessage); // Send the message through
Serial1 with a newline character
Serial1.begin(9600); // Initialize Serial1 for sending data
sendMessage = ""; // Reset the message
}
} else {
void loop() {
sendMessage += inputChar; // Append characters to the
while (Serial1.available() > 0) { message
char receivedChar = Serial1.read(); }
if (receivedChar == '\n') { }
Serial.println(receivedMessage); // Print the received message in }
the Serial monitor
receivedMessage = ""; // Reset the received message
} else {
receivedMessage += receivedChar; // Append characters to the
received message
}
}
• We start by declaring two String variables for our incoming and outgoing
messages.
• String sendMessage;
• String receivedMessage;
• Inside setup() we initialize both Serial and Serial1 with a baud rate of 9600,
establishing a connection with the computer and the other transmitting
Arduino board.
• Serial.begin(9600); - opens the serial port on USB and sets data rate
• Serial1.begin(9600); - opens the serial port on UART and sets data rate
• Reading Messages: If a new byte is received, meaning Serial1.available() is
larger than 0 we check the received message.
while (Serial1.available() > 0) {
...
}
• Send Messages: For sending messages we first check if there are any
characters available in the Serial input buffer. In other words we check
if there is any text written inside the serial monitor, in which case
Serial.available() > 0.
if (Serial.available() > 0) {
...
}
Advantages of UART Protocol
• It has less physical interfacing based on only two lines.
• Simple to configure data and data size.
• Speed is also configurable. In most cases, this baud rate is 9600 for
the UART protocol.
• Full duplex mode configuration is possible by using two wires so that
is the major advantage of UART.
• Error detection is possible
Disadvantages of UART Protocol
• UART is having serial communication, therefore, it has less speed.
• Start bit, stop bit, and the parity bit is other overhead.
• Since this is asynchronous communication so here there are many
things that we need to do in configuration, for instance, we should
configure both devices at the same speed because the clock signal is
absent.

You might also like