0% found this document useful (0 votes)
57 views181 pages

Microcontrollers and Applications - Unit 1 and 2 Notes

The document provides an overview of microcontrollers and their applications, focusing on their role in embedded systems. It covers essential topics such as programming, interfacing, and communication protocols, aiming to equip students with the knowledge needed for careers in IoT and automation. The course is designed to foster innovation and adaptability in technology-driven fields.

Uploaded by

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

Microcontrollers and Applications - Unit 1 and 2 Notes

The document provides an overview of microcontrollers and their applications, focusing on their role in embedded systems. It covers essential topics such as programming, interfacing, and communication protocols, aiming to equip students with the knowledge needed for careers in IoT and automation. The course is designed to foster innovation and adaptability in technology-driven fields.

Uploaded by

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

MICROCONTROLLERS

AND APPLICATIONS
Hrishikesh Kamat
COEP Technical University

The brain behind every smart device


SYLLABUS OVERVIEW

Introduction to Microcontrollers
Programming with Microcontrollers
8 Bit Microcontroller
I/O Interfacing
Communication Protocols
External Peripheral Interfacing
Practicals
INTRODUCTION

About Me
Hrishikesh Kamat, CEO, Shalaka Connected Devices LLP and
IoTAdda
10+ years entreprenerial experience in designing embedded
systems and IoT solutions for industries.
Chess player, Motorcyclist, Traveller, Photographer.

Objectives
To equip students with foundational knowledge of
microcontrollers and their programming, enabling them to design
and implement embedded systems for real-world applications.
This course prepares students for careers in cutting-edge fields
like IoT, automotive systems, and industrial automation, fostering
innovation and adaptability to future technological
advancements.

Empower students to build innovative embedded systems


Embedded systems are specialized computer
EMBEDDED SYSTEMS systems designed to perform dedicated
functions within larger systems.

They integrate hardware and software to


deliver specific, real-time operations.

Key Characteristics

Task-Specific: Designed to perform one or a few


specific tasks.
Real-Time Operations: Executes tasks within
strict time constraints.
Resource-Constrained: Limited memory,
processing power, and energy consumption.
Hardware-Software Integration: Combines
microcontrollers, sensors, and software to
function.
Embedded systems are specialized computer
EMBEDDED SYSTEMS systems designed to perform dedicated
functions within larger systems.
They integrate hardware and software to
deliver specific, real-time operations.
Examples
Consumer Electronics: Washing machines,
microwaves, smart TVs.
Automotive: Engine control units (ECUs), ABS
systems, airbag controllers.
Medical Devices: Pacemakers, infusion pumps,
diagnostic equipment.
Industrial Automation: PLCs, robotics, energy
monitoring systems.
Why Learn Embedded Systems?
The foundation of modern technology, from IoT to
robotics.
Essential for careers in industries like automotive,
healthcare, and automation.
Growing demand for skilled engineers to develop
and maintain such systems.
ELEMENTS OF EMBEDDED SYSTEMS

Environment Actuators Microcontroller Sensors Environment


Communication Communication

Hardware Software Communication Sensors & User Interface (UI)


Interfaces Actuators
Microcontroller/Processor: Firmware: Instructions Sensors: Measure physical
Protocols like SPI, I2C,
The brain of the system. running the system. parameters (e.g., Displays: LCDs,
UART.
Memory: RAM for RTOS: Optional for temperature). touchscreens.
Network connectivity: Wi-Fi,
temporary data, ROM/Flash multitasking in real-time Actuators: Perform actions Inputs: Buttons, keypads, or
Bluetooth, Zigbee.
for programs. systems. (e.g., motors, LEDs). touch sensors.
I/O Interfaces: Connects Drivers: Interface software
peripherals like sensors and for hardware control.
actuators.
Power Supply: Provides
stable energy.
Unit 1:
INTRODUCTION TO
MICROCONTROLLERS
1.
NUMBERING
SYSTEM
What is a numbering System ?

A method of representing numbers using symbols in a structured


way.
Common systems:
Binary (Base 2): 0, 1.
Decimal (Base 10): 0–9.
Octal (Base 8): 0–7.
Hexadecimal (Base 16): 0–9, A–F.
Why Numbering Systems Matter?

1. Microcontrollers Operate in Binary Format


Microcontrollers communicate and execute instructions in binary, as they are electronic devices
that process on/off signals (0s and 1s).
Every instruction or data point is represented in binary format at the hardware level, making it
essential to understand binary operations.
2. Memory Addresses and Machine Instructions are Often Hexadecimal
Hexadecimal simplifies the representation of binary numbers.
A single hexadecimal digit corresponds to 4 binary digits, making it more concise and human-
readable.
Example: Instead of writing 110110101111, it is represented as 0xD6F.
Memory addresses, instructions, and debugging tools in microcontroller environments use
hexadecimal notation.
Why Numbering Systems Matter?

3. Essential for Programming and Debugging


Understanding numbering systems is critical when:
Writing low-level programs in Assembly or Embedded-C.
Reading and interpreting memory maps, registers, and debugging output.
Analyzing machine code or firmware logs during error analysis.
4. Foundation for Hardware Interfacing
When working with hardware peripherals, such as LEDs, sensors, or communication modules, binary
and hexadecimal numbers often represent configurations or data.
Example: Configuring an I/O pin as input or output is often done by writing binary values to a register.
5. Real-World Relevance
Common tools like oscilloscopes, debuggers, and protocol analyzers display values in binary or
hexadecimal.
Engineers use these formats daily for tasks like testing circuits, analyzing waveforms, or programming
microcontrollers.
Common Numbering Systems

1. Binary (Base 2)
Definition: A numbering system that uses only two symbols: 0 and 1.
Each digit represents a power of 2.
Example:

Applications:
Logic Circuits: Binary logic (AND, OR, NOT gates) forms the basis of all digital electronics.
Microcontroller Instructions: All machine instructions and memory representations are binary.
Example: Setting an I/O pin high or low corresponds to writing 1 or 0.
Data Representation: Bits in binary represent status flags, control signals, or on/off states in embedded
systems.
Why Microcontrollers only understand Binary?

Microcontrollers are built using digital circuits made of transistors.


A transistor acts as a switch that can either be ON (representing 1) or OFF
(representing 0).
These two states form the basis of binary logic.
ON = High Voltage (1).
OFF = Low Voltage (0).
Common Numbering Systems

2. Decimal (Base 10)


Definition: A numbering system using ten symbols: 0 through 9.
Each digit represents a power of 10.
Example:

Applications:
Human-Readable Format: Decimal is commonly used to represent system values like sensor readings
(e.g., temperature, speed).
Example: A temperature sensor output in Celsius or Fahrenheit.
User Interaction: Values displayed on screens or inputted via keypads often use decimal numbers for
clarity.
Importance of Decimal System

Why the Decimal System is Important


Human-Readable Format: Simplifies data representation for users (e.g., sensor outputs like 25°C or 120
km/h).
User Interaction: Keypads and displays use decimal for intuitive input and output.
Example: Entering cooking time on a microwave or viewing the temperature on a thermostat.
Applications
Real-World Data Representation: Converts binary sensor data into decimal units for clarity.
Example: An ADC value of 204 representing 2.04V.
Debugging & Monitoring: Engineers use decimal for easy system verification and analysis.
Mathematical Calculations: Handles real-world values in applications like cost computation in vending
machines.
Common Numbering Systems

3. Octal (Base 8)
Definition: A numbering system using eight symbols: 0 through 7.
Each digit represents a power of 8.
Example:

Applications:
Memory Addressing in Older Systems: Used in early computer systems for compact memory
addressing.
Microcontroller Debugging: Some older microcontroller registers and error codes are represented in
octal format.
Compact Binary Representation: Each octal digit represents three binary digits, making it easier to work
with binary data in some contexts.
Importance of Octal System

Why is Octal Used?


Compact Binary Representation: Each octal digit represents 3 binary digits, simplifying binary data
interpretation.
Historical Relevance: Commonly used in early computer systems for memory addressing and error codes.

Memory Addressing:
Simplifies addressing in older microcontrollers and systems.
Compact and easier to understand compared to long binary strings.
Debugging & Error Codes:
Some older microcontroller registers and error outputs use octal for simplicity.
Efficient Data Representation:
Bridges binary and human-readable formats effectively in specific contexts.
Example
Binary: 110110 → Octal: 66
Makes debugging and memory analysis faster and more efficient.
Common Numbering Systems

4. Hexadecimal (Base 16)


Definition: A numbering system using sixteen symbols: 0 through 9 and A through F.
Each digit represents a power of 16.
Example:
Importance of Hexadecimal System

Applications:

Memory Addressing: Used for concise representation of memory addresses.

Example: Address 0xFF12 in hexadecimal instead of 1111111100010010 in binary.

Machine Code Representation: Hexadecimal simplifies writing and reading opcodes in assembly language.

Example: A MOV instruction might be represented as 0x89AB.

Color Codes in Displays: Commonly used to define colors in HTML/CSS and graphical interfaces.

Example: #FF5733 represents an RGB color.

.BIN: Direct and efficient programming when no memory mapping or error checking is needed.

.HEX: Preferred for programming tools that manage memory placement and require error detection.
Hexadecimal System

Decimal Hexadecimal Decimal Hexadecimal Decimal Hexadecimal

0 0x0 11 0xB 21 0x15

1 0x1 12 0xC 22 0x16

2 0x2 13 0xD 23 0x17

3 0x3 14 0xE 24 0x18

4 0x4 15 0xF 25 0x19

5 0x5 16 0x10 26 0x1A

6 0x6 17 0x11 27 0x1B

7 0x7 18 0x12 28 0x1C

8 0x8 19 0x13 29 0x1D

9 0x9 20 0x14 30 0x1E

10 0xA 31 0x1F

32 0x20
Decimal to Binary

Steps:
Divide the decimal number by 2.
Record the remainder (either 0 or 1).
Repeat the division process with the quotient until the quotient is 0.
Write the remainders in reverse order to get the binary equivalent.
Example: Convert 13 to Binary
13÷2=Q 6 R 1
6÷2= Q 3 R 0
3÷2= Q 1 R 1
1÷2= Q 0 R 1
Binary: 13=1101(Base2)
Decimal to Binary
Binary to Decimal

Steps:
Write the binary number.
Multiply each digit by 2s position, where the position starts from 0
(rightmost digit).
Add the results to get the decimal number.
Example: Convert 1011 to Decimal
Binary to Hexadecimal
Decimal to Hexadecimal

First Convert into Binary, then Binary to Hexadecimal by Grouping 4 bits


Decimal to Hexadecimal

629 (Base10) to Hexadecimal

1714 (Base10) to Hexadecimal


Addition Rules
Basic Rules:
1. 0 + 0 = 0
No carry is generated.
Example: Adding 0 and 0 results in 0.
2. 0 + 1 = 1
No carry is generated.
Example: Adding 0 and 1 results in 1.
3. 1 + 0 = 1
No carry is generated.
Example: Adding 1 and 0 results in 1.
4. 1 + 1 = 10
Sum is 0 and a carry of 1 is generated.
Example: Adding 1 and 1 results in 10 (binary for 2).
5. 1 + 1 + 1 = 11
Sum is 1 and a carry of 1 is generated.
2's Complement

Inverting the bits is simply a matter of changing al Os to Is and 1s to Os. This is called
the l's complement.

To get the 2's complement of a binary number, invert al the bits and then add I to the
result.
Subtraction Rules

There is no subtraction circuit in a microcontroller

Steps to Perform Subtraction Using 2's Complement


1. Write Both Numbers in Binary
Ensure both numbers have the same number of bits by adding leading zeros if necessary.
2. Find the 2's Complement of the Subtrahend
The subtrahend is the number being subtracted.
To find 2's complement:
a. Invert all the bits (1's complement).
b. Add 1 to the result.
3. Add the Minuend and the 2's Complement of the Subtrahend
Perform binary addition of the minuend (the number being subtracted from) and the 2's complement of
the subtrahend.
4. Handle Overflow
If the addition produces an extra carry bit, discard it.
The result is the final subtraction in binary.
Subtraction Rules

Example: 7−5 in Binary Discard Overflow


1. Write the Numbers in Binary The result is 0010
7=0111 (Base 2) Final Answer
5=0101 (Base 2) 7−5=2, and 0010=2
2. Find the 2's Complement of 5
a. Invert the Bits (1's complement): Key Advantages of 2's Complement
0101→1010 1. Eliminates the need for separate
b. Add 1: subtraction circuitry in hardware.
1010+1=1011 2. Handles both positive and negative
numbers seamlessly.
3. Add 7 and the 2's Complement of 5
3. Overflow is automatically managed by
0111 +
discarding the carry.
1011
--------
10010
Example

Subtract 13−9 Using 2's Complement (Base 10)

Step 1: Represent Numbers in Binary

Ensure both numbers have the same number of bits. If necessary, add leading zeros
Example

Subtract 7-13 Using 2's Complement (Base 10)

Step 1: Represent Numbers in Binary

Ensure both numbers have the same number of bits. If necessary, add leading zeros
Example

Perform Binary Addition

The result is 1010​. Since the leftmost


bit (MSB) is 1, it indicates a negative
number (in 2's complement
representation).
Addition of Hexadecimal Numbers
Addition of Hexadecimal Numbers

Let’s add 0x1A3F and 0x2B5E step by step. 1A3F


+
2B5E
Subtraction of Hexadecimal Numbers
Subtraction of Hexadecimal Numbers
Answer: 111F
Let's solve 0x2B5E - 0x1A3F step by step: 2B5E
-
1A3F
2.1
THE
MICROCONTROLLER
What is a Microcontroller?

Definition:
A microcontroller is a compact integrated circuit (IC) designed to execute specific
control-oriented tasks in embedded systems.
It combines multiple functionalities into one chip, making it cost-effective and
efficient for small-scale applications.

Key Features:
Integrated Components:
Includes a CPU, memory (RAM/ROM/Flash), and I/O peripherals on a single chip.
Often includes timers, ADCs (Analog-to-Digital Converters), DACs (Digital-to-Analog
Converters), and communication interfaces (SPI, I2C, UART).
Real-Time Operation:
Optimized for low-latency and real-time control applications.
Low Power Consumption:
Ideal for battery-operated and energy-sensitive devices.
Embedded Programming:
Programs are written in Assembly or Embedded-C and stored in ROM.
Compact Size:
Reduces hardware complexity and cost by integrating components.

Examples:
8051, AVR, PIC, and ARM Cortex-M series.
Application of Microcontrollers

1. Consumer Electronics
Microcontrollers are embedded in devices for automation and control.
Examples:
Washing Machines: Control water level, temperature, and spin cycles.
Smart TVs: Manage remote control inputs, streaming, and smart features.
Microwave Ovens: Regulate cooking time, power levels, and user inputs.
2. Automotive
Microcontrollers enable automation and safety features in vehicles.
Examples:
Engine Control Units (ECUs): Optimize fuel injection, ignition timing, and
emissions.
Anti-lock Braking Systems (ABS): Monitor wheel speed and prevent skidding.
Airbag Deployment: Control real-time deployment based on crash sensors.
Application of Microcontrollers

3. Industrial Automation
Used in systems requiring precise real-time control and monitoring.
Examples:
PLCs (Programmable Logic Controllers): Control machinery and factory
processes.
Robotics: Manage robotic arms and automated assembly lines.
Energy Monitoring: Measure power usage and improve energy efficiency.
4. IoT Devices
Microcontrollers power smart, interconnected devices.
Examples:
Smart Thermostats: Control heating and cooling based on user preferences and
sensors.
Home Automation Systems: Control lights, fans, and appliances remotely.
Wearables: Track health metrics like heart rate and steps.
What is a Microprocessor?
Definition
A microprocessor is a central processing unit (CPU) designed to execute general-
purpose computational tasks.
Unlike a microcontroller, it lacks integrated peripherals (like RAM, ROM, or I/O) and
relies on external components for operation.
Key Features
1. High Computational Power:
Optimized for complex tasks like multitasking, data processing, and high-speed
calculations.
Capable of executing millions of instructions per second (MIPS).
2. Modularity:
Requires external memory (RAM/ROM) and peripheral devices for full functionality.
More flexible and expandable than microcontrollers.
3. Advanced Instruction Sets:
Supports complex operations with rich instruction sets (e.g., x86, ARM).
4. Not Real-Time Optimized:
Designed for performance, not for real-time operations or low-latency tasks.

Examples
8085, 8086, Intel Core i7, AMD Ryzen, and ARM Cortex-A series.
Application of Microprocessors

Applications
1. Personal Computing:
The backbone of desktops, laptops, and notebooks.
Handles multitasking, file processing, and high-performance applications.
Examples: Running operating systems (Windows, macOS) and applications like MS Office, browsers, and multimedia software.
2. High-Performance Systems:
Powers gaming consoles, servers, and AI models.
Examples:
Gaming: Enables real-time rendering of high-resolution graphics.
AI Workloads: Processes complex machine learning algorithms for tasks like voice recognition (Siri, Alexa).
3. Mobile and Embedded Devices:
Microprocessors like ARM Cortex-A are found in smartphones and tablets.
Powers apps, camera systems, communication modules, and displays.
Examples: Android and iOS devices running apps like WhatsApp or Instagram.
4. Scientific and Technical Computing:
Used in simulations, modeling, and data analysis.
Examples: Weather forecasting, climate modeling, and DNA sequencing.
5. Industrial and Commercial Applications:
Manages large-scale automation systems and robotics.
Examples: Controlling manufacturing equipment or managing databases in banking systems.
Microcontrollers vs Microprocessors

Feature Microcontroller Microprocessor

Definition Integrated circuit for specific tasks CPU for general-purpose computing

Components CPU, memory, and I/O peripherals on one chip Requires external memory, I/O, and peripherals

Cost Low-cost, suitable for mass production Higher cost due to external components and power

Power Consumption Low (optimized for battery-powered devices) High, requires advanced cooling solutions

Processing Power Optimized for simple control tasks Optimized for high-speed, complex computations

Real-Time Operations Designed for real-time control and monitoring Not ideal for strict real-time operations

Applications Embedded systems, IoT, consumer electronics Personal computers, AI systems, gaming consoles

Memory Limited on-chip RAM/ROM Flexible, uses external RAM/ROM

Embedded-C, Assembly, or low-level


Programming High-level programming languages (C++, Python, etc.)
programming

I/O Interface Directly interfaces with sensors, actuators, etc. Interfaces indirectly through external controllers

Examples 8051, ARM Cortex-M, PIC, AVR Intel Core i7, AMD Ryzen, ARM Cortex-A
Microcontrollers vs Microprocessors
2.2
RISC VS CISC
UNDERSTANDING THE PROCESSOR
ARCHITECTURES
Basic Computer Architecture
What is a Computer Architecture?
The design and organization of a computer system.
Determines how the CPU, memory, and input/output
systems interact.
Key Components:
CPU: The brain of the computer, responsible for
executing instructions.
Memory: Stores data and instructions (RAM, cache,
etc.).
Buses: Pathways for data transfer between
components.
Instruction Cycle:
Step 1: Fetch the instruction from memory.
Step 2: Decode the instruction to understand its
purpose.
Step 3: Execute the instruction.
Instruction Sets

What is an Instruction Set?


The commands that a processor can
execute, defined by its architecture.
Examples of Instructions:
Data Transfer: Load, store, move.
Arithmetic/Logic: Add, subtract,
AND, OR.
Control Flow: Branch, jump, loop.
Key Points:
RISC uses simple, fixed-length
instructions.
CISC uses complex, variable-
length instructions.
Introduction to RISC
RISC (Reduced Instruction Set Computing):
Philosophy: Simplify instructions to enhance speed and efficiency.
Characteristics:
Uniform instruction length simplifies decoding.
Optimized for a smaller set of commonly used instructions.
Relies heavily on compiler efficiency to manage complex tasks.
Often uses a load/store architecture (data loaded into registers before
processing).
Benefits:
High performance and low power consumption.
Easier pipelining (parallel processing of instructions).
Common Use Cases:
Mobile devices, IoT, and performance-critical applications.
Introduction to CISC

CISC (Complex Instruction Set Computing):


Philosophy: Reduce the number of instructions required to complete a program.
Characteristics:
A wide variety of instructions, some very complex.
Instructions perform multiple tasks (e.g., loading data and performing
arithmetic in one step).
Designed to minimize software complexity at the expense of hardware
complexity.
Benefits:
Efficient for executing tasks with fewer instructions.
Backward compatibility with older software.
Common Use Cases:
Desktop computers, servers, and systems where software compatibility and
versatility are critical.
Difference between RISC and CISC

Feature RISC CISC

Instruction Set Small, focuses on essential operations Extensive, includes specialized instructions

Execution Single-cycle execution for most instructions Multi-cycle execution for complex operations

Simple and efficient due to fixed instruction


Pipelining Challenging due to varied instruction lengths
size

Memory Access Access only via load/store instructions Instructions often directly access memory

High, relies on compilers to optimize


Compiler Dependency Lower, less compiler optimization required
performance

Advantages Faster execution, low power, simplicity Versatility, fewer instructions for tasks

Disadvantages More instructions per task Higher power, complex hardware


Memory Hierarchy

What is Memory Hierarchy?


An arrangement of storage systems by speed and proximity to the
CPU.
Types of Memory:
Registers: Fastest, smallest capacity, inside the CPU.
Cache: Stores frequently accessed data for quick retrieval.
RAM: Larger capacity, slower than cache, temporary data storage.
Storage (HDD/SSD): Permanent data storage, slowest.
Importance:
Faster memory improves CPU performance.
RISC architectures are optimized for efficient memory use.
Memory Hierarchy

What is Memory Hierarchy?


An arrangement of storage systems by speed and proximity to the
CPU.
Types of Memory:
Registers: Fastest, smallest capacity, inside the CPU.
Cache: Stores frequently accessed data for quick retrieval.
RAM: Larger capacity, slower than cache, temporary data storage.
Storage (HDD/SSD): Permanent data storage, slowest.
Importance:
Faster memory improves CPU performance.
RISC architectures are optimized for efficient memory use.
2.3
VON NEUMANN VS
HARVARD
Von Neumann Architecture

Definition: A single memory unit stores both data and


program instructions.
Key Features:
Single Memory Space: Shared for instructions and
data.
Sequential Execution: Instructions are executed one
after another.
Program Counter: Manages instruction execution
order.
Flexibility: Suitable for general-purpose computing.
Advantages:
Simpler design.
Easier to implement and manage memory.
Disadvantages:
Von Neumann Bottleneck: Shared bus between CPU and
memory causes delays.
Slower performance in modern applications requiring
simultaneous access.
Harvard Architecture

Definition: Separate memory units for data and


program instructions.
Key Features:
Distinct Buses: Independent paths for data and
instructions.
Parallel Processing: Simultaneous fetching and
execution.
Optimized Memory Access: Reduced contention
between data and instructions.
Advantages:
Faster execution due to dedicated buses.
Enhanced performance in specialized systems.
Disadvantages:
More complex hardware.
Increased cost due to separate memory systems.
Applications

Von Neumann Architecture Harvard Architecture


General-Purpose Systems: Specialized Systems:
Personal computers (PCs) and laptops. Embedded systems such as home
Servers, workstations, and mainframes. appliances, automotive control units,
Used in systems requiring flexible and IoT devices.
memory usage for both data and Digital Signal Processors (DSPs) used in
programs. audio, video, and image processing.
Advantages in Applications: Real-time systems requiring fast
Simpler hardware design makes it cost- execution of predefined tasks.
effective for general-purpose Advantages in Applications:
computing. Faster execution due to parallel data
Widely used in software-intensive and instruction fetching.
environments (e.g., Windows, Linux Optimized for systems with repetitive
systems). tasks or limited memory requirements.
Examples: Examples:
x86 architecture in Intel and AMD 8051 microcontroller.
processors. Atmel AVR and PIC microcontrollers.
Differences

Aspect Von Neumann Architecture Harvard Architecture

Memory Design Single memory for both instructions and data. Separate memories for instructions and data.

Data and Instruction Bus Single bus used for both data and instruction transfers. Separate buses for data and instruction transfers.

Slower due to the need to share the bus for instructions Faster as instructions and data can be accessed
Execution Speed
and data. simultaneously.

More complex hardware due to separate buses and memory


Complexity Simpler hardware design, easier to implement.
systems.

Higher cost due to additional components (memory and


Cost Lower cost due to simpler design.
buses).

Only one operation (data or instruction) can occur at a


Memory Access Parallel fetching and execution of instructions and data.
time.

Allows self-modifying code as both data and instructions Does not support self-modifying code as memories are
Flexibility
share memory. separate.

Applications General-purpose computing like PCs, laptops, and servers. Embedded systems, DSPs, and real-time systems.

Examples x86 processors (Intel, AMD). 8051, PIC microcontrollers, and DSPs like TMS320.
2.4

X BIT MICROCONTROLLERS
Word Size

Definition: The word size of a


microcontroller refers to the number of
bits the CPU can process at a time in a
single operation.
It dictates the width of the data bus,
registers, and ALU (Arithmetic Logic Unit).
For example:
An 8-bit microcontroller can process 8
bits of data (1 byte) in a single cycle.
Highway as the Data Bus:
A 16-bit microcontroller can handle 16 Imagine the data bus in a microcontroller as
bits (2 bytes) at a time. a highway where cars represent bits of data.
The word size determines how many cars
A 32-bit microcontroller processes 32
(bits) can travel side-by-side on the
bits (4 bytes) at once. highway at the same time.
Classification by BUS Size

Classification by BUS Size:


8-bit
16-bit
32-bit

Important Conversion
8 Bit microcontrollers

Word Size: 8 bits (can process 8 bits of data


at a time).
Examples: 8051, AVR, PIC16.
Features:
Low processing power.
Typically low power consumption.
Limited memory (RAM: <4 KB, ROM: <64
KB).
Simple architecture; easy to program.
Applications:
Cheap electronic products
Toys
Small-scale embedded systems.
16 Bit microcontrollers

Word Size: 16 bits (can process 16 bits of data at a time).


Examples: MSP430, PIC24, some ARM Cortex-M0.
Features:
Moderate processing power.
Power-efficient for real-time applications.
Increased memory compared to 8-bit MCUs.
More peripherals and GPIOs.
Applications:
Industrial automation.
Mid-range IoT devices.
Motor control.
32 Bit microcontrollers

Word Size: 32 bits (can process 32 bits of data at a time).


Examples: ARM Cortex-M3/M4, STM32, ESP32.
Features:
High processing power.
Large memory capacity.
Advanced peripherals and real-time performance.
Support for complex algorithms like DSP.
Applications:
High-end IoT devices.
Automotive systems.
Advanced robotics.
Difference between 8bit, 16bit, 32 bit microcontrollers

Feature 8-bit MCU 16-bit MCU 32-bit MCU

Word Size 8 bits 16 bits 32 bits

Processing Power Low Moderate High

Memory Support Limited (<64 KB) Moderate (<512 KB) High (>1 MB)

Power Consumption Very Low Low to Moderate Moderate

Peripherals Basic Moderate Advanced

Cost Lowest Mid-range Higher

Applications Simple IoT, Automation Industrial IoT, Motor Control Advanced IoT, Automotive
2.5

MEMEORY, POINTERS, AND


EXECUTION
Introduction to Memory Structures

Memory in Microcontrollers/Computers:
Divided into Program Memory and Data
Memory. Think of a library:
Example: Harvard vs. Von Neumann Program memory is the bookshelf
where permanent books
architecture. (instructions) are stored.
Program Memory: Like a recipe book—you follow the
instructions but don’t alter the
Stores executable code. book.

Non-volatile (e.g., Flash memory). Data memory is the study desk


Data Memory: where temporary notes (variables,
stack data) are written.
Stores runtime data (variables, stack, Like a notepad—you write
etc.). calculations, erase, and reuse.

Volatile (e.g., RAM).


Program Memory

Details:
Program memory is a type of memory used to store the instructions or code that a processor executes.
It is non-volatile, meaning it retains its contents even when the power is turned off. This makes it ideal for
storing permanent instructions, like the firmware of a device.
Contains machine instructions.
Read-only during execution.
Organized in sequential addressable blocks
Types:
ROM/Flash memory.
Erasable Programmable Read-Only Memory (EPROM).
Why is It Read-Only During Execution?
Program memory is read-only during execution to prevent accidental overwriting of critical instructions.
This ensures the integrity of the code being executed.
In many systems, write-protection mechanisms are in place to avoid modifications during runtime.

Example:
In microcontrollers like AVR or PIC, Flash memory is used to store code.
Data Memory
What is Data Memory?
Volatile Memory: Loses its content when power is off.
Stores runtime data, including:
Global Variables: Persistent throughout the program's execution (long-term notes).
Local Variables: Temporary data used in functions (scratchpad).
Stack: Special memory area for managing function calls and temporary storage.
Types of Data Memory
Registers:
Fastest memory directly within the CPU.
Used for immediate computations and quick data transfer.
Limited in size (e.g., Accumulator, Index Register).
RAM (Random Access Memory):
Larger but slower than registers.
Divided into:
Heap: For dynamic memory allocation.
Stack: For function calls, local variables, and interrupt handling.
How It Works
During execution:
The CPU fetches instructions from program memory.
Intermediate results and runtime data are stored in data memory.
Pointers
What is a Stack?
A Last In, First Out (LIFO) data structure in data memory.
Used for temporary storage of critical data during program execution.
Grows dynamically during runtime.
Uses of the Stack
1. Function Calls:
Stores return addresses to ensure the program can resume after the
function is executed.
Example: When calling a function, the CPU "remembers" the next
instruction address using the stack.
2. Temporary Variables:
Holds data local to functions (e.g., loop counters or intermediate
calculations).
3. Interrupt Handling:
Saves the current execution state to allow servicing an interrupt.
Stack Pointer (SP)
A special register that points to the top of the stack.
Automatically updates during:
Push: Adds data to the stack (SP decreases in most architectures).
Pop: Removes data from the stack (SP increases)
Program Counter

What is the Program Counter (PC)?


The Program Counter (PC) is a special register in the CPU that keeps track of the memory address of the next
instruction to be executed.
It is essential for maintaining the sequential flow of program execution unless a control instruction (e.g., jump, call)
alters it.
How Does the PC Work?
Sequential Execution:
By default, the PC increments after every instruction fetch.
Example: If the PC starts at 0x1000, after fetching the instruction at 0x1000, it increments to 0x1001 to fetch the
next instruction.
Modified During:
Jumps: Redirects program execution to a specific address.
Example: A JUMP 0x2000 instruction sets PC to 0x2000, so the next fetch happens there.
Function Calls: Stores the current PC value on the stack and loads the function’s starting address into the PC.
Interrupts: Saves the current PC to the stack and jumps to the interrupt service routine (ISR).
Returns:
After completing a function or servicing an interrupt, the PC is restored from the stack to resume normal execution.
Why is the PC Important?
The PC ensures the correct order of execution by guiding the CPU on which instruction to process next.
Without the PC, the CPU would lose track of its position in the program.
Execution of Programs
1. Fetch: CPU Fetches the Instruction
What Happens:
The Program Counter (PC) contains the address of the next instruction to be executed.
The CPU uses this address to fetch the instruction from Program Memory.
The fetched instruction is stored in the Instruction Register (IR) for further processing.
Example:
If PC = 0x0010, the CPU fetches the instruction stored at address 0x0010 in Program
Memory.
2. Decode: Understanding the Instruction
What Happens:
The CPU decodes the fetched instruction to understand:
Operation: What action to perform (e.g., addition, move).
Operands: The data to operate on (e.g., registers, memory locations).
Decoding involves breaking down the binary code into recognizable commands.
Example:
Instruction 11001000 might mean "Add the contents of Register A and Register B".
Execution of Programs
3. Execute: Performing the Operation
What Happens:
The CPU performs the decoded operation.
Examples of operations:
Arithmetic: Add, subtract, multiply.
Logic: AND, OR, XOR, NOT.
Data Transfer: Move data from one location to another.
Control: Change the program flow (e.g., jump, call).
Example:
If the instruction was ADD A, B, the CPU adds the values in Register A and Register B and stores the result
back in Register A.
4. Store: Writing Back Results
What Happens:
After execution, the result is stored back in:
A register (fast access).
Data Memory (for variables and intermediate results).
A peripheral (e.g., sending data to an output device).
Example:
If the instruction was ADD A, B, the result (e.g., 5 + 3 = 8) is stored in Register A.
3

8051 MICROCONTROLLER
8051 Architecture
Salient Features

Eight bit CPU


On chip clock oscillator
4Kbytes of internal program memory (code memory) [ROM]
128 bytes of internal data memory [RAM]
64 Kbytes of external program memory address space.
64 Kbytes of external data memory address space.
32 bi directional I/O lines (can be used as four 8 bit ports or 32 individually addressable I/O
lines)
Two 16 Bit Timer/Counter :T0, T1
Full Duplex serial data receiver/transmitter
Four Register banks with 8 registers in each bank.
Sixteen bit Program counter (PC) and a data pointer (DPTR)
8 Bit Program Status Word (PSW)
8 Bit Stack Pointer
Five vector interrupt structure (RESET not considered as an interrupt.)
8051 CPU consists of 8 bit ALU with associated registers like accumulator ‘A’, B register, PSW,
SP, 16 bit program counter, stack pointer.
ALU can perform arithmetic and logic functions on 8 bit variables.
8051 has 128 bytes of internal RAM which is divided into
Working registers [00 – 1F]
Bit addressable memory area [20 – 2F]
General purpose memory area (Scratch pad memory) [30-7F]
The Stack and the Stack Pointer

The stack refers to an area of internal RAM that is used in conjunction with
certain opcodes to store and retrieve data quickly.
The 8-bit stack pointer (SP) register is used by the 8051 to hold an internal RAM
address that is called the "top of the stack."
The top of the stack is the location in internal RAM where the last byte of data
was stored by a stack operation.
The SP increments befo re storing data on the stack so that the stack grows up as
data is stored.
As data is retrieved from the stack, the byte is read from the stack, and then the
SP decrements to point to the next available byte of stored data.
The SP is set to 07h when the 8051 is reset and can be changed to any internal
RAM address by the programmer
Program Counter (PC) and Data Pointer (DPTR)

Program instruction bytes are fetched from locations in memory that are
addressed by the PC.
The PC is automatically incremented after every instruction byte is fetched and
may also be altered by certain instructions.
The PC is the only register that does not have an internal address.
The DPTR register is made up of two 8-bit registers, named DPH and DPL
Are used to furnish memory addresses for internal and external code access and
external data access.
The DPTR is under the control of program instructions
Can be specified by its 16-bit name, DPTR, or by each individual byte name, DPH
and DPL.
DPTR does not have a single internal address; DPH and DPL are each assigned an
address.
A and B CPU Registers

The 8051 contains 34 general-purpose, or working, registers. Two of these,


registers A and B.
The other 32 are arranged as part of internal RAM in four banks, BO-B3, of eight
registers each, named RO to R7.
The A (accumulator) register is used for many operations, including addition,
subtraction, integer multiplication and division, and Boolean bit manipulations.
The A register is also used for all data transfers between the 8051 and any
external memory.
The B register is used with the A register for multiplication and division
operations.
Flags and the Program Status Word (PSW)

Flags are 1-bit registers provided to store the results of certain program
instructions.
Other instructions can test the condition of the flags and make decisions based
upon the flag states.
The 8051 has four math flags that respond automatically to the outcomes of
math operations and three general-purpose user flags that can be set to 1 or
cleared to 0 by the programmer as desired
The math flags include carry (C), auxiliary carry (AC), overflow (OY), and parity (P).
User flags are named FO, GFO, and GFI; they are general-purpose flags.
Note that all of the flags can be set and cleared by the programmer.
Flags and the Program Status Word (PSW)
Special Function Registers

The 8051 has a group of specific internal registers, each called a special-function
register (SFR), which may be addressed much like internal RAM, using addresses
from 80h to FFh.
Some SFRs (marked with an asterisk*) are also bit addressable; this feature allows
the programmer to change only what needs to be altered, leaving the remaining
bits in that SFR unchanged.
Not all of the addresses from 80h to FFh are used for SFRs, and attempting to use
an address that is not defined, or "empty" results in unpredictable results.
SFRs are named in certain opcodes by their functional names, such as A or TH0,
and are referenced by other opcodes by their addresses, such as 0E0h or 8Ch.
Note that any address used in the program must start with a number; thus
address E0h for the A SFR begins with 0
Failure to use this number convention will result in an assembler error when the
program isassemble
Special Function Registers
8051 Pin Diagram
8051 Pin Diagram
8051 Pin Diagram
XTAL1 and XTAL2

The 8051 has an on-chip


oscillator but requires an
external crystal to run it
A quartz crystal oscillator is
connected to inputs XTAL1
(pin19) and XTAL2 (pin18)
The quartz crystal oscillator
also needs two capacitors of
30 pF value
The original 8051 operates at 12
MHZ
XTAL1 and XTAL2

The 8051 requires a clock signal for timing and execution of


instructions.
Typically, an external crystal oscillator (like a 12 MHz quartz crystal)
is connected between XTAL1 and XTAL2, along with two small
capacitors (commonly 30pF) to stabilize the oscillation.
The oscillator generates a precise clock signal that drives the
internal CPU timing.
It is like the heartbeat of the microcontroller
RST
RESET pin is an input and is active high (normally low)
Upon applying a high pulse to this pin, the microcontroller will reset and
terminate all activities
This is often referred to as a power-on reset
Activating a power-on reset will cause all values in the registers to be lost
EA
EA’, “external access’’, is an input pin and must be connected to Vcc or GND
The 8051 family members all come with on-chip ROM to store programs and
also have an external code and data memory.
Normally EA pin is connected to Vcc (Internal Access)
EA pin must be connected to GND to indicate that the code or data is stored
externally.

PSEN’ and ALE

PSEN, “program store enable’’, is an output pin


This pin is connected to the OE pin of the external memory.
For External Code Memory, PSEN’ = 0
For External Data Memory, PSEN’ = 1
ALE pin is used for demultiplexing the address and data.
Internal Memory Organization
A functioning computer must have
MEMORY FOR PROGRAM CODE BYTES,
COMMONLY IN ROM
RAM MEMORY FOR VARIABLE DATA THAT
CAN BE ALTERED AS THE PROGRAM
RUNS.
 Additional memory can be added
externally using suitable circuits.
 8051 has a Harvard architecture, which
uses the same address , in different
memories, for
code and data.
Internal circuitry accesses the correct
memory based upon the nature of the
operation in progress.
Internal RAM
Thirty-two bytes from address 00h to 1Fh that make up 32 working
registers organized as four banks of eight registers each. (Bank0- Bank3;
with each bank having registers R0-R7)
Each register can be addressed by name (when its bank is selected) or
by its RAM address.
Thus R0 of bank 3 is R0 (if bank 3 is currently selected) or address 18h
(whether bank 3 is selected or not)
Bits RS0 and RS1 in the PSW determine which bank of registers is
currently in use.
Register banks not selected can be used as general-purpose RAM.
Bank 0 is selected upon reset.
A bit-addressable area of 16 bytes occupies RAM byte addresses 20h to
2Fh, forming a total of 128 addressable bits.
An addressable bit may be specified by its bit address of 00h to 7Fh, or 8
bits may form any byte address from 20h to 2Fh
Thus, for example, bit address 4Fh is also bit 7 of byte address 29h
Addressable bits are useful when the program need only remember
a binary event (switch on, light off, etc.).
A general-purpose RAM area above the bit area, from 30h to 7Fh,
addressable as bytes
Internal ROM

The 8051 is organized so that data memory and program code memory can be in two entirely
different physical memory entities; each has the same address ranges.
A corresponding block of internal program code, contained in an internal ROM, occupies code
address space 0000h to 0FFFh.
The PC is ordinarily used to address program code bytes from addresses 0000h to 0FFFh.
Program addresses higher than 0FFFh, which exceed the internal ROM capacity, will cause the 8051
to automatically fetch code bytes from external program memory
Code bytes can also be fetched exclusively from an external memory, addresses 0000h to FFFFh, by
connecting the external access pin (EA pin 31 on the DIP) to ground.
The PC does not care where the code is; the circuit designer decides whether the code is found
totally in internal ROM, totally in external ROM, or in a combination of internal and external ROM.
Input/ Output Pins, Ports, and Circuits

Ports can be accessed directly by instructions during program execution


I/O ports are memory mapped, they are treated as memory locations
All ports are bit addressable
Each PIN consists of a D latch, I/P buffer and O/P driver
SFRs for each port is made of 8-latches
Accessed by SFRs address or name of that port
The four 8-bit I/O ports P0, P1, P2 and P3 each uses 8 pins
ll the ports upon RESET are configured as output, ready to be used as output ports
When the first 0 is written to a port, it becomes an output
To reconfigure it as an input, a 1 must be sent to the port
To use any of these ports as an input port, it must be programmed
Unit 2:
PROGRAMMING WITH
MICROCONTROLLERS
What are Assembler Directives?

Special instructions for the assembler, not


executed by the microcontroller.
Used to define memory locations, constants,
and program structure.
Help in better code organization and easier
debugging.
Control the assembly process by specifying
where data/code should be stored.
E.g : ORG (Origin)
Defines the starting address for the code or data.
ORG 0000H ; Start the program at address 0000H
MOV A, #55H ; Load 55H into accumulator
Categories of Assembler Directives

Data Definition Directives - Define constants and


memory storage.
Code Organization Directives - Define the structure
of the program.
Memory Allocation Directives - Allocate memory
space.
Control Directives - Control the flow of the
assembly process.
Data Definition Directives

DB (Define Byte): Stores an 8-bit value.


Example: `MYDATA DB 0FFH` (Stores 0FFH in
memory)
DW (Define Word): Stores a 16-bit word.
Example: `MYWORD DW 1234H` (Stores 1234H in
memory)
EQU (Equate): Assigns a constant value to a label.
Example: `COUNT EQU 10` (COUNT is replaced
with 10)
Code Organization Directives

ORG (Origin): Specifies the starting address of the


program.
Example: `ORG 0000H` (Starts program at address
0000H)
END: Marks the end of the assembly program.
Example: `END` (Signifies the end of the source file)
SEGMENT: Defines different segments like CODE, DATA,
BIT.
Example: `DATA SEGMENT` (Defines the start of a
data segment)
Code Organization Directives
DATA SEGMENT
NUM1 DB 25 ; Store 25 in memory
NUM2 DB 50 ; Store 50 in memory
RESULT DB ? ; Reserve 1 byte for RESULT (uninitialized)
DATA ENDS

DATA SEGMENT → Marks the beginning of the data section.


NUM1 DB 25 → Defines a byte (DB) with value 25.
NUM2 DB 50 → Defines another byte with value 50.
RESULT DB ? → Reserves space for a variable but does not initialize it.
DATA ENDS → Marks the end of the data segment.
Memory Allocation Directives

`DS (Define Storage)`: Reserves memory space.


Example: `VAR DS 10` (Reserves 10 bytes for VAR)
`RS (Reserve Space)`: Reserves memory for registers.
Example: `TEMP RS 2` (Reserves 2 register spaces)
`USING`: Defines the register bank to be used.
Example: `USING 2` (Selects Register Bank 2)
Control Directives

`IF, ELSE, ENDIF`: Conditional assembly.


Example: `IF DEBUG MOV A, #55H ENDIF`
The instruction MOV A, #55H only if DEBUG is defined and
nonzero. If DEBUG is not defined or zero, the assembler
ignores the instruction, allowing for flexible debugging or
feature-specific code inclusion.
`MACRO & ENDM`: Define reusable code blocks.
Example: `MYMACRO MACRO` (Start macro definition)
`INCLUDE`: Includes external files in assembly.
Example: `INCLUDE myfile.inc`
Importance of Assembler Directives

Improves Code Readability: Helps in structured programming.


Efficient Memory Utilization: Allocates memory properly.
Simplifies Debugging: Uses labels and structured code.
Optimizes Execution: Ensures correct code placement.
Assembler directives guide the assembly process.
They help in defining memory, constants, and program flow.
Essential for efficient embedded system development using
8051.
Proper use of directives improves code maintainability and
performance.
Editor

A software tool used to


write and edit source
code.
Provides syntax
highlighting, auto-
indentation, and basic
error checking.
Examples: Keil µVision,
Notepad++, VS Code.
Linker

A program that combines


multiple object files into a single
executable file.
Resolves references between
different modules and assigns
final memory addresses.
Example: Converts multiple
`.obj` files into a `.hex` file for
microcontrollers.
Linker
A linker is a program that takes different parts of a program (written in multiple files) and
combines them into a single executable file.
How it Works:
When you write a program, it may have multiple source files (like functions or libraries).
The compiler converts these files into object files (.obj or .o), which contain machine
code but are not yet complete.
The linker joins these object files and resolves missing connections (like function calls
from one file to another).
It creates a final executable file (.exe, .hex, or .bin for embedded systems) that can run
on a microcontroller or computer.
Example:
If your code uses a function from a library, the linker makes sure the correct function is
included.
It ensures everything is connected properly before the program runs.
Think of a linker like a puzzle solver—it takes different pieces (files) and fits them together to
create a complete program!
Loader
A system program that loads an executable file into memory for execution.
Ensures that program instructions and data are properly placed in RAM.
In embedded systems, the loader places firmware into microcontroller memory.
A loader is a program that loads an executable file into memory so the CPU can run it.
How It Works:
The linker creates an executable file (.exe, .hex, .bin).
The loader places this file into RAM and sets up necessary resources.
It hands control to the CPU to start execution.
Example:
In embedded systems, a loader transfers firmware (.hex file) into a microcontroller's
memory so it can run.
On a computer, when you open a software application, the OS loads it into RAM using a
loader.
Think of a loader like a movie projector—it places the film (program) in position so it can be
played (executed)!
Debugger

A tool that helps find and fix errors in a program.


Provides features like breakpoints, step execution, and memory
inspection.
Examples: Keil Debugger, GDB (GNU Debugger).

A debugger is a tool that helps programmers find and fix errors (bugs)
in their code by allowing them to observe how a program runs.
What a Debugger Does:
Runs the program step-by-step to check each instruction.
Sets breakpoints (pauses execution at a specific line).
Watches variables and registers to see how values change.
Detects errors like crashes or incorrect logic.
Helps modify and test fixes without restarting the entire program.
Simulator
A software tool that mimics the behavior of a microcontroller or processor.
Allows code testing without actual hardware.
Example: Keil µVision Simulator, Proteus.
A simulator is a software tool that mimics the behavior of a microcontroller or
processor, allowing you to test your program without actual hardware.
What a Simulator Does:
1. Executes code virtually, just like it would run on real hardware.
2. Displays register values, memory, and I/O operations to check program behavior.
3. Helps debug and test code before loading it onto a physical microcontroller.
4. Saves time and cost, as you don’t need the actual hardware for initial testing.
Example:
Keil µVision Simulator allows you to run 8051 assembly/C programs and monitor
CPU registers.
Proteus lets you visually simulate circuits with microcontrollers before building
them.
Emulator

A hardware tool that replicates the behavior of a real microcontroller.


Helps test programs on actual hardware conditions before final deployment.
Example: ICE (In-Circuit Emulator).
An emulator is a hardware or software tool that replicates the behavior of a real
microcontroller or system, allowing programs to run as if they were on actual hardware.
What an Emulator Does:
1. Runs real code on a virtual or substitute hardware setup.
2. Mimics the exact behavior of the target system, including CPU, memory, and peripherals.
3. Allows debugging and testing under real-world conditions.
4. Can be used to test firmware before deploying on actual hardware.
Example:
In-Circuit Emulator (ICE) is a hardware tool that connects to a microcontroller and lets
developers test programs in real-time.
QEMU (software emulator) allows running ARM-based firmware on a PC.
Summary

Editor: Used for writing code.


Linker: Combines object files into an executable.
Loader: Loads the executable into memory.
Debugger: Helps find and fix errors.
Simulator: Software-based microcontroller testing.
Emulator: Hardware-based testing tool.
3

INSTRUCTION SET
8051 Instruction Set
General syntax for 8051 assembly language is as follows.
LABEL: OPCODE OPERAND ; COMMENT
LABEL: (THIS IS NOT NECESSARY UNLESS THAT SPECIFIC LINE HAS TO BE
ADDRESSED). The label is a symbolic address for the instruction. When the program is assembled, the label
will be given specific address in which that instruction is stored. Unless that specific line of instruction is
needed by a branching instruction in the program, it is not necessary to label that line.
OPCODE: Opcode is the symbolic representation of the operation. The assembler converts the opcode to a
unique binary code (machine language).
OPERAND: While opcode specifies what operation to perform, operand specifies where to perform that
action. The operand field generally contains the source and destination of the data. In some cases only
source or destination will be available instead of both. The operand will be either address of the data, or
data itself.
COMMENT: Always comment will begin with ; or // symbol. To improve the program quality,
programmer may always use comments in the program.
Types of Operand
What is an Operand?
The operand is the data on which an instruction operates.
It can be a constant, a register, or a memory address.
MOV A, #30H ; Here, #30H is the operand (immediate value)
MOV A, R1 ; Here, R1 is the operand (register)
MOV A, 40H ; Here, 40H is the operand (direct memory address)
MOV A, @R0 ; Here, @R0 is the operand (indirect memory location)

Operand Type Example Description

Immediate MOV A, #10H Direct constant value

Register MOV A, R2 Data in a register

Memory MOV A, 50H Data stored at a memory address

Indirect MOV A, @R1 Data from an address stored in a register


Instruction
What is an Instruction?
A command given to the microcontroller to perform a
specific task. e.g

Every instruction consists of: MOV A, #50H ; Move immediate value 50H into accumulator A

Mnemonic (operation name) ADD A, R2 ; Add the value of register R2 to A

Operands (values, registers, or memory addresses)

Instruction Type Example Description

Data Transfer MOV A, R1 Move data between registers/memory

Arithmetic ADD A, R3 Perform math operations

Logical ANL A, R2 Perform AND, OR, XOR operations

Branching SJMP LABEL Change program flow (jumps, calls)

Bit Manipulation SETB P1.0 Set/Clear specific bits


Mnemonic
What is a Mnemonic?
A short name for an assembly instruction. Mnemonic Meaning

Makes it easier to write and remember. MOV Move data

ADD Add two values

SUBB Subtract

ANL AND logic operation

ORL OR logic operation

CLR Clear (set to 0)

SETB Set bit to 1

Jump to another
JMP
instruction
Opcode (Operation Code)
What is an Opcode?
The machine code (binary/hex value) of an instruction.
Mnemonics are for humans, but microcontrollers
understand opcodes.

Mnemonic Opcode

MOV A, #30H 74 30

ADD A, R2 28

JMP 1000H 02 10 00
Addressing Modes

Immediate

Addressing Modes Register Direct

Memory Indirect

Indexed
Immediate Addressing Mode
In this mode, the operand (data) is directly given in the instruction.
The data is immediately available and does not need to be fetched from memory or
registers.

MOV destination, #data

MOV → Move instruction


destination → Register where the data is stored
#data → Immediate value (indicated by #)

Use Cases
Setting initial values for loops and counters.
Defining constants in a program.
Performing quick arithmetic operations without using memory.
Register Addressing Mode
The operand is stored in a register.
The instruction refers directly to the register.

MOV destination, source


MOV A, R3 ; Copy contents of Register R3 into Accumulator A
MOV R2, R1 ; Copy contents of Register R1 into Register R2

Use Cases
Fast execution (registers are inside CPU).
Used in loops where values need frequent updates.
Temporary storage for calculations
Direct Addressing Mode
The operand is located in an internal RAM address.
The instruction directly specifies the memory address

MOV A, 40H ; Load the value from RAM address 40H into A
MOV 50H, R2 ; Store the value of R2 into memory address 50H

Use Cases
Storing variables in internal RAM.
Flags and control registers can be accessed directly.
Used in embedded applications for memory-based operations.
Indirect Addressing Mode
A register (R0 or R1) holds the memory address instead of the actual data.
The instruction fetches data from the memory location pointed to by the register.

MOV R0, #40H ; Store address 40H in R0


MOV A, @R0 ; Fetch value from memory address 40H into A
MOV @R0, R3 ; Store the value of R3 into memory address 40H

Use Cases
Used for arrays and buffers (when data location is variable).
Accessing external RAM in 8051 (e.g., via MOVX).
Efficient when processing multiple memory locations dynamically.
Indexed Addressing Mode
Definition
The operand address is calculated using an offset (A) and a base register (DPTR or PC).
Used only for reading from Program Memory (ROM).

MOV DPTR, #2000H ; Load base address 2000H into DPTR


MOV A, #05H ; Load offset value 05H into A
MOVC A, @A+DPTR ; Fetch byte from ROM at (2000H + 05H)

Use Cases
Used for lookup tables in ROM (e.g., fonts, sine wave values).
Fetching pre-stored data from program memory.
Waveform generation, character mapping.
Comparison Table of Addressing Modes

Addressing Mode Example Where Used? Speed Use Cases

Fixed values,
Immediate MOV A, #10H Constants Fast
counters, delays

Temporary values,
Register MOV A, R2 Registers Fastest
quick operations

Variables, flags,
Direct MOV A, 30H Internal RAM Medium
buffers

Internal & External Arrays, flexible


Indirect MOV A, @R0 Medium
RAM memory access

MOVC A, Program Memory Lookup tables,


Indexed Slow
@A+DPTR (ROM) font storage
EMBEDDED C BASICS
Embedded C
Embedded Software or Program allow Hardware to monitor
external events (Inputs / Sensors) and control external devices
(Outputs) accordingly.
During this process, the program for an Embedded System may
have to directly manipulate the internal architecture of the
Embedded Hardware (usually the processor) such as Timers, Serial
Communications Interface, Interrupt Handling, and I/O Ports etc.
There are many programming languages that are used for
Embedded Systems like Assembly (low-level Programming
Language), C, C++, JAVA (high-level programming languages), Visual
Basic, JAVA Script (Application level Programming Languages), etc.
In the process of making a better embedded system, the
programming of the system plays a vital role and hence, the
selection of the Programming Language is very important.
What to use?
The following are few factors that are to be considered while
selecting the Programming Language for the development of
Embedded Systems.
Size: The memory that the program occupies is very important
as Embedded Processors like Microcontrollers have a very
limited amount of ROM (Program Memory).
Speed: The programs must be very fast i.e., they must run as
fast as possible. The hardware should not be slowed down due
to a slow running software.
Portability: The same program can be compiled for different
processors.
Ease of Implementation
Ease of Maintenance
Readability
Why C?

There are other high-level programming languages that offered the


above mentioned features but none were close to C Programming
Language. Some of the benefits of using Embedded C as the main
Programming Language:
Significantly easy to write code in C
Consumes less time when compared to Assembly
Maintenance of code (modifications and updates) is very simple
Make use of library functions to reduce the complexity of the
main code
You can easily port the code to other architecture with very little
modifications
History of C

Developed by Dennis Ritchie in the late 60’s and early 70’s, is the most
popular and widely used programming language. T
he C Programming Language provided low level memory access using an
uncomplicated compiler (a software that converts programs to machine
code) and achieved efficient mapping to machine instructions.
wide range of applications ranging from Embedded Systems to Super
Computers.
Embedded C Programming Language, which is widely used in the
development of Embedded Systems, is an extension of C Program Language.
The Embedded C Programming Language uses the same syntax and
semantics of the C Programming Language like main function, declaration of
datatypes, defining variables, loops, functions, statements, etc.
Embedded C and C

There is actually not much difference between C and Embedded C apart from
few extensions and the operating environment. Both C and Embedded C are
ISO Standards that have almost same syntax, datatypes, functions, etc.
Embedded C is basically an extension to the Standard C Programming
Language with additional features like Addressing I/O, multiple memory
addressing and fixed-point arithmetic, etc.
C Programming Language is generally used for developing desktop
applications, whereas Embedded C is used in the development of
Microcontroller based applications.
Basic of Embedded C

Keywords in Embedded C
A Keyword is a special word with a special meaning to the compiler (a C
Compiler for example, is a software that is used to convert program written
in C to Machine Code). For example, if we take the Keil’s Cx51 Compiler (a
popular C Compiler for 8051 based Microcontrollers) the following are some
of the keywords:
bit
sbit
sfr
Small
Large
Data types in Embedded C

Data Types in C Programming Language (or any programming language for


that matter) help us declaring variables in the program.
There are many data types in C Programming Language like signed int,
unsigned int, signed char, unsigned char, float, double, etc. In addition to
these there few more data types in Embedded C.
Basic Structure
The following part shows the basic structure of an Embedded C Program.
Multiline Comments . . . . . Denoted using /*……*/
Single Line Comments . . . . . Denoted using //
Preprocessor Directives . . . . . #include<…> or #define
Global Variables . . . . . Accessible anywhere in the program
Function Declarations . . . . . Declaring Function
Main Function . . . . . Main Function, execution begins here
{
Local Variables . . . . . Variables confined to main function
Function Calls . . . . . Calling other Functions
Infinite Loop . . . . . Like while(1) or for(;;)
Statements . . . . .
….
….
}
Function Definitions . . . . . Defining the Functions
{
Local Variables . . . . . Local Variables confined to this Function
Statements . . . . .
….
….
}
Components of Embedded C
Comments
Comments are readable text that are written to help us (the reader) understand the code easily.
They are ignored by the compiler and do not take up any memory in the final code (after
compilation).
There are two ways you can write comments: one is the single line comments denoted by // and
the other is multiline comments denoted by /*….*/.
Preprocessor Directive:
A Preprocessor Directive in Embedded C is an indication to the compiler that it must look in to
this file for symbols that are not defined in the program.
In C Programming Language (also in Embedded C), PreprocessorDirectives are usually
represented using # symbol like #include… or #define….
Global Variables: Global Variables, as the name suggests, are Global to the program i.e., they can be
accessed anywhere in the program.
Local Variables: Local Variables, in contrast to Global Variables, are confined to their respective
function.
Main Function: Every C or Embedded C Program has one main function, from where the execution of
the program begins.
Basic Types and Operators
Basic data types
Types: char, int, float and double
Qualifiers: short, long, unsigned, signed, const
Constant: 0x1234, 12, “Some string”
Enumeration:
Names in different enumerations must be distinct
enum WeekDay_t {Mon, Tue, Wed, Thur, Fri};
enum WeekendDay_t {Sat = 0, Sun = 4};
Arithmetic: +, -, *, /, %
prefix ++i or --i ; increment/decrement before value is used
postfix i++, i--; increment/decrement after value is used
Relational and logical: <, >, <=, >=, ==, !=, &&, ||
Bitwise: &, |, ^ (xor), <<, >>, ~(ones complement)
Conditional Statements
If statement is responsible for modifying the flow of execution of a program. If statement is always used with a
condition. The condition is evaluated first before executing any statement inside the body of If
If/Else If
Else If
#include <stdio.h>

int main() {
int marks = 75; // Example input: marks obtained by a student

if (marks >= 90) {


printf("Grade: A\n");
}
else if (marks >= 75) {
printf("Grade: B\n");
}
else if (marks >= 50) {
printf("Grade: C\n");
}
else {
printf("Grade: F\n");
}

return 0;
}
Nested If-Else
What is the output?
Loops
What is Loop in C?
Looping Statements in C execute the sequence of statements many
times until the stated condition becomes false.
A loop in C consists of two parts, a body of a loop and a control
statement.
The control statement is a combination of some conditions that
direct the body of the loop to execute until the specified condition
becomes false.
The purpose of the C loop is to repeat the same code a number of
times.
Types of Loops

Entry Controlled Loop –


condition is checked
before entering the
body of the loop
Exit Controlled Loop –
condition is checked
before exiting the body
of the loop
Entry Controlled Loop

#include <stdio.h>

int main() {
int i = 1; // Initialize the counter

// Entry-controlled loop (condition checked first)


while (i <= 5) {
printf("%d\n", i); // Print the current value of i
i++; // Increment the counter
}

return 0;
}
Exit Controlled Loop

int i = 10;

do {
printf("%d\n", i); // This executes even though i > 5
i++;
} while (i <= 5);
Infinite Loops

The control conditions must be well defined and specified otherwise the loop will
execute an infinite number of times. The loop that does not stop executing and
processes the statements number of times is called as an infinite loop. An infinite
loop is also called as an "Endless loop." Following are some characteristics of an
infinite loop:
No termination condition is specified.
The specified conditions never meet.
#include <stdio.h>

int main() {
while (1) { // Condition is always true
printf("This is an infinite loop.\n");
}

return 0;
}
Types of Loops

While
Do-While
For
While

It is an entry-controlled loop.
In while loop, a condition is evaluated before processing a body of the loop. If a
condition is true then and only then the body of a loop is executed.
After the body of a loop is executed then control again goes back at the
beginning, and the condition is checked if it is true, the same process is executed
until the condition becomes false.
Once the condition becomes false, the control goes out of the loop.
After exiting the loop, the control goes to the statements which are immediately
after the loop.
The body of a loop can contain more than one statement. If it contains only one
statement, then the curly braces are not compulsory.
It is a good practice though to use the curly braces even we have a single
statement in the body.
While

#include <reg51.h> // Header file for 8051 microcontroller

sbit LED = P2^0; // Define LED connected to Port 2, Pin 0


sbit Button = P3^0; // Define Button connected to Port 3, Pin 0

void main() {
LED = 0; // Turn OFF LED initially
Button = 1; // Set Button as input (pull-up enabled)

while (1) { // Infinite loop


if (Button == 0) { // If button is pressed (active-low)
LED = 1; // Turn ON LED
} else {
LED = 0; // Turn OFF LED
}
}
}
Do While
A do...while loop in C is similar to the while loop except that the condition is always
executed after the body of a loop. It is also called an exit-controlled loop.
#include <reg51.h> // Header file for 8051 microcontroller

sbit LED = P2^0; // Define LED connected to Port 2, Pin 0

void delay() {
unsigned int i, j;
for (i = 0; i < 100; i++) {
for (j = 0; j < 100; j++); // Simple delay
}
}

void main() {
LED = 0; // Ensure LED is OFF initially

do {
LED = ~LED; // Toggle the LED state (ON/OFF)
delay(); // Add a delay
} while (1); // Infinite loop
}
For
Most efficient looping structureThe initial value of the for loop is performed only once.
The condition is a Boolean expression that tests and compares the counter to a fixed value after
each iteration, stopping the for loop when false is returned.
The incrementation/decrementation increases (or decreases) the counter by a set value.
For
#include <reg51.h> // 8051 register definitions

sbit LED = P2^0; // Define LED at Port 2, Pin 0

// Function for delay


void delay(unsigned int time) {
unsigned int i, j;
for (i = 0; i < time; i++) {
for (j = 0; j < 100; j++); // Nested loop creates delay
}
}

void main() { // Blink LED 5 times fast


while (1) { // Infinite loop for (int k = 0; k < 5; k++) {
LED = 1; // Turn ON LED
// Blink LED 5 times slowly delay(50); // Fast delay
for (int k = 0; k < 5; k++) { LED = 0; // Turn OFF LED
LED = 1; // Turn ON LED
delay(50); // Fast delay
delay(200); // Slow delay
}
LED = 0; // Turn OFF LED
}
delay(200); // Slow delay
}
}
Break - Continue
The break statement is used mainly in in the switch statement.
It is also useful for immediately stopping a loop.

When you want to skip to the next iteration but remain in the
loop, you should use the continue statement.
Loops
Which loop to Select?
Selection of a loop is always a tough task for a programmer, to
select a loop do the following steps:
Analyze the problem and check whether it requires a pre-test or a
post-test loop.
If pre-test is required, use a while or for a loop.
If post-test is required, use a do-while loop.
Switch-Case Statement
Switch statement in C tests the value of a variable and
compares it with multiple cases. Once the case match is found,
a block of statements associated with that particular case is
executed.
Each case in a block of a switch has a different name/number
which is referred to as an identifier. The value provided by the
user is compared with all the cases inside the switch block until
the match is found.
If a case match is NOT found, then the default statement is
executed, and the control goes out of the switch block.
Switch-Case Statement
Switch-Case Statement
Switch-Case Statement
#include <reg51.h> // 8051 register definitions
// Switch-case for LED behavior
sbit LED = P2^0; // Define LED at Port 2, Pin 0
switch (count) {
sbit Button = P3^0; // Define Button at Port 3, Pin 0 (Input)
case 0:
LED = 0; // LED OFF
void delay() {
break;
unsigned int i, j;
for (i = 0; i < 200; i++) {
case 1:
for (j = 0; j < 100; j++); // Simple delay
LED = 1; // LED ON
}
break;
}
case 2:
void main() {
for (int i = 0; i < 5; i++) { // Blink LED 5 times
unsigned char count = 0; // Counter for button presses
LED = 1;
Button = 1; // Set button as input (pull-up enabled)
delay();
LED = 0;
while (1) {
delay();
if (Button == 0) { // If button is pressed
}
delay(); // Debounce delay
break;
count++; // Increment count
}
}
if (count > 2) count = 0; // Reset count after 2
}
while (Button == 0); // Wait for button release
}
Why do we need Switch Case
There is one potential problem with the if-else statement which is the complexity
of the program increases whenever the number of alternative path increases. If you
use multiple if-else constructs in the program, a program might become difficult
to read and comprehend. Sometimes it may even confuse the developer who
himself wrote the program.
The solution to this problem is the switch statement.
Rules for switch statement:
An expression must always execute to a result.
Case labels must be constants and unique.
Case labels must end with a colon ( : ).
A break keyword must be present in each case.
There can be only one default label.
We can nest multiple switch statements.
Why do we need Switch Case
There is one potential problem with the if-else statement which is the complexity
of the program increases whenever the number of alternative path increases. If you
use multiple if-else constructs in the program, a program might become difficult
to read and comprehend. Sometimes it may even confuse the developer who
himself wrote the program.
The solution to this problem is the switch statement.
Rules for switch statement:
An expression must always execute to a result.
Case labels must be constants and unique.
Case labels must end with a colon ( : ).
A break keyword must be present in each case.
There can be only one default label.
We can nest multiple switch statements.
Practical 1
#include <reg51.h>.

unsigned int i;
void delay(void)
{
for (i = 0; i < 60000; i++)
{
}
}

void main()
{
P1 = 0x00;
while (1)
{
P1 = 0x00;
delay();

P1 = 0xFF;
delay();
P1 = 0x00;
delay();

}
}
Why writing good code is important....
Program 1.1
#include <reg51.h>

unsigned int delay_counter; // Renamed for better clarity

// Function to introduce delay


void delay(unsigned int time)
{
for (delay_counter = 0; delay_counter < time; delay_counter++)
{
// Wasting time for delay
}
}

void main()
{
P1 = 0x00; // Initialize Port 1 as LOW

while (1) // Infinite loop


{
P1 = 0x00; // Turn OFF all LEDs
delay(60000);

P1 = 0xFF; // Turn ON all LEDs


delay(60000);

P1 = 0x00; // Turn OFF again


delay(60000);
}
}
Program 2
#include <reg51.h>

void main (){


unsigned char x,y;
unsigned int i;

P1=0x00;
while(1){
x=0x01;
for(y=0;y<8;y++)
{P1=x;
for(i=0;i<40000;i++);
x=x<<1;
}}}
Program 2.1
#include <reg51.h>

#define DELAY_TIME 40000 // Define delay value for better readability

void delay(void)
{
unsigned int i;
for (i = 0; i < DELAY_TIME; i++); // Software delay
}

void main()
{
unsigned char ledState, shiftCount;

P1 = 0x00; // Initialize all LEDs OFF

while (1) // Infinite loop


{
ledState = 0x01; // Start with first LED ON

for (shiftCount = 0; shiftCount < 8; shiftCount++)


{
P1 = ledState; // Display LED pattern
delay(); // Wait before shifting
ledState <<= 1; // Shift LED to the left
}
}
}
Program 3

# include <reg51.h>
void main(void)
{unsigned char x;
unsigned int i;
char seg[16] = {0xC0,0xF9, 0xA4, 0xB0, 0x99, 0x92,
0x82, 0xF8, 0x80, 0x90, 0x88, 0x00, 0xC6, 0xC0,
0x86, 0x8E};
while(1)
{
for(x=0; x<16; x++)
{P1 = seg[x]; Common Cathode Display:
for(i=0; i<32000; i++); 0 (LOW) = Segment ON
1 (HIGH) = Segment OFF
}
}
}
Program 3
Hex Code Binary Equivalent Segments ON Displayed Character

0xC0 1100 0000 a, b, c, d, e, f 0

0xF9 1111 1001 b, c 1

0xA4 1010 0100 a, b, g, e, d 2

0xB0 1011 0000 a, b, c, d, g 3

0x99 1001 1001 b, c, f, g 4

0x92 1001 0010 a, f, g, c, d 5

0x82 1000 0010 a, f, e, d, c, g 6

0xF8 1111 1000 a, b, c 7

0x80 1000 0000 a, b, c, d, e, f, g 8

0x90 1001 0000 a, b, c, f, g 9

0x88 1000 1000 a, b, c, e, f, g A

All segments ON (used


0x00 0000 0000 for testing or blanking (Blank/Error)
out)

0xC6 1100 0110 a, d, e, f C

0xC0 1100 0000 a, b, c, d, e, f D

0x86 1000 0110 a, d, e, f, g E

0x8E 1000 1110 a, e, f, g F


2-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display
2-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display

Traffic Light LEDs


P2.0 → Red Light (Direction A)
P2.1 → Green Light (Direction A)
P2.2 → Red Light (Direction B)
P2.3 → Green Light (Direction B)
7-Segment Display (Common Cathode)
Connected to Port 1 (P1)
Uses predefined segment values for digits 9 to 0.
2-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display
#include <reg51.h>

// Define LED Pins for Traffic Lights


sbit RED_A = P2^0; // Red Light for Direction A
sbit GREEN_A = P2^1; // Green Light for Direction A
sbit RED_B = P2^2; // Red Light for Direction B
sbit GREEN_B = P2^3; // Green Light for Direction B

// 7-Segment Display Values for 9 to 0 (Common Cathode)


const unsigned char SEGMENT_VALUES[10] = {
0xC0, // 0
0xF9, // 1
0xA4, // 2
0xB0, // 3
0x99, // 4
0x92, // 5
0x82, // 6
0xF8, // 7
0x80, // 8
0x90 // 9
};
2-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display

/**
* @brief Generates a software delay for 1 second.
*/
void delay_1s(void) {
unsigned int i;
for (i = 0; i < 60000; i++); // Approximate 1-second delay
}

/**
* @brief Displays countdown on the 7-segment display from 9 to 0.
*/
void countdown(void) {
signed char digit;
for (digit = 9; digit >= 0; digit--) {
P1 = SEGMENT_VALUES[digit]; // Show number on 7-segment display
delay_1s(); // Wait for 1 second
}
}
2-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display
/**
* @brief Main function to control traffic lights.
*/
void main(void) {
P1 = 0xFF; // Initialize 7-segment display (OFF)
P2 = 0x00; // Initialize all traffic lights OFF

while (1) {
// Direction A Green, Direction B Red
GREEN_A = 1; // Turn on Green for Direction A
RED_A = 0; // Turn off Red for Direction A
RED_B = 1; // Turn on Red for Direction B
GREEN_B = 0; // Turn off Green for Direction B
countdown(); // Show 9-second countdown

// Switch to Direction B Green, Direction A Red


GREEN_A = 0; // Turn off Green for Direction A
RED_A = 1; // Turn on Red for Direction A
RED_B = 0; // Turn off Red for Direction B
GREEN_B = 1; // Turn on Green for Direction B
countdown(); // Show 9-second countdown
}
4-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display
4-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display

Traffic Light LEDs (Connected to Port 2 - P2)


P2.0 → Red Light (North)
P2.1 → Green Light (North)
P2.2 → Red Light (East)
P2.3 → Green Light (East)
P2.4 → Red Light (South)
P2.5 → Green Light (South)
P2.6 → Red Light (West)
P2.7 → Green Light (West)
7-Segment Display (Common Cathode)
Connected to Port 1 (P1)
Displays countdown from 9 to 0.
4-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display
#include <reg51.h>

// Define LED Pins for Traffic Lights


sbit RED_N = P2^0; // Red Light for North
sbit GREEN_N = P2^1; // Green Light for North
sbit RED_E = P2^2; // Red Light for East
sbit GREEN_E = P2^3; // Green Light for East
sbit RED_S = P2^4; // Red Light for South
sbit GREEN_S = P2^5; // Green Light for South
sbit RED_W = P2^6; // Red Light for West
sbit GREEN_W = P2^7; // Green Light for West

// 7-Segment Display Values for 9 to 0 (Common Cathode)


const unsigned char SEGMENT_VALUES[10] = {
0xC0, // 0
0xF9, // 1
0xA4, // 2
0xB0, // 3
0x99, // 4
0x92, // 5
0x82, // 6
0xF8, // 7
0x80, // 8
0x90 // 9
};
4-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display
/**
* @brief Generates a software delay for 1 second.
*/
void delay_1s(void) {
unsigned int i;
for (i = 0; i < 60000; i++); // Approximate 1-second delay
}

/**
* @brief Displays countdown on the 7-segment display from 9 to 0.
*/
void countdown(void) {
signed char digit;
for (digit = 9; digit >= 0; digit--) {
P1 = SEGMENT_VALUES[digit]; // Show number on 7-segment display
delay_1s(); // Wait for 1 second
}
}
4-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display
/**
* @brief Turns off all green lights and turns all red lights ON.
*/
void all_red(void) {
RED_N = 1; GREEN_N = 0;
RED_E = 1; GREEN_E = 0;
RED_S = 1; GREEN_S = 0;
RED_W = 1; GREEN_W = 0;
}
4-Way Traffic Light System with 9-Second
Countdown using 8051 & 7-Segment Display

void main(void) {
P1 = 0xFF; // Initialize 7-segment display (OFF)
P2 = 0xFF; // Initialize all Red lights ON (Traffic stopped)

while (1) {
// North Green, Others Red
all_red();
GREEN_N = 1; RED_N = 0; // North gets Green
countdown();

// East Green, Others Red


all_red();
GREEN_E = 1; RED_E = 0; // East gets Green
countdown();

// South Green, Others Red


all_red();
GREEN_S = 1; RED_S = 0; // South gets Green
countdown();

// West Green, Others Red


all_red();
GREEN_W = 1; RED_W = 0; // West gets Green
countdown();
}
}

You might also like