0% found this document useful (0 votes)
19 views18 pages

Unit Ii

The document covers Embedded C programming, focusing on memory and I/O interfacing, including types of memory, control signals, and interfacing techniques. It also discusses Real-Time Operating Systems (RTOS), their characteristics, types, and the importance of multitasking and real-time responsiveness in embedded systems. Additionally, it highlights context switching, task scheduling, and priority scheduling policies in RTOS, emphasizing the need for efficient resource management and deterministic behavior.

Uploaded by

learner22032000
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)
19 views18 pages

Unit Ii

The document covers Embedded C programming, focusing on memory and I/O interfacing, including types of memory, control signals, and interfacing techniques. It also discusses Real-Time Operating Systems (RTOS), their characteristics, types, and the importance of multitasking and real-time responsiveness in embedded systems. Additionally, it highlights context switching, task scheduling, and priority scheduling policies in RTOS, emphasizing the need for efficient resource management and deterministic behavior.

Uploaded by

learner22032000
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/ 18

UNIT 2 – EMBEDDED C PROGRAMMING

EMBEDDED C PROGRAMMING
Memory Interfacing and I/O Interfacing (Pointwise Notes)

1. Embedded C Basics
• Extension of C language with hardware access.
• Used for programming microcontrollers and embedded systems.
• Requires:
o #include <reg51.h> for 8051 microcontroller
o Bit-addressing, delay functions, port access

2. Memory Interfacing
Purpose:

To connect external RAM, ROM, or Flash to microcontroller to increase storage.

Types of Memory:

• ROM – Stores firmware


• RAM – Temporary data storage
• EEPROM/Flash – Non-volatile rewritable storage

Control Signals:

Signal Description
CS Chip Select
RD Read Enable
WR Write Enable
ALE Address Latch Enable

Address Bus:

• Carries memory address


• Example: 8051 has 16-bit address bus → 64KB memory
Interfacing ROM Example (8051):
#include <reg51.h>
unsigned char xdata *rom_ptr = (unsigned char xdata *) 0x8000;
unsigned char data;
void main() {
data = *rom_ptr; // Read from ROM at 0x8000
}

3. I/O Interfacing
Purpose:

To connect and control external input/output devices like sensors, switches, LEDs,
displays, etc.

I/O Ports in 8051:

Port Pins Direction


P0 0–7 Bidirectional (needs pull-up)
P1 8–15 Bidirectional
P2 16–23 Bidirectional
P3 24–31 Alternate Functions (INT, RXD, TXD, etc.)

Input Device (e.g., switch):


#include <reg51.h>
sbit switch1 = P1^0;
sbit led = P1^1;
void main() {
while (1) {
if (switch1 == 0) // Active low
led = 1; // Turn ON LED
else
led = 0; // Turn OFF LED
}
}

Output Device (e.g., LED):


#include <reg51.h>
void main() {
while (1) {
P1 = 0xFF; // Turn ON all LEDs
}
}

4. Memory-Mapped I/O vs Isolated I/O


Feature Memory-Mapped I/O Isolated I/O
Address space Shared with memory Separate address space
Instructions Normal read/write Special IN, OUT instructions
Speed Fast Comparatively slower

5. Interfacing Techniques
Polling:

• CPU keeps checking device status


• Simple but wastes CPU time

Interrupt:

• Device interrupts CPU when ready


• Efficient and responsive

DMA (Direct Memory Access):

• Transfers data between memory and I/O without CPU

6. Challenges in Memory & I/O Interfacing


• Address decoding complexity
• Timing mismatch
• Power and signal noise
• Data integrity and buffering

Programming Embedded Systems in C

1. Why C for Embedded Systems?


• Close to hardware (low-level).
• Easy to port and maintain.
• Fast and efficient.
• Supported by all microcontroller compilers.
2. Features of Embedded C
• Direct access to memory-mapped hardware.
• Bit-level and port-level manipulation.
• No standard library dependencies.
• Use of special keywords: sbit, xdata, idata, etc.

3. Typical Embedded C Program Structure


#include <reg51.h> // Header for 8051 MCU

void main() {
// Initialization
// Infinite loop
while (1) {
// Main logic
}
}

4. Common Header Files


Header Use
<reg51.h> Registers and ports for 8051 MCU
<intrins.h> Intrinsic functions like NOP()
<absacc.h> Absolute memory access

5. Data Types
Data Type Description Size in 8051
char Signed 8-bit 1 byte
unsigned char Unsigned 8-bit 1 byte
int Signed 16-bit 2 bytes
long Signed 32-bit 4 bytes
bit 1-bit Boolean 1 bit (special)

6. Accessing I/O Ports (8051 Example)


#include <reg51.h>

void main() {
P1 = 0xFF; // Set Port 1 high
P2 = 0x00; // Set Port 2 low
}
7. Using sbit for Bit-Level Control
#include <reg51.h>
sbit LED = P1^0;

void main() {
LED = 1; // Turn ON LED
LED = 0; // Turn OFF LED
}

8. Delay Functions
void delay_ms(unsigned int ms) {
unsigned int i, j;
for (i = 0; i < ms; i++)
for (j = 0; j < 1275; j++);
}

9. Programming Tasks in Embedded C


Task Example
Toggle LED P1^0 = ~P1^0;
Read switch if (P3^2 == 0) { ... }
Interfacing LCD Send commands/data via port pins
Timer programming Configure TMOD, TCON, etc.
Interrupt handling Use void isr() interrupt n

10. Memory Class Specifiers


Keyword Purpose
code Read-only memory (like Flash/ROM)
data Internal RAM (0x00 – 0x7F)
xdata External RAM
idate Indirect Internal RAM
bit Bit-addressable memory area

11. Interrupts in Embedded C (8051 Example)


void ext0_isr(void) interrupt 0 {
// External interrupt 0 logic
}

12. Best Practices


• Always include while(1) loop.
• Use comments for hardware-specific logic.
• Don’t use floating point unnecessarily.
• Use macros for ports, pins, and delays.

Conclusion: Embedded C allows low-level control over hardware using high-level


syntax, making it ideal for embedded system programming.

Real-Time Operating System (RTOS)

1. What is RTOS?
• RTOS is an operating system designed to serve real-time applications that process
data as it comes in.
• Provides predictable and deterministic responses.
• Example: Medical devices, industrial robots, automotive systems.

2. Types of RTOS
Type Description
Hard RTOS Strict deadlines, failure is unacceptable.
Soft RTOS Missed deadlines degrade performance.
Firm RTOS Occasional deadline miss is tolerable.

3. RTOS Kernel Services


Service Description
Task Management Create, delete, suspend, resume tasks.
Scheduling Decides which task runs next.
Inter-Task Communication Message queues, semaphores, events.
Memory Management Allocate/free memory blocks dynamically.
Interrupt Handling Fast response to external/internal events.
Timers and Delays Generate delays or periodic actions.

4. Characteristics of a Good RTOS


• Deterministic behavior (predictable timing)
• Minimal interrupt latency
• Fast context switching
• Multitasking capability
• Small memory footprint
• Scalability (for small to complex systems)
• Priority-based preemptive scheduling
• Support for inter-task synchronization and communication

5. Qualities of a Good RTOS


Quality Importance
Reliability System should not crash
Efficiency Optimal CPU and memory usage
Flexibility Easy to configure for different hardware
Security Protects shared resources
Modularity Easy to update and maintain

6. RTOS vs General OS
RTOS General Purpose OS
Real-time response No strict timing
Prioritizes critical tasks Equal or time-sharing priority
Small memory/CPU usage High resource usage
Example: FreeRTOS, VxWorks Example: Windows, Linux

7. How to Choose an RTOS?


Functional Requirements
• Real-time performance
• Number of tasks/processes
• Task priorities and scheduling policy
• Communication needs (queues, semaphores)
• Hardware support

Non-Functional Requirements

• Portability
• Scalability
• Cost (open-source or licensed)
• Community and vendor support
• Memory footprint
• Power efficiency (especially for IoT)

8. Examples of Popular RTOS


RTOS Name Features
FreeRTOS Open-source, widely used, portable
VxWorks Commercial, aerospace & medical
RTLinux Real-time Linux extension
TI-RTOS For Texas Instruments processors
Zephyr Lightweight RTOS for IoT devices

Conclusion:
RTOS ensures timely, reliable, and efficient task management in embedded systems where
delays can be critical. Choosing the right RTOS depends on both functional and non-
functional requirements.

Need for RTOS (Real-Time Operating


System)
1. Multitasking Support
• Handles multiple tasks simultaneously.
• Example: Read sensor, control motor, update display — all at once.

2. Real-Time Responsiveness
• Guarantees timely response to events.
• Suitable for systems where delay = failure.
• Example: Airbags in cars, pacemakers, fire alarms.

3. Task Scheduling
• Efficient task prioritization using scheduling algorithms:
o Round Robin
o Priority-based
o Preemptive

4. Deterministic Behavior
• Predictable execution time.
• Helps meet deadlines and real-time constraints.

5. Modularity and Scalability


• System divided into small independent tasks (modular).
• Easy to maintain, scale, and update.

6. Efficient Resource Management


• Manages CPU, memory, I/O among tasks.
• Avoids resource conflicts using:
o Semaphores
o Mutexes
o Message Queues
7. Improved Reliability & Stability
• Isolation of tasks improves fault tolerance.
• If one task fails, others can continue.

8. Better Power Management


• Idle task/sleep mode support reduces power in embedded devices.
• Ideal for battery-operated IoT devices.

9. Inter-task Communication
• Provides built-in mechanisms:
o Message Queues
o Signals
o Shared Memory

10. Used in Critical Applications


• Industrial automation
• Aerospace systems
• Medical electronics
• Telecommunication systems

Conclusion:
RTOS is essential in embedded systems where timing, reliability, multitasking, and
resource control are critical. It ensures real-time performance and better system
management.

Context Switching in RTOS

1. Definition
• Context Switching is the process where the CPU switches from one task (or thread)
to another.
• RTOS saves the current task’s state (context) and loads the next task’s context to
continue execution.

2. What is Context?
The context includes:

• Program Counter (PC)


• Stack Pointer (SP)
• CPU registers (R0 to Rn)
• Status registers (flags)
• Task-specific data (if needed)

3. Why is Context Switching Needed?


• To switch between multiple tasks in multitasking systems.
• To ensure fairness and meet real-time deadlines.
• To preempt low-priority tasks for high-priority ones.

4. Steps in Context Switching


1. Interrupt occurs or task yields
2. Save current task context to its TCB (Task Control Block)
3. Select the next task based on scheduling
4. Load next task's context from its TCB
5. Resume execution of the new task

5. Types of Context Switching


Type Triggered By
Voluntary Task yields CPU
Involuntary Interrupt or time slice expiry

6. Overhead of Context Switching


• Time-consuming due to memory operations.
• Adds latency (switching delay).
• Frequent switches may reduce performance.

7. Minimizing Context Switching


• Use proper task priorities
• Avoid unnecessary preemption
• Use co-operative scheduling for simple systems

8. Real-Time OS Handling
• RTOS manages context switching efficiently and quickly.
• Example: FreeRTOS uses portSAVE_CONTEXT() and portRESTORE_CONTEXT()
macros for this.

9. Example Analogy
Like switching between open tabs in a browser:

• Save current tab state


• Switch to new tab and restore its state

Conclusion:
Context switching is a core function of an RTOS, enabling multitasking by saving and
restoring the state of tasks, but must be optimized to avoid time and memory overhead.

1. Multiple Task and Process – Explanation


Task:

• Smallest unit of execution in an RTOS.


• Shares memory with other tasks.
• Lightweight (less overhead).
• RTOS handles multiple tasks for parallel execution.

Process:

• Independent program in execution.


• Has its own memory space, stack, and resources.
• Used in full-fledged OS (e.g., Linux), not typically in RTOS.

Why Multiple Tasks in Embedded Systems:

• Parallel operations → better performance.


• Example:
o Task 1: Read sensor
o Task 2: Process data
o Task 3: Control motor
o Task 4: Send data to cloud

2. Multirate Systems
Definition:

• A system where tasks execute at different rates/frequencies.

Example:

Task Frequency
Sensor Reading Every 10 ms
Display Update Every 100 ms
Data Logging Every 1 sec

Why Needed?

• Each task has different timing needs.


• Saves CPU time by avoiding unnecessary execution.

3. Process States and Scheduling


Main Process States:

State Description
Ready Task is ready to run, waiting for CPU.
Running Task is currently executing.
Blocked Task is waiting for event (I/O, timer, etc.).
Suspended Task is stopped and not eligible to run.

State Transition Diagram:


┌────────────┐
│ Ready │◄─────┐
└────┬───────┘ │
│ │
┌────▼──────┐ ┌───▼─────┐
│ Running │──►│ Blocked │
└────┬──────┘ └─────────┘

Suspended / Exit

4. Scheduling Policies (in RTOS)


Policy Description Use Case
First Come First Serve
Task executed in order of arrival. Simple, but not real-time.
(FCFS)
Each task gets equal time slot Fair for equal-priority
Round Robin (RR)
(time slicing). tasks.
Rate Monotonic Scheduling Widely used in real-time
Shorter period = Higher priority.
(RMS) systems.
Earliest Deadline First Task with closest deadline gets Optimal for dynamic
(EDF) CPU. deadlines.
Priority-Based Preemptive Highest priority task always runs. Standard in RTOS.

Example Scenario:

Task Period Deadline Priority (RMS)


T1 10 ms 10 ms High
T2 50 ms 50 ms Medium
T3 100 ms 100 ms Low

In RMS, T1 will preempt T2 and T3.

Summary Table
Concept Key Points
Tasks & Processes Task = lightweight, Process = heavyweight
Multirate System Tasks run at different time intervals
Process States Ready, Running, Blocked, Suspended
Scheduling RMS, EDF, Round Robin, FCFS, Priority-based
Priority Scheduling Policies in Real-
Time Systems

1. Priority Scheduling – Overview


• Tasks are assigned priorities.
• CPU always executes the highest priority ready task.
• Can be preemptive or non-preemptive.
• Widely used in Real-Time Operating Systems (RTOS).

2. Earliest Deadline First (EDF)

Explanation:

• Dynamic priority scheduling algorithm.


• Task with the earliest absolute deadline is executed first.
• Priorities change dynamically based on deadlines.

Properties:

• Optimal scheduling for single processor systems.


• Schedules any feasible task set (if total utilization ≤ 1).
• Can guarantee all deadlines are met if schedulable.

Implementation Concept:

• Maintain a ready queue sorted by task deadlines.


• At every scheduling event, pick the task with the nearest deadline.

Advantages:

• Optimal for uniprocessor scheduling.


• High CPU utilization.
• Flexible and adaptive.

Disadvantages:

• Overhead due to dynamic priority changes.


• Complex to implement in systems with many tasks.
• Not ideal for hard real-time systems with strict static priorities.

3. Rate Monotonic Scheduling (RMS)

Explanation:

• Static priority algorithm.


• Priority assigned based on task period: shorter period → higher priority.
• Tasks run periodically at fixed rates.

Properties:

• Fixed priority, simple to implement.


• Schedulable if CPU utilization < ~69% for many tasks.
• Priority is static and does not change during runtime.

Implementation Concept:

• Assign priorities before runtime based on period.


• Scheduler always picks the ready task with highest static priority.

Advantages:

• Easy and predictable.


• Good for periodic tasks with fixed timing.
• Widely used and well-studied.
Disadvantages:

• CPU utilization is limited (~69% max).


• Not suitable for sporadic or aperiodic tasks.
• Lower priority tasks may suffer from starvation.

4. Priority Inversion

Explanation:

• Problem occurs when a high-priority task waits for a resource locked by a low-
priority task.
• Low-priority task prevents higher priority task from running → violates priority-based
scheduling.

Example:

• Task H (high priority) waits for resource held by Task L (low priority).
• Medium priority Task M runs, preempting Task L, causing Task H to wait longer.

Solutions:

• Priority Inheritance Protocol: Low priority task temporarily inherits higher priority.
• Priority Ceiling Protocol: Tasks cannot lock resources if priority is below ceiling.

Implementation Concept:

• RTOS manages priority inheritance automatically.


• Protect shared resources using mutexes with priority protocols.

Consequences if not handled:

• Deadlock, missed deadlines, unpredictable behavior.


5. Summary Table
Policy Type Priority Basis Advantages Disadvantages
Optimal CPU
EDF Dynamic Earliest deadline High overhead, complex
utilization, flexible
Shorter period → Simple, predictable, Limited CPU utilization,
RMS Static
higher priority widely used starvation possible
Priority Blocking due to Addressed with Causes delays, requires
Problem
Inversion resource sharing priority inheritance careful management

6. Implementation Notes
• Both EDF and RMS need a task control block (TCB) with priority or deadline info.
• Scheduler maintains a ready queue sorted by priority or deadline.
• Preemption allows higher priority tasks to interrupt lower priority ones.
• Priority inversion requires mutexes with priority protocols to avoid deadlock and
starvation.

Conclusion:

• EDF is best for dynamic and flexible real-time systems.


• RMS is best for fixed periodic tasks with static priorities.
• Priority inversion is a critical issue in priority scheduling, and solutions like priority
inheritance are essential to maintain system predictability.

You might also like