Microcontrollers and Applications - Unit 1 and 2 Notes
Microcontrollers and Applications - Unit 1 and 2 Notes
AND APPLICATIONS
Hrishikesh Kamat
COEP Technical University
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.
Key Characteristics
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?
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
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
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
Applications:
Machine Code Representation: Hexadecimal simplifies writing and reading opcodes in assembly language.
Color Codes in Displays: Commonly used to define colors in HTML/CSS and graphical interfaces.
.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
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
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
Ensure both numbers have the same number of bits. If necessary, add leading zeros
Example
Ensure both numbers have the same number of bits. If necessary, add leading zeros
Example
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
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
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
Instruction Set Small, focuses on essential operations Extensive, includes specialized instructions
Execution Single-cycle execution for most instructions Multi-cycle execution for complex operations
Memory Access Access only via load/store instructions Instructions often directly access memory
Advantages Faster execution, low power, simplicity Versatility, fewer instructions for tasks
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.
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
Important Conversion
8 Bit microcontrollers
Memory Support Limited (<64 KB) Moderate (<512 KB) High (>1 MB)
Applications Simple IoT, Automation Industrial IoT, Motor Control Advanced IoT, Automotive
2.5
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.
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
8051 MICROCONTROLLER
8051 Architecture
Salient Features
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
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 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
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
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)
Every instruction consists of: MOV A, #50H ; Move immediate value 50H into accumulator A
SUBB Subtract
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
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.
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.
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.
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).
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
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
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
int main() {
int marks = 75; // Example input: marks obtained by a student
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
#include <stdio.h>
int main() {
int i = 1; // Initialize 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
void main() {
LED = 0; // Turn OFF LED initially
Button = 1; // Set Button as input (pull-up enabled)
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
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>
void main()
{
P1 = 0x00; // Initialize Port 1 as LOW
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>
void delay(void)
{
unsigned int i;
for (i = 0; i < DELAY_TIME; i++); // Software delay
}
void main()
{
unsigned char ledState, shiftCount;
# 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
/**
* @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
/**
* @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();