Unit -3
1) Introduction to Arduino:
Arduino is an open-source electronics platform based on easy-to-use hardware and
software. It is widely used for building digital devices and interactive objects that can sense
and control the physical world.
The Arduino platform consists of two main parts:
Arduino Board (Hardware): A microcontroller-based development board that can read
inputs (like light, temperature, or button presses) and turn them into outputs (like turning
on an LED, running a motor, or sending data).
Arduino IDE (Software): A programming environment where users write code in C/C++ to
control the board.
Arduino is popular among students, hobbyists, and professionals due to its simplicity, cost-
effectiveness, and extensive community support.
Features of Arduino Board:(MDAPURCFROTSD)
Microcontroller:
Arduino boards are built around a microcontroller (e.g., ATmega328P in Arduino Uno),
which is the brain of the board, responsible for executing code.
Digital Input/Output Pins:
Most boards have 14 digital I/O pins, which can be used to read digital signals (like switches)
or output signals (like turning on an LED).
Analog Input Pins:
Typically includes 6 analog input pins to read analog sensors like temperature or light
sensors.
Power Supply Options:
Can be powered through USB, DC adapter, or battery (typically 7–12V). A built-in voltage
regulator provides consistent voltage levels.
USB Interface
:Used for programming the board and serial communication with a computer. USB also
powers the board when connected.
Reset Button:
Used to restart the program running on the board without disconnecting power.
Clock Speed:
Most Arduino boards operate at 16 MHz, ensuring smooth and reliable timing operations.
Flash Memory:
Used to store the program. For example, the Uno has 32 KB flash memory.
RAM and EEPROM:
Temporary and permanent memory for storing variables and data. E.g., Uno has 2 KB SRAM
and 1 KB EEPROM.
Open-source Hardware and Software:
Arduino is completely open-source, allowing users to modify and customize both hardware
and software as needed.
Wide Range of Models:
Different boards for different use-cases: Uno, Nano, Mega, Leonardo, Due, etc., each with
varying features and capabilities.
Shield Compatibility:
Supports add-on boards called "shields" (e.g., motor shields, Wi-Fi shields) to extend
functionality without soldering.
Community and Documentation:
Arduino has a large community, extensive tutorials, and detailed documentation, making
learning and troubleshooting easier.
2)Types of Arduino Boards:
Arduino offers a variety of boards, each designed for specific purposes. Below are the most
commonly used types of Arduino boards:
1. Arduino Uno
Most popular and beginner-friendly board.
Based on ATmega328P microcontroller.
Has 14 digital I/O pins, 6 analog inputs.
Ideal for basic electronics and prototyping.
2. Arduino Mega 2560
Designed for complex projects requiring more I/O.
Based on ATmega2560 microcontroller.
Has 54 digital I/O pins, 16 analog inputs.
Used in robotics, automation, and large sensor networks.
3. Arduino Nano
Compact and breadboard-friendly version of the Uno.
Based on ATmega328P.
Same functionality as Uno but smaller in size.
Suitable for space-constrained projects.
4. Arduino Leonardo
Uses ATmega32u4 microcontroller.
Can act as a USB device like a keyboard or mouse.
Useful for Human Interface Device (HID) projects.
5. Arduino Due
Based on 32-bit ARM Cortex-M3 processor (SAM3X8E).
Higher processing power and more memory.
Has 54 digital I/O pins, 12 analog inputs.
Suitable for advanced projects requiring speed and performance.
6. Arduino Micro
Small board similar to Leonardo.
Based on ATmega32u4.
Can emulate USB devices and fits easily into compact projects.
7. Arduino Nano Every
Improved version of the classic Nano.
Based on ATmega4809.
More memory and faster than the original Nano.
8. Arduino Pro Mini
Minimalist version of the Nano.
Requires an external USB-to-serial adapter to program.
Designed for permanent or embedded applications.
9. Arduino MKR Series (e.g., MKR1000, MKR Zero)
Designed for IoT (Internet of Things) applications.
Includes Wi-Fi, Bluetooth, or LoRa connectivity.
Uses SAMD21 Cortex-M0+ 32-bit microcontroller.
10. Arduino Portenta Series
High-performance boards for industrial and AI applications.
Includes dual-core ARM Cortex processors.
Supports real-time OS (RTOS) and advanced interfaces.
3)Introduction to Arduino Toolchain:
The Arduino toolchain is the set of software tools used to write, compile, upload, and
debug programs (called sketches) for Arduino boards. It provides a bridge between human-
readable code and the machine code that the microcontroller can execute.
🔧 Main Components of the Arduino Toolchain:
1. Arduino IDE (Integrated Development Environment):
User-friendly platform to write, edit, and upload Arduino programs.
Supports C/C++ programming with built-in functions for easier hardware control.
Key features: syntax highlighting, code autocompletion, serial monitor.
2. Arduino Sketch:
The name of an Arduino program file (extension: .ino).
Composed of two main functions:
o setup(): Runs once at startup.
o loop(): Repeats continuously after setup().
3. Preprocessor:
Processes the .ino sketch to convert it into a valid C++ source file.
Adds function prototypes and includes required libraries automatically.
4. AVR-GCC Compiler:
Compiles the C++ code into machine-level instructions for AVR microcontrollers.
Converts source code into hex files that can be uploaded to the board.
5. AVR Libc:
A C library specifically written for AVR microcontrollers.
Provides functions like delay(), millis(), and hardware access routines.
6. AVRDUDE (AVR Downloader/UploaDEr):
A command-line tool that uploads the compiled hex file to the Arduino board via
USB.
Communicates with the microcontroller bootloader.
7. Arduino Bootloader:
A small program pre-installed in most Arduino boards.
Allows code uploading via USB without the need for an external programmer.
Initializes the microcontroller to receive new programs from the IDE.
8. Serial Monitor and Plotter:
Tools to communicate with the board and display output from the microcontroller.
Used for debugging and data visualization.
🔄 Working Flow of the Arduino Toolchain:
1. Write Code in Arduino IDE (.ino file).
2. Preprocessing: IDE adds necessary includes and function declarations.
3. Compile using AVR-GCC → generates .hex file.
4. Upload the .hex file to the Arduino board using AVRDUDE.
5. Execute the program on the microcontroller.
6. Monitor and Debug using the Serial Monitor or Plotter.
4)Arduino Programming Structures
Arduino programming involves specific structures and syntax to communicate effectively
with the microcontroller. Two key concepts are sketches and pins, which form the
foundation of all Arduino programs.
🔹 1. Sketches in Arduino
A sketch is the name given to the program written for Arduino boards. It is written in
simplified C/C++ and saved with the .ino extension. Every sketch follows a standard
structure.
📌 Basic Structure of a Sketch:
// Global variable declarations
void setup() {
// Initialization code – runs once
void loop() {
// Main code – runs continuously
✨ Components:
Global Declarations:
o Variables/constants are declared before the setup() function.
setup():
o Executes once when the board starts or resets.
o Used to initialize inputs/outputs and communication protocols (e.g.,
pinMode(), Serial.begin()).
loop():
o Executes repeatedly in a loop.
o Contains the main logic of the program.
✅ Example Sketch:
jint led = 13;
void setup() {
pinMode(led, OUTPUT); // Set pin 13 as output
void loop() {
digitalWrite(led, HIGH); // LED ON
delay(1000); // Wait 1 sec
digitalWrite(led, LOW); // LED OFF
delay(1000); // Wait 1 sec
}
🔹 2. Pins in Arduino
Pins on an Arduino board are physical connectors used to interface with external
components like sensors, LEDs, motors, and more. There are two main types of pins: Digital
and Analog.
📌 Types of Pins:
Pin Type Function
Digital Pins Read/write HIGH or LOW (0 or 1) values
Analog Input Pins Read analog voltages (0–5V) using ADC
PWM Pins (~) Provide analog output using analogWrite()
Power Pins Provide voltage (3.3V, 5V, GND)
Special Pins TX/RX for communication, Reset, AREF
🔧 Common Functions Used with Pins:
Common Functions Used with Pins:
1. pinMode(pin,mode);
Sets a pin as INPUT, OUTPUT, or INPUT_PULLUP.
Example: pinMode(7, OUTPUT);
2. digitalWrite(pin,value);
Writes a digital value: HIGH (1) or LOW (0).
Example: digitalWrite(7, HIGH);
3. digitalRead(pin);
Reads a digital value: returns HIGH or LOW.
Example: int val = digitalRead(2);
4. analogRead(pin);
Reads an analog voltage and returns a value from 0 to 1023.
Example: int sensorValue = analogRead(A0);
5. analogWrite(pin,value);
Used with PWM pins to simulate analog output (0–255).
Example: analogWrite(9, 128);
🔸 Pin Layout – Example (Arduino Uno):
14 Digital I/O Pins (0–13)
6 Analog Input Pins (A0–A5)
PWM Pins: 3, 5, 6, 9, 10, 11
Power Pins: 5V, 3.3V, GND, VIN
Communication Pins: TX (1), RX (0)
5)Arduino Shields
🔹 What is an Arduino Shield?
An Arduino Shield is a modular, plug-and-play board that is designed to be mounted
directly on top of an Arduino board (like the Uno, Mega, etc.). Shields add extra
functionalities to Arduino without needing complex wiring or circuit design.
They save time and make it easier to expand Arduino's capabilities for specific applications
such as motor control, internet connectivity, GPS tracking, wireless communication, etc.
🔹 Features of Arduino Shields:
Designed to stack on Arduino boards.
Include headers to match Arduino pin layout.
Allow multiple shields to be stacked together (if compatible).
Plug-and-play and require minimal coding effort.
Often come with libraries and examples.
🔹 Common Types of Arduino Shields:
1. Motor Driver Shield
Controls DC motors, servo motors, and stepper motors.
Often based on L298N or TB6612FNG ICs.
Example: Used in robotics and automation projects.
2. Wi-Fi Shield
Adds Wi-Fi connectivity to Arduino.
Can connect to the internet or local networks.
Based on modules like ESP8266 or ESP32.
Example: IoT-based home automation.
3. Ethernet Shield
Enables Arduino to connect to a LAN using an Ethernet cable.
Based on the W5100 or ENC28J60 chip.
Example: Web server projects or remote monitoring.
4. Bluetooth Shield
Adds Bluetooth communication support.
Allows Arduino to communicate with smartphones or other devices.
Example: Wireless robot control using a phone app.
5. Relay Shield
Provides electrical isolation and allows Arduino to control high-voltage devices like
fans, bulbs, etc.
Useful for home automation.
6. GPS Shield
Adds Global Positioning System capability.
Based on GPS modules like NEO-6M.
Example: Location tracking systems, vehicle navigation.
7. GSM/GPRS Shield
Adds mobile communication features: call, SMS, and internet.
Based on modules like SIM800 or SIM900.
Example: Remote alert systems or SMS-based security systems.
8. Touchscreen LCD Shield
Adds a graphical touchscreen display to Arduino.
Can display text, buttons, and real-time data.
Example: User interfaces for embedded systems.
9. Data Logging Shield
Contains SD card module and RTC (Real Time Clock).
Used to store sensor data with timestamps.
Example: Weather stations, environmental monitoring.
10. Proto Shield
Blank board with a grid of solder pads.
Used for building and testing custom circuits.
🔹 Advantages of Using Shields:
Saves wiring and development time.
Easily stackable and reusable.
Reduces complexity in hardware design.
Offers reliable and tested expansion options.
6)Integration of Sensors and Actuators with Arduino
🔹 1. What is a Sensor?
A sensor is a device that detects or measures a physical property (such as temperature,
light, motion, distance, etc.) and converts it into an electrical signal that the Arduino can
process.
🔹 2. Components of a Sensor System:
Component Description
Sensing Element The part that detects the physical property.
Signal Conditioning Converts raw data into readable electrical signals.
Analog/Digital Interface Sends the processed signal to Arduino.
🔹 3. Types of Sensors:
Type Example Sensor Measured Quantity
Temperature LM35, DHT11 Heat/temperature
Motion PIR sensor Body movement
Distance Ultrasonic sensor Range/distance
Light LDR Light intensity
Gas MQ2, MQ135 Gas concentration
Proximity IR sensor Object presence/distance
🔹 4. What is an Actuator?
An actuator is a device that receives an electrical signal from Arduino and converts it into
physical movement or action (e.g., turning on a motor, buzzer, LED, etc.).
🔹 5. Types of Actuators:
Actuator Type Example Action Performed
LED Indicator light Turns ON/OFF (light signal)
DC Motor Motors Rotational motion
Servo Motor SG90 Precise angle control
Relay Relay module Switches high-power devices
Buzzer Piezo buzzer Sound alert
🔹 6. Difference Between Sensor and Actuator:
Feature Sensor Actuator
Function Detects input from environment Produces output action
Direction of Signal Environment → Arduino Arduino → Environment
Example IR sensor, Temperature sensor Motor, LED, Buzzer
Type of Device Input Device Output Device
🔹 7. Example 1: Controlling LED using IR Sensor and Remote
🧩 Components:
IR Receiver (like TSOP1738)
IR Remote
Arduino Uno
LED
🔧 Working:
1. IR remote sends coded signals.
2. IR sensor receives and decodes the signal.
3. Arduino reads the signal and turns LED ON/OFF accordingly.
8. Example 2: Reading a Switch
🧩 Components:
Push button
Arduino Uno
LED
🔧 Working:
1. When switch is pressed, Arduino reads HIGH.
2. LED turns ON or OFF.
UNIT -4
1) ✅ IoT Communication Protocols – Bluetooth and Wi-Fi (13
Marks)
🔷 Introduction to IoT Communication Protocols
IoT (Internet of Things) refers to a system where physical devices are connected to the
internet and can communicate, collect, and share data. The success of an IoT system
depends largely on the communication protocol it uses.
Bluetooth and Wi-Fi are two popular short-range wireless communication protocols that
allow smart devices to exchange data.
🔵 1. Bluetooth Communication Protocol
🔸 Definition:
Bluetooth is a low-power, short-range wireless communication protocol used for point-to-
point and point-to-multipoint communication.
It operates on the 2.4 GHz ISM band and was developed to replace RS-232 serial
communication cables.
Bluetooth is a wireless technology whereby two or three devices can communicate with
each other over a short distance usually 10-100 meters depending on the Bluetooth version.
It is mostly used for connecting smart devices like smartphones, headphones, keyboards,
and smartwatches among others. Bluetooth works at a frequency of 2. The chip supports a 4
GHz frequency band and is specially tailored for low-power devices which are usually run by
battery.
🔸 Bluetooth Versions:
Version Key Feature
Bluetooth Classic Suitable for data-heavy applications
Bluetooth LE (BLE) Lower power, designed for IoT, wearables, sensors
🔸 Architecture / Network Topology:
Piconet: One master and up to 7 slaves.
Piconet is a type of Bluetooth network that contains one primary node called the
master node and seven active secondary nodes called slave nodes. Thus, we can say
that there is a total of 8 active nodes which are present at a distance of 10 meters.
The communication between the primary and secondary nodes can be one-to-one or
one-to-many. Possible communication is only between the master and slave; Slave-
slave communication is not possible. It also has 255 parked nodes, these are
secondary nodes and cannot take participation in communication unless it gets
converted to the active state.
Scatternet: Multiple interconnected piconets.
It is formed by using various piconets. A slave that is present in one piconet can act
as master or we can say primary in another piconet. This kind of node can receive a
message from a master in one piconet and deliver the message to its slave in the
other piconet where it is acting as a master. This type of node is referred to as a
bridge node. A station cannot be mastered in two piconets.
🔸 Technical Specifications:
Feature Description
Frequency 2.4 GHz ISM band
Range 10 – 100 meters (based on device class)
Data Rate Up to 3 Mbps (Classic), 2 Mbps (BLE)
Power Consumption Very low (suitable for battery-powered devices)
Security 128-bit encryption, pairing modes
Types of Bluetooth
Various types of Bluetooth are available in the market nowadays. Let us look at them.
In-Car Headset: One can make calls from the car speaker system without the use of
mobile phones.
Stereo Headset: To listen to music in car or in music players at home.
Webcam: One can link the camera with the help of Bluetooth with their laptop or
phone.
Bluetooth-Equipped Printer: The printer can be used when connected via Bluetooth
with mobile phone or laptop.
Bluetooth Global Positioning System (GPS): To use Global Positioning System
(GPS) in cars, one can connect their phone with car system via Bluetooth to fetch the
directions of the address.
🔸 Advantages of Bluetooth in IoT:
Low power usage (especially BLE)
Simple pairing
Cost-effective
Supported on nearly all smartphones
Disadvantages of Bluetooth
Limited range, usually up to 100 meters depending on the version.
Slower data transfer speeds compared to Wi-Fi (up to 50 Mbps in Bluetooth 5.0).
Prone to interference from other devices using the 2.4 GHz frequency.
Limited number of devices can be connected at once.
Lower security measures, making it more vulnerable to attacks.
🔸 Common Applications:
Wearable devices (fitness bands, smartwatches)
Wireless headsets
Home automation (e.g., Bluetooth-controlled bulbs)
Arduino + HC-05/HC-06 communication
🔶 2. Wi-Fi Communication Protocol
🔸 Definition:
Wi-Fi (Wireless Fidelity) is a high-speed wireless communication protocol that allows
devices to connect to the internet or local area networks using radio frequency signals,
mainly at 2.4 GHz and 5 GHz.
Wi-Fi is a wireless networking technique that gives larger coverage area up to one hundred
meters indoors and even more, outdoors for integrating a high prompt internet association.
It enables or links devices to the internet or to a Local Area Network (LAN) through
utilization of radio waves. Wi-Fi works in two major frequency bands, 2. 4 GHz and 5 GHz,
and is popularly known as a home or business wireless network and through which several
devices can connect to the same internet.
Types of Wi-Fi Connections
LAN (Local Area Network)
A LAN operates within a limited area like an office building or home, connecting various
devices such as computers, printers, and storage devices. It uses components like switches,
routers, and cables, with Wi-Fi being the most common wireless form of LAN. Think of it as a
network that serves a single location.
PAN (Personal Area Network)
A PAN is the smallest network type, centered around one person's devices in a specific
location, typically connecting personal gadgets like phones, computers, and gaming
consoles. Bluetooth is the most well-known wireless PAN technology. These networks are
perfect for personal use in homes or small offices.
MAN (Metropolitan Area Network)
A MAN covers a larger geographical area than a LAN, typically spanning across a city, college
campus, or business complex. It's designed to connect multiple locations within a
metropolitan area, making it ideal for organizations that need to manage systems across
several buildings or facilities.
WAN (Wide Area Network)
A WAN is the largest network type, covering vast geographical areas like cities, countries, or
even the entire globe - the Internet being the most famous example. It can encompass
multiple smaller networks like LAN and MAN, and cellular networks are the most common
type of wireless WAN.
How does a Wi-Fi work?
Wi-Fi is a wireless technology for networking, so it uses Electromagnetic waves to transmit
networks. We know that there are many divisions of Electromagnetic waves according to
their frequency such as X-ray, Gamma-ray, radio wave, microwave, etc, in Wi-Fi, the radio
frequency is used. For transmitting Wi-Fi signal there is three medium,
Base Station Network or an Ethernet(802.3) Connection: It is the main host network
from where the network connection is provided to the router.
Access Point or Router: it is a bridge between a wired network and a wireless
network. It accepts a wired Ethernet connection and converts the wired connection
to a wireless connection and spreads the connection as a radio wave.
Accessing Devices: It is our mobile, computer, etc from where we use the Wi-Fi and
surfing internet.
🔸 IEEE Standards:
Standard Max Speed Frequency
802.11b 11 Mbps 2.4 GHz
802.11g 54 Mbps 2.4 GHz
802.11n 600 Mbps 2.4/5 GHz
802.11ac >1 Gbps 5 GHz
🔸 Technical Specifications:
Feature Description
Frequency Band 2.4 GHz and 5 GHz
Range Indoors: ~50m, Outdoors: ~100m
Data Rate Up to 1 Gbps (depending on standard)
Power Consumption Higher than Bluetooth
Security WPA2, WPA3, WEP encryption
Topology Star network using a router or access point
🔸 Advantages of Wi-Fi in IoT:
Fast data transfer
Widely available infrastructure (routers)
Supports cloud and internet connectivity
Simultaneous multi-device communication
Disadvantages of Wi-Fi
Higher power consumption, not ideal for small battery-powered devices.
More complex setup, requires routers and network configuration.
More expensive infrastructure with routers and access points.
Prone to signal degradation over long distances or physical barriers.
Potentially more susceptible to hacking if not properly secured.
🔸 Common Applications:
Smart home devices (CCTV, thermostat, lights)
IoT dashboards (real-time data on browser/cloud)
Arduino + ESP8266 or ESP32 modules
Industrial automation and smart agriculture
🆚 Comparison Table: Bluetooth vs Wi-Fi
Feature Bluetooth Wi-Fi
Range 10–100 meters Up to 100 meters
Data Rate Up to 3 Mbps Up to 1 Gbps
Power Usage Low (especially BLE) High
Cost Low-cost modules like HC-05 Slightly higher (ESP8266, ESP32)
Topology Point-to-point or piconet Star with router/access point
Local device-to-device
Ideal Use Case Cloud access, internet-based apps
communication
Feature Bluetooth Wi-Fi
Smart cameras, weather stations, IoT
Examples Smart bands, toys, Bluetooth locks
hubs
Bluetooth Wifi
Bluetooth has no full form. While wifi stands for Wireless Fidelity.
Whereas it requires a wireless adapteron
It requires a Bluetooth adapter on all
all devices and a wireless router for
devices for connectivity.
connectivity.
Bluetooth consumes low power. While it consumes high power.
The security of Bluetooth is less in While it provides better security than
comparison to wifi. Bluetooth.
Bluetooth is less flexible means in this Whereas wifi supports a large amount of
limited users are supported. users.
The radio signal range of Bluetooth is ten Whereas in wifi this range is hundred
meters. meters.
Bluetooth requires low bandwidth. While it requires high bandwidth.
Bluetooth frequency range 2.400 GHz to
WiFi frequency range 2.4GHz to 5 GHz.
2.483 GHz
Bluetooth Wifi
Bluetooth demands a Bluetooth setting or WiFi demands a wireless router to set up
adapter on all devices to set up the connectivity and adapter on the
connectivity. device.
In WiFi modulation technique
In Bluetooth modulation technique is is OFDM(Orthogonal Frequency Division
GFSK(Gaussian frequency shift keying). Multiplexing) and QAM(Quadrature
Amplitude Modulation).
Bit-rate in Bluetooth is 2.1 Mbps. Bit-rate in WiFi is 600 Mbps.
Applications
1. Consumer
Applications
2. Games
1. Wifi analyzer
3. Industry
2. wifi inspector
4. sport training
It's under IEEE 802.15.1 It's under IEEE 802.11 Standard
Real-Time Arduino Use Cases
✅ Bluetooth Example (HC-05 with Arduino):
Control LED with smartphone via Bluetooth.
✅ Wi-Fi Example (ESP8266 with Arduino):
Read sensor data and upload to web or IoT cloud platforms like ThingSpeak.
✅ Conclusion
Both Bluetooth and Wi-Fi are vital for IoT communication, and each has specific advantages:
Bluetooth is best for low power, short-range communication between local devices.
Wi-Fi is ideal for high-speed data transmission and internet/cloud-connected
systems.
Choosing the right protocol depends on the project’s range, power, speed, and cost
requirements.
2) 🔶 ZigBee – A Low-Power Wireless Communication Protocol
✅ Introduction to ZigBee
ZigBee is a low-power, low-data-rate wireless communication protocol based on the IEEE
802.15.4 standard. It's specifically designed for IoT, home automation, industrial control,
and wireless sensor networks.
🔹 6.3.1 ZigBee Architecture
ZigBee architecture is divided into several layers:
🔸 1. Application Layer
Topmost layer
Hosts the application objects and defines user interfaces
Includes Application Support Sublayer (APS)
🔸 2. Network Layer
Handles network formation, routing, and addressing
Responsible for device joining/leaving
🔸 3. MAC Layer (Medium Access Control)
Manages channel access
Uses CSMA/CA (Carrier Sense Multiple Access with Collision Avoidance)
🔸 4. PHY Layer (Physical Layer)
Defines hardware (antenna, transceiver)
Operates at 2.4 GHz, 868 MHz, and 915 MHz frequencies
🔹 6.3.2 Logical Device Types
ZigBee supports three types of devices:
Device Type Description
Coordinator Initializes and manages the network. Only one per ZigBee network.
Forwards data and extends network range. Can communicate with other
Router
routers and end devices.
Limited functionality (e.g., sensors). Communicates only with its parent node.
End Device
Energy-efficient.
🔹 6.3.3 Network Layer
The network layer is crucial in ZigBee and handles:
Network discovery and formation
Address assignment (each device gets a 16-bit short address)
Routing (chooses best path for data packets)
Security (supports encryption)
Supports different topologies:
Star
Tree
Mesh
🔹 6.3.4 Simple Tree Routing Protocol
Used in tree topology networks.
Each router has a parent-child relationship.
Devices send data up the tree to the root (coordinator).
Efficient for static networks with predictable routes.
Advantages:
Simple implementation
Low memory requirement
Limitations:
Not very fault-tolerant (single link failure can cause issues)
🔹 6.3.5 ZigBee-AODV (ZAODV)
ZAODV stands for ZigBee-Ad hoc On-Demand Distance Vector routing protocol.
A dynamic routing protocol used in mesh networks.
Routes are established on-demand when data needs to be sent.
Supports self-healing in case of route failure.
Reduces unnecessary broadcast traffic.
Steps:
1. Route Request (RREQ) is sent.
2. Intermediate nodes forward the request.
3. Route Reply (RREP) is sent back with the best path.
4. Route is stored in a routing table.
🔹 6.3.6 APS Layer (Application Support Sublayer)
Part of the Application Layer.
Acts as a bridge between the application and network layer.
Responsibilities:
o Binding: Associates devices (e.g., switch to light)
o Message formatting and addressing
o Security management
o Manages endpoint addresses and clusters
🔹 6.3.7 ZigBee Applications
ZigBee is widely used in:
🔸 Home Automation:
Smart lights, fans, doors
Energy meters
🔸 Industrial Automation:
Machine monitoring
Process control
🔸 Healthcare:
Patient monitoring systems
🔸 Smart Agriculture:
Soil moisture sensors
Automated irrigation
🔸 Environmental Monitoring:
Air quality sensors
Weather stations
✅ Conclusion
ZigBee is ideal for low-power, low-bandwidth, short-range applications. Its mesh
networking, low co📡 Global Positioning System (GPS)
3) 🔶GPS
✅ 1.Introduction
GPS is a satellite-based navigation system that enables a receiver to determine its exact
location (latitude, longitude, altitude) anywhere on Earth, in all weather conditions, 24/7,
without any subscription fee or setup charges.
✅ 2. History and Development
Developed by the U.S. Department of Defense (DoD) in the 1970s.
Originally for military use; made available for civilian use in the 1980s.
The system is also referred to as NAVSTAR GPS.
✅ 3. Components of GPS
GPS consists of three major segments:
🔸 a. Space Segment
24+ satellites orbiting Earth at ~20,200 km altitude.
Each satellite completes two orbits per day.
They continuously transmit signals containing the satellite’s position and time.
🔸 b. Control Segment
Ground stations that monitor, manage, and update satellite positions and clocks.
Main control station: Colorado Springs, USA.
🔸 c. User Segment
Devices like smartphones, car navigation systems, and GPS modules (e.g., Neo-6M).
Receive satellite signals and compute position.
✅ 4. How GPS Works
1. GPS satellites broadcast radio signals with:
o Satellite position (ephemeris data)
o Exact time (from atomic clock)
2. GPS receiver gets signals from at least 4 satellites.
3. Using trilateration, it calculates:
o Distance from each satellite
o Position in 3D space (latitude, longitude, altitude)
4. Correction factors account for atmospheric delays, clock errors, etc.
✅ 5. GPS Accuracy
Factor Affecting Accuracy Description
Satellite geometry Better accuracy when satellites are widely spaced
Signal blockage Buildings, trees, tunnels can block signals
Atmospheric interference Delays due to ionosphere and troposphere
Quality of GPS receiver High-end receivers = better accuracy
Accuracy ranges from 5–10 meters (standard) to <1 meter (with DGPS/RTK GPS).
✅ 6. Applications of GPS
📍 Personal Use:
Google Maps navigation
Fitness trackers, running/cycling apps
🚗 Automotive:
Vehicle tracking
Anti-theft systems
Aviation & Marine:
Aircraft navigation
Ship tracking and positioning
🚜 Agriculture:
Precision farming
Automated tractors
📦 Logistics:
Fleet management
Real-time delivery tracking
👮 Emergency:
Disaster response
Ambulance and firetruck navigation
✅ 7. GPS Module with Arduino (e.g., NEO-6M)
🔸 Common GPS Module: Ublox NEO-6M
Communicates via UART (TX/RX)
Baud rate: 9600 bps
Outputs NMEA sentences like $GPGGA, $GPRMC (location, speed, time)
🔸 Uses with Arduino:
Vehicle tracking system
Geo-fencing applications
Location-based automation
8. Advantages of GPS
Global coverage
High reliability
No subscription cost
Passive (no need to transmit data)
✅ 9. Limitations of GPS
Needs clear sky view
Indoor positioning not effective
Errors from atmospheric conditions or multi-path reflections
✅ 10. Alternatives to GPS
GLONASS (Russia)
Galileo (EU)
BeiDou (China)
IRNSS/NavIC (India)
✅ Conclusion
GPS has revolutionized navigation and location-based services across all industries. With its
integration into Arduino and IoT systems, GPS modules enable real-time tracking,
automation, and enhanced safety features for smart solutions.
4)GSM Modules
✅ Introduction to GSM
GSM (Global System for Mobile Communication) is a digital mobile communication
standard developed to describe protocols for second-generation (2G) digital cellular
networks. It is widely used for voice and data transmission over mobile networks.
In embedded systems, GSM modules (e.g., SIM800, SIM900) are used to enable devices to
communicate over cellular networks via SMS, voice, and GPRS (data).
🔹 6.5.1 Base Station Subsystem (BSS)n
The BSS handles the radio communication between mobile devices and the network.
🔸 a. Base Transceiver Station (BTS)
Contains antenna and transceivers.
Facilitates wireless communication with mobile stations (phones, GSM modules).
Each BTS covers one cell in the cellular network.
🔸 b. Base Station Controller (BSC)
Controls multiple BTSs.
Manages handover, frequency assignment, and power control.
Acts as a bridge between BTS and the core network.
🔹 6.5.2 Network Switching Subsystem (NSS)
The NSS is the core part of the GSM system that handles call setup, routing, and mobility
management.
Components:
Component Function
Mobile Switching Center Core controller for voice call switching. Manages call setup,
(MSC) routing, and teardown.
Home Location Register Database storing permanent user information (SIM details,
(HLR) services).
Visitor Location Register
Temporary data of users currently in the area.
(VLR)
Authentication Center
Provides security and encryption keys for user authentication.
(AUC)
Equipment Identity Register
Stores IMEI numbers of devices. Used to block stolen phones.
(EIR)
🔹 6.5.3 Mobile Station (MS)
The Mobile Station refers to the user’s device or embedded module.
Components:
Component Description
Mobile Equipment
The device (e.g., mobile phone or GSM module) used by the user.
(ME)
Subscriber Identity Module; stores IMSI, phone number, and
SIM Card
encryption keys.
A hardware module used in embedded systems (e.g., SIM800L) to
GSM Module
send/receive SMS and data.
6.5.4 GSM Channels
GSM uses multiple logical and physical channels over radio frequencies.
🔸 a. Traffic Channels (TCH)
Carry voice or user data.
Full-rate or half-rate channels.
🔸 b. Control Channels (CCH)
Used for network management, not for user data. Types include:
Channel Purpose
Broadcast Control Channel (BCCH) Broadcasts cell-specific information.
Common Control Channel (CCCH) Used for call setup and paging.
Dedicated Control Channel (DCCH) Manages call/session-specific control information.
GSM Frequency Bands:
900 MHz and 1800 MHz (common in Asia/Europe)
850 MHz and 1900 MHz (North America)
✅ Applications of GSM Modules
SMS-based device control (home automation)
Vehicle tracking systems
Weather and health monitoring
Smart farming and irrigation
Security alerts via SMS/Call
✅ Advantages
Wide network availability
Voice and SMS support
Easy integration with microcontrollers
✅ Limitations
Limited data rate (compared to 4G/5G)
Requires SIM card and cellular signal
Latency in remote areas
✅ Conclusion
GSM modules are a crucial component in IoT and communication-based embedded systems.
Understanding the architecture—from BSS to NSS, Mobile Station, and GSM channels—
enables efficient use in real-time applications such as tracking, automation, and remote
control.
5)Raspberry Pi Architecture – Open Platform
The Raspberry Pi is a low-cost, credit-card-sized computer developed by the Raspberry Pi
Foundation. It is widely used for IoT, robotics, automation, and education due to its
affordability and flexibility. It functions as a full-fledged computer, running a Linux-based OS
and supporting peripherals such as a monitor, keyboard, and mouse.
🔹 6.6.1 About the Board
The Raspberry Pi board includes several hardware components integrated into a single
compact board:
📦 Key Components:
Component Description
CPU (SoC) ARM-based Broadcom processor (e.g., BCM2837 in Pi 3).
RAM Varies by model (512MB to 8GB in Pi 4).
GPU VideoCore IV for video and 3D graphics processing.
General Purpose Input/Output pins for connecting sensors, motors, LEDs,
GPIO Pins
etc.
Component Description
USB Ports Connect peripherals like mouse, keyboard, camera.
HDMI Port For video output to display.
SD Card Slot Stores OS and data (acts as the main boot drive).
Ethernet/Wi-Fi Networking support.
Audio Jack For sound output.
CSI and DSI Camera Serial Interface (CSI) and Display Serial Interface (DSI) ports for
Ports camera and display.
🔹 6.6.2 Linux on Raspberry Pi
The Raspberry Pi runs Linux-based operating systems, the most popular being Raspberry Pi
OS (formerly Raspbian).
🐧 Features of Linux on Raspberry Pi:
Lightweight OS tailored for ARM processors.
Includes a GUI (LXDE desktop environment).
Command-line interface via Terminal.
Full programming support: Python, C, C++, Java, Node.js.
Tools like Thonny IDE, VS Code, and GPIO libraries.
Internet, multimedia, file system, and remote SSH access.
🔧 Example Linux Commands:
sudo apt update # Update package list
sudo apt install python3 # Install Python
gpio readall # View GPIO pin status (after installing wiringPi)
🔹 6.6.3 Difference Between Raspberry Pi and Desktop Computers
Feature Raspberry Pi Desktop Computer
Size Small (credit card size) Large and bulky
Feature Raspberry Pi Desktop Computer
Cost Low (Rs. 4000–10,000) High (Rs. 30,000+)
Processor ARM-based SoC x86 or x64 CPUs
OS Linux-based (Raspberry Pi OS) Windows/macOS/Linux
Power Uses micro USB or USB-C Uses SMPS
Learning, IoT, embedded, General computing, gaming, professional
Purpose
automation use
Expandability GPIO pins for hardware projects Limited physical I/O expansion
Boot Device MicroSD card HDD/SSD
✅ Additional Advantages of Raspberry Pi
Low power consumption.
Supports Python, IoT, AI, and cloud integration.
Ideal for DIY projects: home automation, surveillance, weather stations, etc.
Community support and thousands of open-source projects.
✅ Applications of Raspberry Pi
Smart home automation
Weather monitoring
IoT gateways
Robotics
Media centers (Kodi)
Educational coding kits
AI/ML projects with TensorFlow Lite
✅ Conclusion
Raspberry Pi, being a powerful and open-source development platform, bridges the gap
between embedded systems and general computing. Its support for Linux and GPIO makes
it perfect for developers, students, and hobbyists to explore real-world IoT and
programming applications.
6)Raspberry Pi Interfacing
Interfacing refers to the connection and communication between the Raspberry Pi and
external devices such as sensors, actuators, displays, and other peripherals. Raspberry Pi is
equipped with GPIO (General Purpose Input/Output) pins and various interfaces that make
this integration possible.
🔹 1. GPIO Pins Overview
The Raspberry Pi comes with a 40-pin GPIO header (in models like Pi 3, 4), which allows
hardware-level communication.
🔸 GPIO Categories:
Digital Input/Output Pins
PWM (Pulse Width Modulation) Pins
I2C (Inter-Integrated Circuit)
SPI (Serial Peripheral Interface)
UART (Universal Asynchronous Receiver-Transmitter)
2. Interfacing Devices with Raspberry Pi
a. LED Interfacing
b. Button / Switch Interfacing
c.Sensor Interfacing
IR Sensor
Used for obstacle detection, motion sensing, etc.
OUT pin → GPIO
VCC, GND to power
d. Actuator Interfacing
🔹 Servo Motor
3. Communication Protocol Interfacing
Protocol Devices Interface Pins
I2C LCDs, sensors (e.g., BMP180) SDA, SCL
SPI ADC chips, TFT displays MISO, MOSI, SCLK, CE
UART GPS modules, GSM modules TX, RX
🔹 4. Display Interfacing
7-Segment Display
16x2 LCD Display (via I2C)
OLED/TFT Displays
5. Camera and Display Ports
CSI (Camera Serial Interface): For connecting official Raspberry Pi Camera.
DSI (Display Serial Interface): For official Raspberry Pi touchscreen displays.
🔹 6. Other Interfaces
USB: Keyboard, mouse, pen drives.
HDMI: Connects to monitors/TV.
Audio jack: Speaker or headphones.
Wi-Fi & Bluetooth: For wireless interfacing (e.g., mobile app communication, IoT
cloud).
🔹 7. Applications of Raspberry Pi Interfacing
Home automation (control lights/fans)
Smart surveillance with cameras and sensors
IoT cloud-based temperature logging
Voice assistant with mic and speaker
DIY weather stations
Robotic car control using sensors
7)Raspberry Pi Programming
Programming the Raspberry Pi is usually done using Python, a simple and powerful language
that has built-in support for GPIO control via libraries like RPi.GPIO and gpiozero.
✅ 1. Controlling an LED with Raspberry Pi
🔸 Circuit Connection:
Connect LED anode to GPIO pin (e.g., GPIO 17).
Connect cathode to a resistor (220Ω) to GND.
Eg
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
while True:
GPIO.output(17, GPIO.HIGH) # LED ON
time.sleep(1)
GPIO.output(17, GPIO.LOW) # LED OFF
time.sleep(1)
2. Interfacing an LED and Switch with Raspberry Pi
🔸 Circuit Connection:
LED: Connect to GPIO 18 (through resistor).
Push Button (Switch): One terminal to GPIO 23, another to GND.
Enable pull-up resistor in code.
EG
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT) # LED
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button
while True:
if GPIO.input(23) == GPIO.LOW:
GPIO.output(18, GPIO.HIGH) # LED ON
else:
GPIO.output(18, GPIO.LOW) # LED OFF
3. Interfacing a Light Sensor (LDR) with Raspberry Pi
Since the Raspberry Pi doesn't have analog input, we use an LDR + capacitor to
form an RC timing circuit to measure light.
🔸 Components:
LDR (Light Dependent Resistor)
10µF capacitor
Connect LDR between 3.3V and GPIO pin (e.g., 18)
Connect capacitor between GPIO and GND
🔸 Concept:
The charging time of the capacitor depends on light. In bright light, resistance is
low and charges fast; in darkness, it charges slowly.
Eg
import RPi.GPIO as GPIO, time
GPIO.setmode(GPIO.BCM)
def rc(pin):
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, 0)
time.sleep(0.1)
GPIO.setup(pin, GPIO.IN)
c=0
while not GPIO.input(pin): c += 1
return c
try:
while True:
print("Light:", rc(18))
time.sleep(1)
except:
GPIO.cleanup()
8)Connecting to the Cloud in IoT
In an IoT ecosystem, devices like sensors, actuators, Raspberry Pi, or Arduino need to
communicate and store data in the cloud to enable:
Remote monitoring
Real-time control
Analytics
Decision-making
Two commonly used cloud solutions are:
🌐 1. WAMP: Autobahn for IoT
🔸 What is WAMP?
WAMP stands for Web Application Messaging Protocol. It enables real-time, full-duplex
communication between devices and cloud services using WebSockets.
WAMP supports two types of messaging:
Publish/Subscribe (Pub/Sub) for event-based updates
Remote Procedure Calls (RPC) for command and control
🔸 Autobahn
Autobahn is an open-source WAMP client library that helps IoT devices communicate with
the cloud using WAMP protocol.
Autobahn-Python – for devices like Raspberry Pi
Autobahn-JS – for web interfaces
🔸 Architecture
Component Function
Device Client Runs Autobahn to publish or receive data
Router WAMP router (like Crossbar.io) routes messages
Subscriber Receives data from the topic
Publisher Sends sensor data to a cloud topic
🔸 Use Case Example
A temperature sensor sends data to a topic like com.home.temp.
A web dashboard subscribes to that topic to display live temperature readings.
🔸 Benefits
Real-time communication
Bidirectional control (e.g., controlling devices from the cloud)
Scalable architecture
Lightweight protocol over WebSockets
☁️2. Xively Cloud for IoT
🔸 What is Xively?
Xively (formerly Pachube, now merged into Google's IoT Core) was a Platform-as-a-Service
(PaaS) designed specifically for IoT cloud integration. It provided tools for:
Device management
Data storage and visualization
Cloud connectivity
Integration with business logic and APIs
Note: Xively has been acquired and integrated into Google Cloud IoT as of 2018, but its
model is still widely studied in IoT curriculums.
🔸 Features of Xively
Feature Description
Device Management Registers and controls thousands of devices
Secure Connectivity TLS/SSL for device-to-cloud communication
Real-Time Monitoring Dashboards for viewing live sensor data
Data APIs REST APIs for accessing device data
Web/Mobile Integration Integrate with Android/iOS/Web apps
🔸 Architecture of Xively IoT Cloud
1. Device Gateway: Connects devices via MQTT/HTTP
2. Xively Cloud Platform: Stores and processes data
3. Business Logic Layer: Processes rules, triggers
4. User Interface: Displays device data, alerts, and control
🔸 Sample Flow (Temperature Sensor):
1. A device reads temperature.
2. It sends the reading via MQTT or HTTP to Xively.
3. Xively stores the data and can trigger alerts if thresholds are exceeded.
4. A mobile app fetches data using Xively REST APIs.
🔸 Advantages of Xively
End-to-end cloud solution
RESTful API integration
Real-time monitoring dashboards
Device provisioning and access control
Ideal for commercial IoT applications
🔸 Comparison: WAMP vs Xively
Feature WAMP (Autobahn) Xively IoT Cloud
Protocol Type Messaging Protocol Full Cloud Platform
Communication Pub/Sub and RPC over HTTP/MQTT based REST
Style WebSocket communication
Medium (needs Crossbar
Setup Complexity Low (via web interface)
Router)
Commercial IoT deployment &
Ideal Use Case Real-time messaging & control
monitoring
Visualization Custom via web apps Built-in dashboard support
UNIT -4
1)RTOS – Real-Time Operating System (13 Marks)
1. Definition:
An RTOS (Real-Time Operating System) is a specialized operating system designed to
process data and execute tasks within a strict time constraint. It ensures that critical
operations are performed in a predictable and timely manner.
2. Key Characteristics:
Feature Description
Determinism Predictable behavior; responses occur within a defined time limit.
Multi-tasking Manages multiple tasks using scheduling algorithms.
Low Latency Quick response time to external events or interrupts.
Feature Description
Preemptive Scheduling Allows higher priority tasks to interrupt lower-priority ones.
Reliability and Stability Designed for long-term usage in embedded systems.
3. Types of RTOS:
1. Hard RTOS:
o Strict deadlines
o Missing a deadline = system failure.
o Example: Airbag system in a car.
2. Soft RTOS:
o Deadlines are important but not critical.
o Occasional delays acceptable.
o Example: Audio/video streaming.
3. Firm RTOS:
o Occasional missed deadlines tolerated, but may degrade performance.
o Example: Robotics and automation.
4. Components of RTOS:
Task/Thread: Basic unit of execution.
Scheduler: Determines the order of task execution.
Interrupt Service Routines (ISR): Handles external hardware events.
Time Management: Manages delays, timeouts, and periodic tasks.
Inter-task Communication (IPC): Semaphores, Message Queues, Mutexes for
synchronization.
Memory Management: Allocation and deallocation of memory safely and efficiently.
5. Scheduling in RTOS:
Preemptive Scheduling: Runs the highest priority task first.
Round Robin: Tasks are executed in a circular order with equal time slices.
Rate Monotonic Scheduling (RMS): Prioritizes tasks with shorter periods.
Earliest Deadline First (EDF): Dynamic priority based on deadline.
6. Advantages of RTOS:
Predictable timing behavior
Faster response to external events
Efficient multitasking
Better resource management
Suitable for embedded systems
7. Applications of RTOS:
Automotive (ABS, airbags)
Aerospace (flight control systems)
Medical devices (pacemakers, monitoring)
Industrial automation (robots, PLCs)
Consumer electronics (smartphones, cameras)
8. Examples of RTOS:
FreeRTOS
VxWorks
RTLinux
QNX
µC/OS
2)I/O Devices Interfacing Overview
I/O (Input/Output) interfacing refers to the method by which microcontrollers or
microprocessors communicate with external input/output devices like keyboards, LEDs,
displays, etc. These devices can't communicate directly with the processor and require
special circuits and code to interact.
🔡 4.2.1 Keyboard Interfacing
Keyboards are input devices. To interface them with a microcontroller:
4.2.1.1 Key Debounce using Hardware
When a key is pressed, it may bounce and generate multiple electrical signals.
Hardware debounce uses components like resistors and capacitors or flip-flops to
filter out the bounce.
This provides a clean, single pulse per key press.
4.2.1.2 Key Debouncing using Software
Uses code to ignore bounce effects.
Common method: wait a few milliseconds after detecting a key press, then recheck.
if (key_pressed) {
delay(20);
if (key_pressed_again) // confirm the press
4.2.1.3 Simple Keyboard Interface
Uses a few keys connected to individual input pins.
Each key press is detected using digital read logic.
Simple for small applications (like 4-key input).
4.2.1.4 Matrix Keyboard Interface
Common for larger keypads (e.g., 4x4 matrix = 16 keys).
Keys are arranged in rows and columns to reduce the number of pins.
Scanning method:
o Set rows as outputs and columns as inputs (or vice versa).
o Activate one row at a time and check for a pressed key in the column.
o Detect the exact key by matching row and column.
💡 4.2.2 LED Interfacing
LEDs are output devices, used for indications.
Connected with a current-limiting resistor to a GPIO pin.
To turn ON: write a HIGH or LOW (based on circuit).
Can be used to blink, indicate status, or output binary data.
🔢 4.2.3 Multiplexed 7-Segment Display Interfacing
7-Segment Displays show numbers (0–9) using 7 LEDs.
Multiplexing:
o Used to control multiple digits using fewer GPIO pins.
o Common cathode or anode types.
o One digit is activated at a time in fast succession → appears like all are lit
(persistence of vision).
4.2.3.1 Interfacing LED Displays
Segment lines (a-g) shared across digits.
Digit enable pins are activated one by one.
Requires timing control (e.g., via timer interrupts or delay loop).
Used for clocks, counters, digital meters.
📺 4.2.4 LCD Interfacing
LCDs (like 16x2 or 20x4) display characters or messages.
Requires data pins (usually 4 or 8-bit mode) + control lines (RS, RW, EN).
4-bit mode saves pins.
Steps:
o Initialize LCD
o Send commands (clear screen, set cursor)
o Send data (characters)
Useful for UI display in embedded systems.
3)🔄 Multiple Tasks and Processes
In embedded or real-time systems, multiple operations (tasks) often need to run
simultaneously or in a coordinated fashion. These tasks can be processes (independent
programs) or threads (lightweight tasks within a process).
🔁 4.5.1 Multirate Systems
Definition: Systems where different tasks run at different rates or time intervals.
Example:
o Temperature sensor task: every 1 second.
o Motor control task: every 10 ms.
o Display update: every 100 ms.
Use Case: Common in real-time control systems like automotive ECUs, industrial
automation.
Benefits:
o Efficient CPU usage.
o Real-time responsiveness.
o Prioritization of faster tasks.
🧠 4.5.2 Process State and Scheduling
🔹 Process States:
A process (or task) typically goes through these states:
State Description
New Process is being created.
Ready Waiting to be assigned to CPU.
Running Currently executing.
Waiting (Blocked) Waiting for some event (I/O, signal).
Terminated Finished execution.
🔹 Scheduling:
Determines which task gets CPU time and when.
Ensures smooth execution of tasks in multitasking environments.
Helps meet deadlines in real-time systems.
📋 4.5.3 Scheduling Policies
These are strategies used to manage task execution:
1. First-Come-First-Serve (FCFS)
Tasks executed in order of arrival.
Simple but can lead to long wait times.
2. Round Robin (RR)
Each task gets a fixed time slot (time quantum).
After that, it goes back to the ready queue.
Fair for all tasks.
3. Priority Scheduling
Tasks have priorities.
High-priority tasks are scheduled first.
Risk: low-priority tasks may starve (never execute).
4. Rate Monotonic Scheduling (RMS) – Real-Time
Tasks with shorter periods (run more frequently) have higher priority.
Widely used in periodic real-time systems.
5. Earliest Deadline First (EDF) – Real-Time
Task with the closest deadline is executed first.
Dynamic, deadline-driven scheduling.
Context Switching — Explained Simply
4)✅ What is Context Switching?
Context Switching is the process of saving the state of a currently running task (process or
thread) and loading the state of another task so that it can run.
It allows a single CPU to handle multiple tasks by switching between them rapidly, giving
the illusion of parallelism.
🧠 Why is Context Switching Needed?
In multitasking or real-time systems, multiple tasks compete for CPU.
Only one task can run on a CPU at a time.
When the system switches from one task to another (due to time completion or a
higher-priority task needing execution), the CPU must save the context (registers,
program counter, stack pointer, etc.) of the current task and load the context of the
new one.
🔁 Steps in Context Switching
1. Save the current task’s context (CPU state: registers, stack pointer, program
counter).
2. Update the process control block (PCB) of the current task.
3. Select a new task using the scheduler.
4. Load the context of the new task from its PCB.
5. Resume execution of the new task.
📦 What is Stored in "Context"?
Program Counter (PC) – Where the program left off.
Stack Pointer (SP) – Points to current stack frame.
CPU Registers – General-purpose and special registers.
Process state – Ready, waiting, running, etc.
🔧 Example Analogy
Imagine you're writing a note (Task A), but then you have to suddenly answer a phone call
(Task B):
You bookmark your place in the notebook and save the pen (saving context of Task
A).
You take out your phone and start talking (loading context of Task B).
When done, you return to your notebook and continue from the bookmark (restore
Task A).
Context Switching Overhead
It takes time to switch contexts.
Too frequent switching can lead to CPU time wasted just in switching (called context
switch overhead).
Real-time OSs aim to minimize this overhead.
5)✅ DIFFERENCE BETWEEN C AND EMBEDDED C
S.No C Language Embedded C
1. General-purpose programming language. Extension of C for embedded system programming.
S.No C Language Embedded C
2. Used for desktop and OS-level applications. Used for microcontroller-based applications.
3. Hardware-independent. Hardware-dependent.
Uses hardware-specific libraries (reg51.h,
4. Uses standard libraries (stdio.h, stdlib.h).
avr/io.h).
Input/output through screen and keyboard using
5. I/O done through ports, registers, and pins.
printf, scanf.
6. Runs with operating system support. Mostly runs on bare-metal (no OS).
7. High memory and processing power available. Limited memory and processing capability.
Direct access and control over hardware like LEDs,
8. No direct interaction with hardware.
motors, etc.
9. Does not support real-time operation. Designed for real-time embedded applications.
Interrupt Service Routines (ISR) are used for
10. Interrupts not directly used.
handling interrupts.
11. Portable across platforms. Less portable, tied to specific hardware.
Compiled using standard compilers (e.g., GCC, Turbo Compiled using embedded compilers (e.g., Keil,
12.
C). MPLAB).
Output is .hex or .bin file for burning into a
13. Output is .exe or desktop application.
microcontroller.
6)Priority-Based Scheduling Policies
Priority-based scheduling is a real-time scheduling technique where tasks are assigned
priorities, and the CPU is always allocated to the task with the highest priority among all
ready tasks. It is used widely in real-time operating systems (RTOS) to meet deadlines.
Two major types of priority-based scheduling are:
4.7.1 Earliest Deadline First (EDF) Scheduling
Definition: EDF is a dynamic priority scheduling algorithm, where the task with the
earliest deadline is given the highest priority.
Working:
o Priorities change dynamically depending on how close each task is to its
deadline.
o When a new task arrives, if its deadline is sooner than the currently executing
task, a context switch may occur.
Advantages:
o Utilization can reach 100% under ideal conditions.
o Flexible for systems with variable task periods.
Disadvantages:
o Overhead due to frequent context switches.
o Complex to implement compared to static methods.
4.7.2 Rate Monotonic Scheduling (RMS)
Definition: RMS is a static priority scheduling algorithm used for periodic tasks.
Tasks with shorter periods are assigned higher priorities.
Working:
o Priorities are fixed at design time based on task frequency.
o Suited for hard real-time systems with periodic tasks.
Advantages:
o Simple and predictable.
o Easy to implement in embedded systems.
Disadvantages:
o CPU utilization is limited to 69.3% (for large number of tasks).
o Cannot handle aperiodic or sporadic tasks well.
4.7.2.1 Comparison between RMS and EDF
Feature RMS (Rate Monotonic Scheduling) EDF (Earliest Deadline First)
Type of Priority Static Dynamic
Priority Assignment Based on task period Based on task deadline
CPU Utilization ≤ 69.3% (n→∞) Can go up to 100%
Feature RMS (Rate Monotonic Scheduling) EDF (Earliest Deadline First)
Complexity Simple More complex
Overhead Low Higher due to frequent switching
Best For Periodic hard real-time tasks Both periodic & aperiodic tasks
4.7.3 Priority Inversion
Definition: A situation where a lower-priority task holds a resource needed by a
higher-priority task, but cannot release it because it is preempted by a medium-
priority task.
Example:
o Low-priority task L locks a resource.
o High-priority task H waits for that resource.
o Medium-priority task M preempts L, delaying H.
Solution:
o Priority Inheritance Protocol: Temporarily boost the priority of L to match H
until the resource is released.
7)Memory Scheduling
Memory scheduling involves managing how the CPU reads from and writes to memory
components efficiently. In microcontroller systems (like 8051), it includes scheduling access
to:
Program memory (for instructions),
Data memory (for variables), and
External memory interfaces.
1.1 Interfacing and Timing Diagrams for Memory Interfacing
8051 has a 16-bit address bus allowing it to access up to 64 KB of both external program
memory and external data memory. Memory interfacing requires careful timing to match
the speed of memory components with the processor.
1.1.1 External Program Memory
Used to store program code externally, typically in EPROM.
The signal /PSEN (Program Store Enable) is used by 8051 to read data from external
program memory.
📌 Timing Diagram Key Points:
8051 places the address on Port 0 (lower byte - multiplexed) and Port 2 (higher
byte).
ALE (Address Latch Enable) is used to latch the lower address byte.
/PSEN goes low to enable the external ROM, and data is read.
1.1.2 External Data Memory
Used to store data variables externally (e.g., in RAM).
8051 uses /RD and /WR signals to read and write data.
Port 0 and Port 2 are used for addressing (same as above).
📌 Timing Diagram Key Points:
ALE latches address using a latch like 74LS373.
/RD is activated for reading; /WR is activated for writing.
1.1.3 Important Points in Accessing External Memory
ALE is crucial to separate address and data signals on Port 0.
External memory must be fast enough to keep up with 8051.
Use latch (74LS373) to hold lower byte address.
Code and data memory have separate control signals: /PSEN for program, /RD
and /WR for data.
1.2 Memory Address Decoding
Decoding is required to select a specific memory chip when multiple memory chips
are connected.
Address decoders (like 74LS138) are used to activate specific memory chips based
on address range.
📌Example:
If you connect:
ROM at 0000H–3FFFH
RAM at 4000H–7FFFH
You need a decoder to generate chip select signals based on the upper address lines (like
A15–A14).
1.3 Interfacing Examples
Example 1: 4 KB EPROM interfacing
Address Range: 0000H–0FFFH
Use /PSEN to enable read
Use latch with ALE to separate address/data
Example 2: 2 KB RAM interfacing
Address Range: 2000H–27FFH
Use /RD and /WR for read/write operations
Chip select generated using A15–A11 decoding logic
1.4 Accessing External Data Memory in 8051C
In 8051C (a variant of the 8051), external data memory is accessed using special
instructions:
🧠 Instructions:
MOVX A, @DPTR → Read data from external memory
MOVX @DPTR, A → Write data to external memory
MOVX A, @Ri or MOVX @Ri, A → Read/write using indirect addressing
💡 Key Notes:
DPTR (Data Pointer Register) holds 16-bit address.
MOVX is used for external memory access.
Port 0 and Port 2 handle the 16-bit address bus and data bus.
UNIT 1
1) features of 8051 microcontroller
1. 8-bit Processor
The 8051 is an 8-bit microcontroller, meaning it processes 8 bits of data at a time.
All arithmetic and logic operations are done on 8-bit data.
✅ 2. Clock Speed
It typically runs at 12 MHz, but it can go up to 33 MHz in modern versions.
Each instruction takes 1 to 2 machine cycles.
✅ 3. On-chip ROM (Program Memory)
Standard 8051 has 4 KB ROM.
Used to store the program code permanently.
✅ 4. On-chip RAM (Data Memory)
8051 has 128 bytes of internal RAM.
This includes general-purpose RAM, bit-addressable RAM, and register banks.
✅ 5. 32 Input/Output (I/O) Lines
8051 has 4 I/O ports (Port 0 to Port 3), each of 8 bits.
These are used to connect external devices like LEDs, sensors, motors, etc.
✅ 6. Two 16-bit Timers/Counters
Timer 0 and Timer 1.
Used for timing operations, delays, counting external events, etc.
✅ 7. Full Duplex Serial Port
Supports serial communication using UART (Universal Asynchronous Receiver
Transmitter).
Used for RS232 communication, debugging, connecting with other microcontrollers
or PCs.
✅ 8. Interrupt Handling
8051 supports 5 interrupts:
o External Interrupt 0 (INT0)
o Timer 0 Overflow
o External Interrupt 1 (INT1)
o Timer 1 Overflow
o Serial Communication
✅ 9. Bit and Byte Addressable Memory
Special feature of 8051: certain memory areas (RAM and SFRs) can be accessed bit-
by-bit.
Useful for controlling individual pins or flags.
✅ 10. On-chip Oscillator and Clock Circuit
Built-in oscillator circuit.
Just connect a crystal oscillator externally to generate system clock.
✅ 11. Power-saving Modes
Idle Mode: CPU stops, but peripherals work.
Power-down Mode: Entire chip sleeps to save power.
✅ 12. Harvard Architecture
Separate memory spaces for program memory (ROM) and data memory (RAM).
Increases speed and efficiency.
✅ 13. Expandability
Can interface with external RAM and ROM.
Address bus: 16-bit → can access up to 64 KB external memory.
2) 🔷 Architecture of 8051 Microcontroller
The 8051 microcontroller is based on Harvard Architecture, meaning it has separate
memory for program and data. It consists of various components that work together for
embedded system applications.
🔹 1.3.1 Central Processing Unit (CPU)
The CPU is the brain of the microcontroller.
It controls the operation of the microcontroller by fetching, decoding, and executing
instructions.
It communicates with memory, ALU (Arithmetic Logic Unit), and registers.
🔹 1.3.2 A and B CPU Registers
These are general-purpose registers used for temporary storage during operations.
Register A (Accumulator):
o Most important register.
o Used in arithmetic, logic, and data transfer operations.
Register B:
o Used during multiplication and division operations.
o Also acts as a temporary storage register.
🔹 1.3.3 Data Pointer (DPTR)
It is a 16-bit register used to access external memory.
Split into:
o DPH (Data Pointer High byte)
o DPL (Data Pointer Low byte)
Mainly used in MOVX (Move External) and code memory access.
🔹 1.3.4 The Program Counter (PC)
The PC is a 16-bit register that holds the address of the next instruction to be
executed.
Automatically incremented after each instruction fetch.
Crucial for program flow and branching (like jumps or calls).
🔹 1.3.5 8051 Flag Bits and PSW (Program Status Word) Register
PSW is an 8-bit register that contains important flag bits:
o CY – Carry flag
o AC – Auxiliary Carry
o F0 – User-defined flag
o RS1, RS0 – Register bank select bits
o OV – Overflow flag
o P – Parity bit
These flags are set or cleared during operations and used for decision-making (e.g.,
conditional instructions).
🔹 1.3.6 Special Function Registers (SFRs) of 8051
These are memory-mapped control registers located in the upper 128 bytes of
internal RAM (80H to FFH).
Each SFR has a specific function (like timers, serial port, I/O ports).
Examples:
o P0, P1, P2, P3 – Port registers
o TCON, TMOD – Timer control
o IE, IP – Interrupt control
o SCON, SBUF – Serial control and data buffer
📊 Summary Table:
Component Description
CPU Executes instructions and controls microcontroller operations
A & B Registers Temporary data storage for ALU operations
DPTR Accesses external memory
Component Description
Program Counter (PC) Points to next instruction to execute
PSW & Flags Indicates status of operations (carry, overflow, etc.)
SFRs Controls peripherals and internal features
3)🔷 8051 Addressing Modes
Addressing modes define how an instruction accesses data stored in memory or registers.
The 8051 microcontroller supports several addressing modes that improve flexibility and
performance in programming.
🔹 2.1.1 Register Addressing
Operands are located in the registers R0 to R7 of the currently selected register
bank.
Fast and efficient.
✅ Example:
MOV A, R2 → Move content of register R2 to accumulator A.
🔹 2.1.2 Direct Byte Addressing
Accesses data directly using a specific memory address.
Can refer to internal RAM locations or SFRs.
✅ Example:
MOV A, 30H → Move data from RAM location 30H to accumulator A.
🔹 2.1.3 Register Indirect Addressing
Uses registers R0 or R1 as pointers to indirectly access memory.
Allows dynamic memory access.
✅ Example:
MOV A, @R0 → Move data from the memory location pointed to by R0 into A.
🔹 2.1.4 Immediate Addressing
The operand (data) is given immediately in the instruction itself.
Used for constant values.
✅ Example:
MOV A, #25H → Move the value 25H directly into accumulator A.
🔹 2.1.5 Register Specific
Refers to instructions that work with specific registers, like the Accumulator (A) or B
register.
These registers have special roles in arithmetic and logic operations.
✅ Example:
ADD A, B → Add the content of register B to accumulator A.
🔹 2.1.6 Index Addressing
Used to access program memory (code) using DPTR or PC with an offset (like
accumulator A).
Commonly used with MOVC (Move Code).
✅ Example:
MOVC A, @A+DPTR → Add A and DPTR, then move data from that code memory
address to A.
🔹 2.1.7 Stack Addressing Mode
Involves pushing and popping data to/from the stack, which uses the SP (Stack
Pointer).
Stack is accessed indirectly.
✅ Example:
PUSH 0x20 → Push content at address 20H to the stack.
📌 Summary Table
Addressing Mode Description Example
Register Addressing Uses R0–R7 registers MOV A, R1
Direct Addressing Uses direct memory address MOV A, 40H
Addressing Mode Description Example
Register Indirect Accesses memory via R0/R1 MOV A, @R0
Immediate Addressing Loads constant value MOV A, #50H
Register Specific Uses A or B register directly ADD A, B
Index Addressing Accesses code memory using offset MOVC A, @A+DPTR
Stack Addressing Uses stack pointer (SP) for push/pop operations PUSH 20H, POP 20H
Byte-Level Logical Instructions in 8051
Byte-level logical instructions in the 8051 microcontroller operate on entire bytes (8 bits) of
data, typically between registers, memory, or immediate values. These instructions perform
bitwise logical operations like AND, OR, XOR, and NOT (complement).
4)✅ Common Byte-Level Logical Instructions
Instruction Description Example Effect
ANL A, Rn AND Accumulator with register ANL A, R2 A = A & R2
ANL A, direct AND Accumulator with direct address ANL A, 30H A = A & [30H]
ANL A, #data AND Accumulator with immediate value ANL A, #0F0H A = A & 0F0H
ORL A, Rn OR Accumulator with register ORL A, R1 A = A | R1
ORL A, direct OR Accumulator with direct address ORL A, 20H A = A | [20H]
ORL A, #data OR Accumulator with immediate value ORL A, #55H A = A | 55H
XRL A, Rn XOR Accumulator with register XRL A, R0 A = A ^ R0
XRL A, direct XOR Accumulator with direct address XRL A, 40H A = A ^ [40H]
XRL A, #data XOR Accumulator with immediate value XRL A, #0FFH A = A ^ FFH
CPL A Complement (invert) Accumulator CPL A A = ~A
CLR A Clear Accumulator CLR A A = 00H
SWAP A Swap nibbles in Accumulator SWAP A A[7:4] <-> A[3:0]
Instruction Description Example Effect
5)Arithmetic Instructions in 8051 Microcontroller
The 8051 supports a range of arithmetic operations used for mathematical processing.
These operations include addition, subtraction, increment, decrement, multiplication,
division, and decimal adjustments.
✅ 2.5.1 Incrementing and Decrementing
Used to increase or decrease a value by 1.
Instruction Description Example Effect
INC A Increment accumulator INC A A=A+1
INC Rn Increment register R0–R7 INC R2 R2 = R2 + 1
DEC A Decrement accumulator DEC A A=A-1
[40H] = [40H]
DEC direct Decrement direct address DEC 40H
-1
✅ 2.5.2 Addition
Used to add two operands and optionally include the carry.
Instruction Description Example Effect
A = A +
ADD A, Rn Add register to A ADD A, R3
R3
Add immediate value A = A +
ADD A, #data ADD A, #10H
to A 10H
A = A +
ADDC A, Rn Add with carry ADDC A, R1
R1 + CY
⚠️Carry flag (CY) is affected by addition.
✅ 2.5.3 Subtraction
Used to subtract a value from the accumulator. Since 8051 doesn’t have a simple SUB
instruction, it uses SUBB (Subtract with Borrow).
Instruction Description Example Effect
SUBB A, Rn Subtract register and borrow SUBB A, R4 A = A - R4 - CY
Subtract immediate and
SUBB A, #data SUBB A, #12H A = A - 12H - CY
borrow
✅ 2.5.4 Multiplication and Division
Only specific registers are used: A and B.
Instruction Description Example Effect
MUL AB Multiply A × B MUL AB Result → A (low byte), B (high byte)
DIV AB Divide A ÷ B DIV AB Quotient → A, Remainder → B
⚠️Overflow flag (OV) is affected by multiplication.
✅ 2.5.5 Decimal Arithmetic
Used for BCD (Binary-Coded Decimal) operations.
Instruction Description Example Effect
Decimal adjust A after BCD Adjusts A to valid BCD if A was the result
DA A DA A
addition of BCD addition
6)🔷 Jump and CALL Instructions in 8051 Microcontroller
Jump and CALL instructions in the 8051 control the flow of execution in a program. These
allow the program to branch to another location, either permanently (jump) or temporarily
(call and return).
✅ 2.8.1 Jump and Call Program Range
In 8051, jump and call instructions are classified by the range (how far they can branch):
Type Range Description
-128 to +127
Short jump Jumps within the same 2 KB code page.
bytes
Jump to address in the same 2KB block of program
Absolute jump Entire 2 KB block
memory.
Long jump Full 64 KB range Unconditional jump to any location in program memory.
LCALL Full 64 KB Used for subroutines located anywhere in memory.
✅ 2.8.2 Jump Instructions
These instructions are used to transfer control to another part of the program based on
conditions or unconditionally.
➤ Types of Jump Instructions:
Instruction Description Example
SJMP addr Short jump (relative) SJMP BACK
AJMP addr Absolute jump AJMP LABEL1
LJMP addr Long jump LJMP 2000H
JC addr Jump if Carry = 1 JC CARRY_ON
JNC addr Jump if Carry = 0 JNC NO_CARRY
Instruction Description Example
JZ addr Jump if A = 0 JZ DONE
JNZ addr Jump if A ≠ 0 JNZ LOOP
DJNZ Rn, addr Decrement and Jump if Not Zero DJNZ R2, LOOP
✅ 2.8.3 CALL and Subroutines
CALL instructions are used to invoke a subroutine (block of code), and the control is
returned after execution.
➤ Types of CALL Instructions:
Instruction Description Example
ACALL addr Absolute call (within 2KB) ACALL SUB1
LCALL addr Long call (anywhere in memory) LCALL INIT
RET Return from subroutine RET
RETI Return from interrupt RETI
🧠 Working:
On a CALL instruction, PC (Program Counter) is pushed to the stack.
After executing the subroutine, RET is used to pop PC and return to the main
program.
7) 8051 Timers Overview
The 8051 microcontroller has two timers/counters:
Timer 0
Timer 1
They can function as either:
Timers (to count internal clock pulses)
Counters (to count external events)
Each timer is 16-bit, divided into:
TH0/TL0 – High and Low bytes of Timer 0
TH1/TL1 – High and Low bytes of Timer 1
🔹 1.1 Structure of TMOD Register (Timer Mode Register)
The TMOD register is 8-bit, divided into two 4-bit fields:
Lower 4 bits → Timer 0
Upper 4 bits → Timer 1
mathematica
CopyEdit
| GATE | C/T | M1 | M0 | GATE | C/T | M1 | M0 |
| T1 Control | T0 Control |
Bit Functions:
Bit Name Description
7, 3 GATE 1 = Timer runs only when INTx is high and TRx = 1
6, 2 C/T 0 = Timer mode (counts internal clock)
Bit Name Description
1 = Counter mode (counts pulses)
5, 1 M1 Mode select bit 1
4, 0 M0 Mode select bit 0
Modes (M1 M0):
M1 M0 Mode Description
0 0 0 13-bit Timer
0 1 1 16-bit Timer
1 0 2 8-bit Auto-reload
1 1 3 Split Timer mode (Timer 0 only)
🔸 1.2 Structure of TCON Register (Timer Control Register)
The TCON register is 8-bit, used to control the timers and external interrupts.
CopyEdit
| TF1 | TR1 | TF0 | TR0 | IE1 | IT1 | IE0 | IT0 |
Bit Functions:
Bit Name Description
7 TF1 Timer 1 Overflow Flag (set when Timer 1 overflows)
6 TR1 Timer 1 Run Control bit (1 = start Timer 1)
5 TF0 Timer 0 Overflow Flag (set when Timer 0 overflows)
4 TR0 Timer 0 Run Control bit (1 = start Timer 0)
3 IE1 External Interrupt 1 Edge Flag
2 IT1 Interrupt 1 Type (1 = edge triggered, 0 = level)
Bit Name Description
1 IE0 External Interrupt 0 Edge Flag
0 IT0 Interrupt 0 Type (1 = edge triggered, 0 = level)
8) 8051 Counter Programming
Counters in 8051 are used to count external events (like pulses). The same Timer modules
(Timer 0 and Timer 1) are used for Timer or Counter mode, differentiated by a bit setting.
🔸 Difference Between Timer and Counter Mode:
Mode Source Use
Time
Timer Internal clock (machine cycle)
delays
Event
Counter External pulses (T0 or T1 pins)
counting
🔸 Selecting Counter Mode:
Use TMOD (Timer Mode) Register
o C/T bit (bit 2 or 6) = 1 ➝ Counter mode
o Example: TMOD = 0x05; ➝ Timer 0 in Mode 1 Counter
=🔹 1.1 Programming Timers in 8051 C (using KEIL C)
🔸 🔹 1.1 Programming Timers in 8051 C (using KEIL C)
🔸 Step-by-step Approach:
✅ 1. Include Header File
✅ 2. Configure TMOD Register
✅ 3. Set Initial Count
✅ 4. Start Timer/Counter
✅ 5. Monitor Overflow Flag
✅ 6. Stop Timer/Counter and Reset Flag
Example 1: Timer Mode (Delay Generator)
CopyEdit
#include <reg51.h>
void delay() {
TMOD = 0x01; // Timer0 Mode1
TH0 = 0xFC; // Load High byte
TL0 = 0x66; // Load Low byte for ~1ms delay
TR0 = 1; // Start Timer0
while (TF0 == 0); // Wait for overflow
TR0 = 0; // Stop Timer
TF0 = 0; // Clear overflow flag
void main() {
while (1) {
P1 = 0xFF; // Turn ON all LEDs
delay();
P1 = 0x00; // Turn OFF all LEDs
delay();