ES Assignment 2
ES Assignment 2
Microprocessor Micro-controller
Microprocessors can be understood as the Micro-controllers can be understood as the
heart of a computer system. heart of an embedded system.
Microprocessors can’t be used in compact Micro-controllers can be used with a
system. compact system.
Microprocessors have less number of Micro-controllers have more number of
registers. registers.
Microprocessors are generally used in Micro-controllers are generally used in
personal computers. washing machines, and air conditioners.
Microprocessors are not efficient and its Microcontrollers are efficient and its power
power consumption is high. consumption is low.
4 general-purpose 16 general-purpose
Registers 32 general-purpose registers registers (some models registers (some models
have more) have more)
Typically up to 20 MHz (some Typically up to 12 MHz Typically up to 64 MHz or
Clock Speed models higher) (varies by model) more (varies by model)
Power Low power consumption Moderate power Low power consumption
Consumption with multiple power-saving consumption, with some with multiple power-
Feature AVR Microcontrollers 8051 Microcontrollers PIC Microcontrollers
modes low-power modes saving modes
Internal oscillator or external Typically uses external Internal oscillator or
Clock Source crystal crystals or oscillators external crystal
Fewer I/O ports compared Typically fewer I/O ports
I/O Ports More I/O ports integrated
to AVR than AVR
Typically low cost,
Typically low cost, especially Cost varies by model but
Cost in lower-end models
especially for basic
generally low to moderate
versions
Popular in embedded
Popular for embedded Older, widely used in
Popularity systems and Arduino projects industrial control systems
systems and automotive
applications
Programming C, Assembly, Arduino (for Assembly, C, and other
C, Assembly
Language beginners) high-level languages
Available in a wide range of Available in a wide range
Limited scalability
Scalability models for different
compared to AVR and PIC
of models for different
applications applications
o DDRx register
o PORTx register
o PINx register
DDRx register:- Data Direction Register configures the data direction of port pins. These
registers are used for determining whether port pins will be used for input or output. On writing
1 to a bit in DDRx makes corresponding port pin as output, while writing 0 to a bit in DDRx makes
corresponding port pin as input.For example:-
For making lower nibble of port B as output and higher nibble as input:
DDRB=0b00001111;
PORTx register:- In general PORTx register can be used for two purposes:
A. To output data: when port is configured as output then PORTx register is used. When we set bits in
DDRx to 1, corresponding pins becomes output pins. Now we can write the data into respective bits in
PORTx register. This will immediately change the output state of pins according to data we have
written on the ports.For example:
B. To activate/deactivate pull up resistors: when port is configured as input we set the bits in DDRx
to 0, i.e. make port pins as inputs the corresponding bits in PORTx registers used to
activate/deactivate pull-up registers associated with that pin. In order for activating pull-up resistor,
set the bit in PORTx register to 1, and for deactivating (i.e. to make port as tri stated) set it to zero.
In input mode, when pull-up is enabled, default state of the pin is '1'. So if we don't add anything to
pin and if we try to read it then it will read as 1.
Note: While using on chip Analog to Digital Converter (ADC), ADC port pins must be used as
tri stated input.
For example:
To make lower nibble of port A as output, higher nibble as input with pull-ups enabled
PINx register:- PINx register used to read the data from port pins. In order to read the data from
port pin, first we have to change the port?s data direction to input. This is done by setting bits in
DDRx to zero. If port is made output, then reading PINx register will give a data that has been output
on port pins.
There are two input modes. Either we can use port pins as internal pull up or as tri stated inputs. It
will be explained as shown below:
Pipelining Concept
Stages in Pipelining:
1. Fetch: The CPU retrieves the next instruction from the program memory.
2. Decode: The fetched instruction is decoded to determine what operation needs to
be performed.
3. Execute: The CPU performs the operation, including arithmetic, logical, or data
movement tasks.
Parallel Execution:
1. In a pipelined system, while one instruction is being executed, the next instruction is
fetched and decoded simultaneously.
2. For AVR, this overlap is possible because of its Harvard architecture, which
separates the program memory (for instructions) and data memory (for operands).
Single Clock Cycle Execution:
1. Most instructions in AVR execute in a single clock cycle due to pipelining. While one
instruction is being executed, the next instruction is being prepared, ensuring no
idle CPU cycles.
1.Pipelining ensures that the CPU is always doing useful work, reducing the overall instruction
execution time.
2.The ability to execute most instructions in a single clock cycle makes AVR microcontrollers faster
and more efficient than non-pipelined architectures(improving performance).
3.By overlapping stages, the time required to execute multiple instructions is significantly reduced
compared to sequential processing(result in reduced latency).
4.Real-time embedded systems benefit greatly from pipelining, as it ensures consistent and
predictable instruction execution timing.
Summary
Pipelining in AVR architecture enables parallel instruction processing by overlapping fetch, decode,
and execute stages. This results in faster and more efficient execution, making AVR microcontrollers
ideal for high-speed and real-time applications. The single clock cycle execution of most instructions is
a direct result of its effective pipelining mechanism.
1. TinyAVR
Features:-
Applications:-
2. MegaAVR
Features:-
Applications:
3. XMEGA AVR
Features:-
Applications:
Features:-
Comparison Summary:
Conclusion
Each type of AVR micro-controller is designed with specific use cases in mind,
ranging from basic applications with low power requirements to high-performance
real-time systems. Selecting the right AVR micro-controller depends on the
application's complexity, processing requirements, and peripheral needs.
Examples of RISC processors are SUN's SPARC, PowerPC, Microchip PIC processors, RISC-V.
=>AVR micro-controllers are based on the RISC (Reduced Instruction Set Computer) architecture,
which offers several advantages that enhance the performance, efficiency, and usability of these
micro-controllers. Below are the key benefits:
1.RISC architecture provides a simple and efficient set of instructions, reducing complexity in
execution.
2.The RISC design reduces the need for complex hardware, making AVR micro-controllers cost-
effective and energy-efficient.
3.RISC architecture minimizes code size, allowing efficient memory usage in AVR micro-controllers.
4.RISC-based AVR micro-controllers consume less power, making them ideal for battery-powered
devices.
5.RISC architecture allows pipelining, enabling overlapping of instruction execution stages and
improving processing speed in AVR.
6.The speed and efficiency of RISC architecture improve real-time performance in AVR systems.
Conclusion
The RISC architecture in AVR micro-controllers provides speed, efficiency, and simplicity, making them
well-suited for a wide range of embedded systems. Its ability to deliver high performance with low
power consumption and reduced design complexity is a significant advantage for developers.
1. Purpose: EEPROM provides non-volatile memory for storing data that must be
preserved even when power is removed.
2. Characteristics:
1. Data can be written, erased, and re-written electrically.
2. Limited write/erase cycles (typically around 100,000 cycles).
3. Usage:
4. Purpose: Flash memory is used to store the main program code in AVR micro-
controllers.
5. Characteristics:
6. Usage:
Summary Table
Each of these components plays a crucial role in the operation and functionality of
AVR micro-controllers, making them versatile for various applications.
Function:
Store temporary data and intermediate results during program execution.
Directly connected to the Arithmetic Logic Unit (ALU), enabling fast data manipulation.
Used for arithmetic, logical, and data transfer operations.
Characteristics:
Function:-
o Performs arithmetic operations (e.g., addition, subtraction) and logical operations
(e.g., AND, OR, NOT).
o Supports bitwise operations and shift operations.
o Handles operations between the general-purpose registers and immediate data.
Characteristics:
o Operates in coordination with the RISC architecture, ensuring most operations are
completed in a single clock cycle.
C. Program Counter:-
Function:-
Tracks the address of the next instruction to be executed in the program memory (Flash).
Ensures sequential execution of instructions unless altered by control flow instructions (e.g.,
jumps, calls, interrupts).
Characteristics:-
D. Watchdog Timer:-
Function:-
o Acts as a safety feature to prevent the system from hanging or freezing.
o Automatically resets the microcontroller if the software fails to reset the timer
within a specified period.
Characteristics:-
1. Harvard architecture separates program memory (Flash) and data memory (SRAM), enabling
simultaneous access to both.
2. Instructions can be fetched from program memory while data is accessed from data memory,
enhancing execution speed.
3. Enables instruction-level pipelining, where the next instruction is fetched while the current
instruction is executed, improving overall performance.
4. he separation of memories ensures efficient usage of storage resources, reducing contention
between program and data access.
5. The architecture simplifies memory access logic, resulting in a more straightforward and reliable
design.
6. Parallel access to program and data memory reduces delays, especially in real-time applications.
7. Faster execution due to reduced memory contention leads to lower power consumption, which is
vital for battery-powered devices.
AVR micro-controllers have general-purpose I/O (GPIO) ports that the CPU uses to
communicate with external devices. Data can be written to or read from GPIO pins by
manipulating the PORTx, PINx, and DDRx registers.
Memory-Mapped I/O:
AVR uses memory-mapped I/O, where peripheral registers (e.g., for UART, SPI,
Timer/Counter) are assigned specific memory addresses. The CPU interacts with peripherals
by reading or writing to these memory locations.
Polling:
The CPU continuously checks the status of peripheral flags (e.g., a transmit buffer empty flag)
to determine when to transfer data.
Example: UART data transmission by monitoring the UDRE (USART Data Register Empty) flag.
Process Flow
This step involves setting up peripheral control registers (e.g., enabling UART, SPI, or ADC, configuring
baud rates, etc.).
·Data transfer occurs through one of the above methods, depending on the peripheral type.
Data can be transferred via polling, interrupts, or serial communication protocols, as per the
peripheral's mechanism.
·Flags and interrupts ensure synchronization between the CPU and peripherals.
Flags indicate the status (e.g., buffer empty, data received), while interrupts allow peripherals to
notify the CPU about data readiness without constant polling.
Parameters C Embedded C
Embedded C programming plays a key role in performing specific function by the processor. In day-to-
day life we used many electronic devices such as mobile phone, washing machine, digital camera, etc.
These all device working is based on micro-controller that are programmed by embedded C.
In embedded system programming C code is preferred over other language. Due to the following
reasons:
o Easy to understand
o High Reliability
o Portability
o Scalability
Easy to Understand
Embedded C is derived from the standard C language, making it easy to learn for those
already familiar with C. Its syntax and structure are simple, which reduces the learning
curve.
High Reliability
Portability
Scalability
Embedded C is scalable to various levels of embedded systems, from simple 8-bit micro-
controllers to advanced 32-bit or 64-bit processors.
Example:-
#define LED_PIN PB0 // Define the LED pin (connected to Port B, Pin 0).
int main(void) {
DDRB |= (1 << LED_PIN); // Set LED_PIN (PB0) as output by setting the corresponding bit in DDRB register.
while (1) {
PORTB |= (1 << LED_PIN); // Turn on LED by setting the LED_PIN bit in PORTB register.
_delay_ms(500); // Wait for 500 milliseconds.
PORTB &= ~(1 << LED_PIN); // Turn off LED by clearing the LED_PIN bit in PORTB register.
_delay_ms(500); // Wait for 500 milliseconds.
}
return 0; // Return 0 (this is just a formality in embedded systems, as main typically runs indefinitely).
}
14. List the data types commonly used in Embedded C. How are they
different from standard C data types?
=>Commonly used data types in Embedded C are:-
Fixed-width integer types are essential in embedded systems due to their predictable size,
which is crucial for memory management and interfacing with hardware registers.
2. Volatile Keyword
The volatile keyword is vital in embedded systems for variables that can be changed by
hardware interrupts or other asynchronous processes. It prevents the compiler from
optimizing away necessary reads and writes.
Using volatile ensures that every read from statusRegister fetches the actual value from the
hardware register, not a cached value.
3. Bit-Fields
Bit-fields are used in embedded systems to pack multiple variables into a single byte or word,
which is useful for manipulating hardware registers and flags.
This struct allows efficient manipulation of individual bits within an 8-bit register, saving
memory and processing time.
4. Enumerations
Enumerations enhance code readability and maintainability, providing a way to define a set of
named integer constants.
5. Floating-Point Types
While not as common in embedded systems due to their computational cost, floating-point
types are sometimes necessary for specific applications like sensor data processing.
7. Pointers
Pointers are fundamental in embedded systems for direct memory access, handling dynamic
memory, and interacting with hardware registers. They provide flexibility but require careful
handling to avoid issues like memory leaks and buffer overflows.
=>Choosing the right data types in embedded C programming is crucial for optimizing
performance, memory usage, and interfacing with hardware. By understanding and leveraging
fixed-width integers, the volatile keyword, bit-fields, enumerations, floating-point types,
advanced programmers can write more efficient and reliable embedded software.
Embedded C data types differ from standard C data types primarily due to the
unique requirements and constraints of embedded systems. Here’s how they are
different:
1. Memory Constraints:
Embedded C: Data types in embedded systems are often optimized for memory usage. For
example, the use of fixed-width integer types (such as int8_t, int16_t, etc.) ensures
that variables occupy a known, specific amount of memory, which is crucial in memory-
constrained environments.
Standard C: While standard C provides flexibility in data type sizes (e.g., int, float, char),
it doesn't necessarily prioritize minimizing memory usage, especially in general-purpose
applications where memory is less of a constraint.
Embedded C: In embedded systems, using fixed-width integer types like int8_t, int16_t,
and uint32_t is crucial for precise control over memory and data representation. These
types are defined in <stdint.h> to ensure consistency across different platforms and
compilers.
Standard C: Standard C allows for general integer types (int, long, etc.), which can vary in
size depending on the compiler and platform. This variability can cause issues in embedded
systems where exact memory usage is critical.
3. Volatile Keyword:
4. Bit-Fields:
Embedded C: Bit-fields are commonly used in embedded C to pack multiple values into a
single byte or word, enabling efficient manipulation of hardware registers. This is essential
for controlling hardware and working with peripheral registers.
Standard C: Bit-fields are supported in standard C, but they are less common because they
are not typically required for general-purpose application development. Standard C doesn't
usually need to optimize for hardware-specific bit-level manipulations.
5. Floating-Point Types:
Embedded C: Floating-point types (e.g., float, double) are often avoided in embedded
systems because they are computationally expensive and require more memory and
processing power, which are limited in embedded systems.
Standard C: Floating-point types are commonly used in standard C for applications that
require decimal calculations, and performance or memory usage is not as critical.
6. Pointers:
Embedded C: Pointers in embedded C are used for direct memory access to hardware
registers and manipulating data in specific memory-mapped locations. They are essential for
efficient hardware control but require careful handling to avoid memory corruption, buffer
overflows, and other issues.
7. OS Independence:
8. Compiler-Specific Extensions:
Conclusion:
Embedded C data types are designed with a focus on efficient use of memory,
precise control over hardware, and the constraints of embedded systems (such as
low power, real-time processing, and limited resources). In contrast, standard C data
types are more generalized, with flexibility for general-purpose programming on
systems where hardware-specific optimizations are less of a concern.
By using data types such as fixed-width integers, volatile, and bit-fields, embedded C
ensures the program behaves as expected while interacting with hardware in a
resource-constrained environment.
Header files define hardware-specific constants, macros, and functions that abstract the
interaction with micro-controller registers, peripherals, and hardware features.
They provide definitions for pin configurations, memory-mapped registers, interrupt
vectors, and other hardware-related settings. These abstractions help make the code
portable and easier to manage across different microcontrollers.
2. Simplification of Code
Instead of repeating definitions and declarations throughout the source files, header files
allow these to be placed in a single location, making the code modular and more
manageable.
By including the header files, the main code is cleaner, shorter, and easier to understand.
3. Function Prototypes
Header files typically contain function prototypes, so the compiler knows the functions’
signatures before they are used in the main program. This enables the use of functions
defined in separate files.
In embedded systems, this is particularly useful for organizing the program into logical blocks,
such as separating hardware interaction code, algorithms, and application code.
7. Platform-Specific Code
Header files are used to separate platform-specific code from application logic. For example,
in embedded systems, different microcontrollers or hardware platforms may require specific
initialization code or register manipulation.
Platform-specific header files allow the main code to remain portable while providing the
necessary functionality for each microcontroller.
8. Conditional Compilation
Header files can include conditional compilation statements (using #ifdef, #ifndef, etc.)
to manage different hardware configurations, features, or platform-specific code. This is
useful when working with different versions of hardware or peripherals.
Example: Including different code blocks based on whether the device has an onboard ADC
or external ADC.
Example:-
// example_header.h
#ifndef EXAMPLE_HEADER_H
#define EXAMPLE_HEADER_H
#define LED_PIN 5 // Macro for LED pin.
// Function Prototypes.
void init_uart(void);
#endif // EXAMPLE_HEADER_H.
#include "example_header.h"
int main() {
// Initialize UART with defined baud rate.
init_uart();
while(1) {
// Main loop.
}
}
Conclusion:
Header files in embedded programming are crucial for organizing code, abstracting
hardware, improving modularity, and ensuring that hardware-specific configurations
and functions are clearly defined and easy to manage. They significantly improve
code readability, reusability, and maintainability, making embedded system
development more efficient.
while(1) {
if(PIND & (1 << 1)) { // Check if button is pressed.
PORTB |= (1 << 0); // Turn ON LED.
} else {
PORTB &= ~(1 << 0); // Turn OFF LED.
}
}
return 0;
}
Explanation:
2. switch-case Statement
The switch-case structure is used when there are multiple conditions to evaluate. It
is more efficient and readable than a series of if-else statements for scenarios with
several choices.
default: // Stop.
PORTB = 0b00000000;
break;
}
}
int main(void) {
DDRB = 0xFF; // Configure PORTB as output.
char command = 'F'; // Example input command.
while(1) {
// Infinite loop.
}
return 0;
}
Explanation:
Conclusion:
1. Compiler
The compiler translates the high-level Embedded C code into machine code (binary
format) that the micro-controller can execute.
Key Roles:
1. Translation: Converts C source code into assembly or machine code understandable by the
micro-controller.
2. Optimization: Optimizes the code for speed, memory usage, and performance in embedded
systems.
3. Error Checking: Detects and reports syntax errors, missing semicolons, undeclared variables,
etc.
4. Platform-Specific Code Generation: Generates code compatible with the target micro-
controller architecture.
Example:
PORTB = 0xFF;
2. Linker
The linker combines multiple object files (.o) and libraries into a single executable
file (.hex or .bin) suitable for the micro-controller.
Key Roles:
Example:
Combines the main source file (main.o) with external libraries like libmath.a into a single
output.hex file.
3. Debugger
The debugger is used to test, analyze, and debug the program running on the micro-
controller.
Key Roles:
Conclusion:
C.It is useful for embedded computers which are with limited computing resources.
D.To compile for a platform where it is not practical to do the compiling, a cross-
compiler is used.
E.When direct compilation on the target platform is not infeasible, so we can use the
cross compiler.
F.It helps to keep the target environment separate from the built environment.
Features of Cross-Assembler :
B.Cross-assemblers are also used to develop program which will run on game
console and other small electronic system which are not able to run development
environment on their own.
3.Debuggers:- A debugger is a tool that allows you to examine the state of a running
program. Debugging is the process of locating and then removing bugs or errors in a program. An interactive
debugging system gives programmers tools to help them test and debug their programs. Debugging is the
methodical process of locating and eliminating bugs or defects in a computer program.
Types of Debuggers:
Static debugger: A static debugger does not rely on any specific software. The debugging can be
completed by the user.
Dynamic debugger: A dynamic debugger can be either software or hardware. There are several
types of dynamic debuggers, including the following:
o Breakpoint Debugger: Adding conditional and unconditional breakpoints to the program at
various points
o Kernel Debugger: To debug the operating system, a debugger with kernel debugging
capabilities is provided.
o Meta Debugger: Debugger includes debugging and meta-debugging features.
o Debugger with the same process: The debugger and debuggee processes are identical, and
they both share the main memory. This type of debugger is simple and straightforward to
implement. This debugger executes more quickly.
Code Uploading: Loads executable files into the target device's Flash memory.
Communication Protocols: Uses protocols like UART, SPI, I2C, or JTAG for data transfer.
Programming Interface: Often combined with debugging tools for seamless code uploading
and testing.
Bootloader Support: Works with bootloaders to facilitate easy updates without external
hardware programmers.
Examples:
o AVRDUDE for AVR microcontrollers.
o ST-Link for STM32 devices.
Importance:
1. Over time, dynamic allocation can lead to memory fragmentation, where free memory is
scattered in small, non-contiguous blocks, making it difficult to allocate large contiguous blocks of
memory.
2. Improper management of dynamically allocated memory can result in memory leaks, where
memory that is no longer needed is not released back to the system, gradually reducing available
memory.
3. In real-time systems, dynamic memory allocation can introduce unpredictable latencies due to
variable allocation and deallocation times, potentially violating timing constraints.
4. Embedded systems often have limited memory resources, making it essential to carefully plan
and manage memory allocation to avoid running out of memory.
5. In multi-threaded environments, dynamic memory allocation must be thread-safe to prevent race
conditions and data corruption.
21. Explain the different types of memory available in AVR micro-
controllers.
Program Memory
Data Memory
EEPROM
Program Memory
Program Memory, also referred to as flash, is where your code is stored. Depending on settings in the
fuse bits, the entire flash memory can be used as application storage or a portion can be code-
blocked off for a bootloader program.
Flash memory is non-volatile meaning its data does not go away when the micro-controller loses
power. Flash cannot be accessed as quickly as Data Memory and individual bytes cannot be modified
at a time so it is not a good place to store variables which constantly change. However, in addition to
storing your application code, it is a good place to put constants like lookup tables or strings.
Data Memory
Data Memory is composed of four parts:
Register File
I/O Registers
Extended I/O Registers
Internal SRAM
Unlike flash, Data Memory is not composed of a single memory type. Rather, it is a contiguous
mapping of addresses across multiple memory types.
The breakdown of data memory is shown below. The location and size of the general purpose
working registers, I/O registers, and extended I/O registers are the same across all chips (even if some
of the extended I/O features are not implemented). However, the size of internal SRAM varies
between different models.
EEPROM
EEPROM is another non-volatile storage location in the AVR architecture. Unlike flash, individual bytes
may be written to it, although its access time is much slower. EEPROM is best served for configuration
settings, i.e. things that need to be available at startup but may be changed at runtime and used the
next time the chip starts up.
=>In AVR micro-controllers, memory is divided into three types: Program Memory
(Flash), Data Memory (SRAM), and EEPROM. Embedded C programs manage
memory using variables, pointers, and specific functions provided by AVR libraries.
Example Code for Memory Management
Hardware Interfacing:
1. The code interacts with PORTB to toggle an LED based on EEPROM values,
showcasing direct hardware manipulation.
Key Takeaways:
23. What are the difference between stack and heap memory in an
embedded system?
=>Note:-This code is valid only if your embedded system support standard C libraries
and also support function like malloc() and free(). And here we are writing it in C
because we are assuming our embedded system fullfill this criteria.
25. How can you optimize memory usage in systems with limited SRAM?
· Use smaller data types (e.g., uint8_t instead of int) to reduce memory usage.
· Keep the stack size small and avoid deep recursion, as the stack consumes SRAM.
· Use bit-fields and structures to store multiple variables in a single memory location.
· Limit the use of global variables, as they consume SRAM throughout the program's
life.
· Enable compiler optimization flags to reduce memory usage, such as -Os for size
optimization.
By implementing these strategies, you can make efficient use of limited SRAM in
embedded systems.
Note:-Embedded system typically have less SRAM compared to the general system.
=>The Interrupt Vector Table (IVT) in AVR micro-controllers plays a critical role in
the interrupt handling process. Its key roles are:
1. The IVT holds the memory addresses of all Interrupt Service Routines (ISRs) for
each interrupt source.
2. When an interrupt occurs, the micro-controller uses the IVT to find the address of
the corresponding ISR.
3. The IVT ensures that the micro-controller knows exactly where to jump to
execute the ISR based on the interrupt that triggered.
4. The position of interrupt entries in the IVT determines their priority, with lower
addresses having higher priority.
In short, the IVT stores and organizes the memory addresses of ISRs, ensuring
efficient and prioritized interrupt handling.
=> Steps for configuring and enabling an interrupt in AVR microcontrollers are:-
· Include header files: Add the avr/io.h and avr/interrupt.h header files to your
program to use interrupt functionality.
· Set the Global Interrupt Enable bit: Set the I bit in the SREG register to enable
global interrupts. You can use the sei() macro (in WinAVR) or the sei instruction in
assembly to enable interrupts globally.
· Enable individual interrupt bits: Enable the specific interrupt bits in the
peripheral's control register (e.g., enabling the Timer overflow interrupt bit in the
TIFR register).
· Provide an interrupt service routine (ISR): Write the ISR to define how the
program should handle the interrupt. The ISR must match the correct syntax and
naming convention.
· Configure the peripheral: Configure the peripheral (e.g., timer, ADC) to generate
the interrupt event, such as setting the timer to overflow after a certain period.
· Ensure conditions for interruption are met: Make sure the conditions for the
interrupt (e.g., timer overflow, ADC conversion completion) are satisfied so that the
interrupt is triggered.
· Disable interrupts (optional): If necessary, you can use the cli() macro to clear the
global interrupt enable bit and disable interrupts.
=>An interrupt mask is a settable / resettable register within the CPU which
determines whether a particular external interrupt will be passed to the internal
control circuitry or not.
The Global Interrupt Enable (I) bit in the Status Register (SREG) acts as the master switch for
interrupts.
Setting this bit (sei() instruction in C or SEI instruction in assembly) allows interrupts to
be processed by the AVR core.
If the I bit is cleared (cli() in C or CLI instruction in assembly), all interrupts are disabled,
regardless of individual interrupt masks.
Each peripheral (e.g., Timer, ADC, UART) has an Interrupt Enable (IE) bit in its respective
control register.
These bits control whether specific interrupts from that peripheral can trigger the interrupt
vector.
For example:
o The Timer Overflow Interrupt Enable bit (TOIE0) in the TIMER0 control register
(TCCR0) enables the timer overflow interrupt.
o The ADC Interrupt Enable bit (ADIE) in the ADC control and status register
(ADCSRA) enables the ADC conversion complete interrupt.
Setting the interrupt enable bit in the respective peripheral register allows the interrupt from
that peripheral to be processed, provided that the global interrupt flag is set.
Each interrupt source has a corresponding interrupt flag (IF) in its status register that is set
when the interrupt condition occurs (e.g., a timer overflow or ADC conversion complete).
The interrupt enable bits in the control registers allow the corresponding interrupts to be
triggered when their respective flags are set.
The interrupt mask in the control registers can be used to disable individual interrupts from
being triggered, even if the interrupt flag is set.
4. Masking Interrupts for Prioritization or Exclusion
You can mask interrupts by clearing the corresponding interrupt enable bit in the
peripheral’s register. This ensures that the interrupt won't trigger the ISR, even if the
interrupt flag is set.
Example: If you want to temporarily disable the ADC interrupt while performing some critical
operation, you can mask the ADC interrupt.
Interrupt Polling
Interrupt can take place at any Whereas CPU steadily ballots the device at
time. regular or proper interval.
In interrupt, interrupt request line While in polling, Command ready bit is used
is used as indication for indicating as indication for indicating that device
that device requires servicing. requires servicing.
32. How are Input and output ports configured in AVR micro-
controllers?
To configure a pin as an output, set the corresponding bit in the Data Direction Register
(DDR) to 1.
Once configured as an output, the value of the pin is controlled using the PORT register.
o PORTx (where x is the port number, such as PORTB, PORTC, etc.) is used to write a
logic 1 (high) or 0 (low) to the pin.
Example:-
To configure a pin as an input, set the corresponding bit in the Data Direction Register (DDR)
to 0.
The input pin value can be read using the PIN register.
o PINx (where x is the port number) is used to read the value of the input pin.
Additionally, the PORT register can be used to enable internal pull-up resistors if the pin is
configured as input (this is useful when the external circuit is not providing a signal).
Example:-
o PINx & (1 << Px); (This reads the input value of the pin)
Example configuration:-
Summary of Registers:
DDRx: Data Direction Register for Port x. Configures the direction (input or output).
PORTx: Port Data Register for Port x. Used to write output values or enable internal pull-ups
for inputs.
PINx: Pin Input Register for Port x. Used to read the current state of input pins.
This configuration allows flexible control of the pins for various tasks like controlling
LEDs, reading switches, etc., in embedded systems.
Program
1. Write an AVR program in C to toggle a bit of a specific port using
bitwise operation.
Explanation:-
2.Write a simple Embedded C program to blink an LED connected to
PORTB pin 0 of an AVR micro-controller.
Explanation:-
3.WAP to turn on an LED when a button connected to PD2 is pressed.
Explanation:-
6.Write an AVR program in C to generate a square wave using
Timer0,Timer1,and Timer2 in an AVR micro-controller.
Explanation:-
9.Write a program using a pointer to manipulate the value of port
register in AVR.
Explanation:-
10.Write a simple Embedded C program to blink an LED connected to an
AVR micro-controller.