0% found this document useful (0 votes)
20 views30 pages

Introduction to Basic C Programming

The document provides an overview of basic C programming, detailing the typical development environment phases, key features of the C language, and structured program development methodologies. It covers fundamental concepts such as data types, operators, control structures, functions, and arrays, as well as simulating object-oriented programming in C through encapsulation, abstraction, inheritance, and polymorphism. Additionally, it discusses the challenges of hardware delays in embedded programming and the inefficiencies associated with busy-wait loops.

Uploaded by

mgirinath06
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)
20 views30 pages

Introduction to Basic C Programming

The document provides an overview of basic C programming, detailing the typical development environment phases, key features of the C language, and structured program development methodologies. It covers fundamental concepts such as data types, operators, control structures, functions, and arrays, as well as simulating object-oriented programming in C through encapsulation, abstraction, inheritance, and polymorphism. Additionally, it discusses the challenges of hardware delays in embedded programming and the inefficiencies associated with busy-wait loops.

Uploaded by

mgirinath06
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

UNIT I BASIC C PROGRAMMING

Typical C Program Development Environment:

This process is generally broken down into six main phases:

1. Edit (Creation) ✍️: The programmer uses a Text Editor (or an IDE) to write the C
source code, which is saved with a .c extension (e.g., program.c).
2. Preprocess: The source code is first processed by the Preprocessor, which handles
directives like #include (to insert content from header files) and #define (to substitute
macros).
3. Compile: The Compiler translates the preprocessed code into machine-readable
Object Code (often a .o or .obj file). This is where syntax errors are detected.
4. Link: The Linker takes the object code and combines it with necessary external code,
such as functions from the C Standard Library or other program modules, to create
a single, complete Executable File (e.g., [Link] or [Link]).
5. Load: The Loader (part of the operating system) places the executable file into the
computer's Primary Memory (RAM) for execution.
6. Execute (Run) : The CPU takes control and runs the program's instructions one by
one.

Introduction to C Programming:

Key Facts and Features:

 Origin: C was developed in the early 1970s by Dennis M. Ritchie at Bell


Laboratories.
 Purpose: It was created primarily to implement and improve the UNIX operating
system, which required a language that was efficient and portable.
 Nature: C is considered a Mid-Level Language. This means it combines the features
of a high-level language (like structured programming and rich libraries) with the
ability to perform low-level tasks (like direct memory manipulation using Pointers).
 Paradigm: It is a Procedural Language, meaning a program is structured as a
sequence of procedures or routines (Functions) that are executed in order.
 Execution: C is a Compiled Language. Source code is translated directly into
machine-specific code, which contributes to its reputation for fast execution speed
and high efficiency.

Structured Program Development in C:

The methodology relies on using only three fundamental control structures to dictate the
flow of execution, which helps eliminate confusing, non-linear jumps in code (like those
caused by excessive use of goto):

1. Sequence: Statements are executed in the order they appear, one after the next.
o Example: Reading an input, then calculating a value, then printing the result.
2. Selection (Decision): The program chooses which code block to execute based on a
condition.
o Implementation in C: if...else statements and the switch statement.
3. Repetition (Looping/Iteration): A block of code is executed repeatedly as long as a
specified condition remains true.
o Implementation in C: while, for, and do...while loops.

Example program:
#include <stdio.h>
int main() {
int x = 5;
printf("The number is: %d\n", x);
return 0;
}.
Loop statement:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++)
printf("%d ", i);
return 0;
}

Data Types and Operators:

Data Types:
define the size and type of data that a variable can hold. They tell the compiler
how much memory to allocate and how to interpret the stored bits.

Memory Example
Type Description
(Typical) Value

int Whole numbers (integers). 4 bytes 100, -5

Single-precision floating-point
float 4 bytes 3.14159
numbers (decimals).

Double-precision floating-point
double 8 bytes 123.456789
numbers (more precise decimals).
Memory Example
Type Description
(Typical) Value

char Single characters. 1 byte 'A', 'z', '5'

Integer:
#include <stdio.h>
int main() {
int sum = 5 + 3;
printf("The sum is: %d\n", sum);
return 0;
}

Float, Double, Char Program:

#include <stdio.h>
int main() {
float f=1.2f; double d=2.345; char c='Z';
printf("Float: %.1f, Double: %.3lf, Char: %c\n", f, d, c);
return 0;
}

Operators:

Operators are symbols used to perform operations on variables and values


(operands).

Type Symbol Example Purpose

+, -, *, /, %
Arithmetic Used for mathematical calculations.
(Modulus)

== (Equal to), > Used for comparison; returns true (1) or false
Relational
(Greater than) (0).

Logical && (AND), **`

Used to assign values; the compound


Assignment =, += (e.g., x += 5)
operators (+=, -=, etc.) are shorthand.
Assignment Operator Program:
#include <stdio.h>
int main() {
int x = 10; x += 5;
printf("Final value of x: %d\n", x);
return 0;
}
Arithmetic Operator Program:
#include <stdio.h>
int main() {
int a = 10, b = 5; int result = a * b;
printf("Sum: %d, Diff: %d, Prod: %d\n", a + b, a - b, result);
return 0;
}
Relational Operator Program:
#include <stdio.h>
int main() {
int x=10, y=5; int greater=x>y, less=x<y, equal=x==y;
printf("X>Y: %d, X<Y: %d, X==Y: %d\n", greater, less, equal);
return 0;}

C Program Control :

1. Selection (Decision Making) :

These statements allow the program to choose which block of code to


execute based on whether a specified condition is true or false.

 if...else: Executes one block of code if the condition is true and an alternative block if
it's false.
 switch: Provides a way to choose one path from many possible options based on the
value of a single variable (usually an integer or character).
2. Repetition (Looping):

These statements cause a block of code to be executed repeatedly until a


specific termination condition is met. This avoids redundant code and allows for processing
large amounts of data.

 while: Tests the condition before each iteration. The loop may not run at all if the
condition is initially false.
 do...while: Executes the loop body at least once before testing the condition at the
end of the iteration.
 for: A compact loop designed for counter-controlled repetition, where initialization,
condition check, and increment/decrement are defined in a single line.

3. Jump Statements (Transfer of Control):

These statements unconditionally transfer control flow within a function.

 break: Immediately exits the innermost switch statement or loop (for, while, do-
while).
 continue: Skips the remaining statements in the current iteration of a loop and moves
to the next iteration.
 goto: Transfers control to a specific labeled statement. (Generally avoided as it makes
code difficult to read and maintain.)

C Functions Introduction to Arrays:

1. C Functions :

Functions are the fundamental building blocks of structured C programs.


They are named, self-contained blocks of code designed to perform a specific, defined task.

 Modularity: They break large programs into smaller, manageable, and logical units,
making the code easier to debug and maintain.
 Reusability: A function can be called (executed) multiple times from different parts
of the program without needing to rewrite the code.
 Structure: Every function has a return type (the type of data it sends back), a name,
and a list of parameters (inputs it accepts). Every C program must have one main
function: int main().

2. Introduction to Arrays:

An Array is the simplest and most common structured data type in C. It


is used to store a collection of items that are all of the same data type under a single variable
name.

 Homogeneous: All elements in an array must be the same type (e.g., all int, all float).
 Contiguous Storage: Array elements are stored sequentially in adjacent memory
locations.
 Zero-Based Indexing: Elements are accessed using a position number called an
index or subscript, which always starts at 0. If an array has $N$ elements, the indices
range from $0$ to $N-1$.
o Example: scores[0] accesses the first element of the scores array.
 Functions & Arrays: Arrays are often passed to functions to process collections of
data (e.g., calculating the average of an array of scores)
UNIT II EMBEDDED C

simulating OOP in C:

1. Encapsulation (The "Object"):

 Structure (struct): A C struct is used to define the data members (attributes) of an


"object."
 Method Pointers: The struct can also include function pointers that act as the object's
methods (behaviors). This is common for polymorphism but often methods are defined
outside the struct and take a pointer to the struct as the first argument.
 The Object Pointer: Conventionally, functions that operate on the object take a pointer
to that struct (e.g., struct MyObject *self) as their first argument, similar to the implicit
this or self pointer in C++/Python.

2. Abstraction (Interface):

 Header Files (.h): The header file acts as the public interface, defining what the object
can do (function prototypes and struct name), while the source file (.c) defines how it
does it (the function implementations).
 Opaque Data Types: Using a typedef for a structure pointer without defining the
struct's internals in the header file (an opaque pointer or handle) is the strongest form
of abstraction. The user can only hold a pointer to the object, not access its internal
members.

3. Inheritance (Subtyping):

 Composition/Structure Nesting: Inheritance is simulated by making the "parent"


struct the very first member of the "child" struct.

// Parent "Base" Struct

struct Animal {

// ... base attributes ...

};

// Child "Derived" Struct

struct Dog {

struct Animal base; // MUST be the first member

};
4. Polymorphism (Method Overriding):

 Function Pointer Table (V-Table): This is the most common way to achieve run-time
polymorphism.

o A special struct (the v-table or vtable) is created within the base object. It holds
function pointers for all the virtual methods (methods intended to be
overridden).
o struct Animal_VTable {
o void (*speak)(struct Animal *self); // Virtual method
o };
o struct Animal {
o const struct Animal_VTable *vptr;

The Structure (struct):

 The Data: The struct holds the attributes (data members) of the object.
 The Method Convention: Unlike true OOP languages where methods are part of the
class, in C, methods are regular functions that accept a pointer to the object as their
first argument. This pointer is conventionally named self or this.

2. Information Hiding via Opaque Pointers:

This technique is the best way to achieve strong abstraction and encapsulation
in C, similar to using a private class in C++.

Element Header (.h) Source (.c) Purpose

The user can only


typedef struct MyObject Defines the full struct
Declaration declare a pointer
MyObject; MyObject { ... };
(MyObject *obj).

The user cannot


access obj-
Function
Function Prototypes >internal_field
Implementations
Access (MyObject_method(MyObject because the
(MyObject_method(...)
*self, ...);) definition of
access the internal fields).
MyObject is
hidden.

Analogy: Think of an opaque pointer (MyObject *) as a key (handle) to a locked box (the
struct). Only the functions defined in the source file (MyObject_method) have the blueprint
to open and manipulate the contents of that box.
Inheritance (Subtyping):

Inheritance in C is simulated using a composition trick that relies on memory


layout.

1. Struct Nesting:

To make a struct Dog inherit from a struct Animal, you must include the Animal
struct as the very first member of the Dog struct.

struct Animal {
int age;
// ... other base fields
};
struct Dog {
struct Animal base; // <-- MUST be the first member
char breed[20];
};
2. Upcasting:

Because the base member starts at the exact same memory address as the Dog
structure itself, you can safely cast a pointer to a Dog into a pointer to an Animal. This allows
functions designed for the base type to operate on the derived type.

This is how a function like Animal_feed(struct Animal *a) can be called with a
struct Dog *d without error:

void Animal_feed(struct Animal *a); // Base function


struct Dog my_dog;
// Call the base function using the derived object
Animal_feed((struct Animal *)&my_dog);

Polymorphism (Virtual Methods):

Polymorphism (the ability for different objects to respond differently to the


same method call) is achieved using a Virtual Table (V-Table) of function pointers.

1. The V-Table Structure:

 The Base Struct (Animal) contains a pointer (vptr) to the V-Table.


 The V-Table is a struct that holds function pointers for every method that is intended
to be "virtual" (overridden by derived classes).

typedef struct {
void (*speak)(void *self); // Function pointer for the 'speak' method
void (*move)(void *self); // Function pointer for the 'move' method
} AnimalVTable;
struct Animal {
const AnimalVTable *vptr; // Pointer to the table of methods
}

2. Method Overriding and Dispatch:

1. Concrete Implementations: Each derived object (Dog, Cat) defines its own
specific static V-Table.

// Dog's unique V-Table


const AnimalVTable Dog_vtable = {
speak = Dog_speak_impl, // Pointer to Dog's specific function
move = Animal_move_impl // Reuses the base implementation
};

2. Constructor: The object's constructor must initialize the object's vptr to point to the
correct static V-Table for its type (e.g., Dog_vtable).
3. Dispatch: To call the method polymorphically, you access the appropriate function
pointer through the vptr at runtime.

// Polymorphic Call
void do_speak(struct Animal *a) {
// The program looks up the correct function address at runtime
// (a->vptr) and calls it.
a->vptr->speak(a);
}

A hardware delay (or busy-wait delay) in the context of embedded programming is


a controlled pause in the execution of a software loop designed to consume a specific amount
of time. It's usually implemented by running a loop a calculated number of times to match a
required time duration, typically measured in microseconds ($\mu\text{s}$) or milliseconds
($\text{ms}$). This is essential for meeting real-time constraints, such as accurately timing
the pulses for a stepper motor or waiting for an external device's response.

Problem with Hardware Delays (Busy-Waiting):

The primary problem with these simple hardware delays, especially in modern or
complex systems, is their inaccuracy and inefficiency.

1. Inaccuracy: The loop execution time is highly dependent on the compiler's


optimization level, the CPU's clock speed, and the specific instruction set
architecture.
2. Lack of Portability: A delay loop calibrated for one microcontroller will execute
differently and inaccurately on another.
3. Wasted CPU Cycles: During the delay, the CPU is running pointless instructions
(busy-waiting) instead of performing useful work or entering a power-saving mode.

Minimal Example of a Busy-Wait Loop:

This is a non-portable and inefficient way to create a delay:


#include <stdint.h>
#include <stdio.h>
void hardware_delay_ms(uint32_t ms) {
// 1. Define loop iterations (MAGIC NUMBER - highly platform-
dependent!)
uint64_t iterations_per_ms = 1000;
// 2. Calculate total required iterations
uint64_t total_iterations = ms * iterations_per_ms;
// 3. Busy-wait loop
for (uint64_t i = 0; i < total_iterations; i++) {
// Simple instruction to burn time (often a NOP or a volatile read)
asm("nop");
}
}

// In a real application, 'ms' is often a hardcoded constraint


int main() {
printf("Starting critical task...\n");
hardware_delay_ms(50); // Delay for 50ms
printf("50ms delay complete.\n");
return 0;
}

Loop Timeout Program :

#include <stdio.h>

#include <stdbool.h>

#include <stdint.h>

[Link] external flag (changes after several iterations):

volatile bool is_ready_flag = false;

bool wait_for_flag(uint32_t max_count) {

uint32_t timeout_counter = 0; // 1. Initialize counter

// Simulate the flag changing state after 1000 iterations

volatile uint32_t internal_wait = 0;

2. Loop while waiting AND before timeout occurs:

while (!is_ready_flag && (timeout_counter < max_count)) {

timeout_counter++;

// Simulate busy-waiting/hardware interaction


if (internal_wait++ == 1000) {

is_ready_flag = true; // Flag changes state

3. Return status:

return is_ready_flag; // Returns true if flag was set, false if timed out

Objective: Prevent an infinite loop while waiting for an asynchronous


event (e.g., hardware readiness).

Mechanism: A timeout counter (timeout_counter) is introduced and


initialized to zero.

Loop Condition: The while loop continues only if both the event
condition is false (!is_ready_flag) AND the counter is below a maximum limit (max_count).

Counting: The counter increments inside the loop, consuming CPU


cycles.

Timeout: If the event never occurs, the counter eventually hits


max_count, forcing the loop to terminate.
UNIT-III 8051 PROGRAMMING IN C

DATA Type and Time Delay in 8051:

1. DATA Type in 8051:

The 8051 microcontroller has several internal memory areas, and one of the
most important is the DATA memory space.
The DATA type specifically refers to the lower 128 bytes of on-chip RAM, ranging from
00H to 7FH.

Characteristics of DATA Type:

1. Directly Addressable:
The DATA area can be accessed using direct addressing mode, which results in
faster execution.
2. Fastest Access Memory:
Since DATA memory is inside the CPU, all instructions accessing it take the
minimum number of machine cycles.
3. Divided into Sub-sections:
o 00H–1FH: Register banks (Bank0–Bank3)
o 20H–2FH: Bit-addressable RAM (16 bytes → 128 bits)
o 30H–7FH: General-purpose RAM (scratchpad area)
4. Used for Frequently Accessed Variables:
Small temporary variables, flags, and counters are usually stored here.

Example Instruction:
MOV A, 25H; Move content of DATA memory location 25H into Accumulator
MOV 30H, #55H ; Load immediate value into DATA RAM

2. Time Delay in 8051:

A time delay in embedded systems is used to pause program execution for a


specific amount of time.
In the 8051, delays are generally created using software loops, because the processor
executes instructions at a fixed speed.

Clock and Machine Cycle:

 Standard crystal: 12 MHz


 8051 uses 12 clocks per machine cycle
 Therefore:
1 machine cycle = 1 µs

This relationship helps calculate the delay created by instructions.


Methods of Generating Time Delays:

(A) Delay Using Software Loops:

A simple delay can be created by decrementing a register inside a loop:

MOV R2, #255


LOOP: DJNZ R2, LOOP

Here, DJNZ takes 2 machine cycles, so you can calculate the delay as:
Delay = 255 × 2 µs = 510 µs

Larger delays can be created using nested loops:

MOV R3, #10


DELAY1: MOV R2, #255
DELAY2: DJNZ R2, DELAY2
DJNZ R3, DELAY1
(B) Delay Using Timers:

8051 has Timer 0 and Timer 1, 16-bit timers used for accurate delays.

Steps to use timer:

1. Load the initial value into THx/TLx


2. Configure timer mode in TMOD
3. Start the timer using TRx
4. Wait for TFx to overflow
5. Stop timer and clear flag

Example:

MOV TMOD, #01H ; Timer0, Mode1 (16-bit)


MOV TH0, #0FCH
MOV TL0, #18H ; Load starting value
SETB TR0 ; Start Timer0

WAIT: JNB TF0, WAIT ; Wait for overflow


CLR TR0 ; Stop timer
CLR TF0 ; Clear flag

Importance of Time Delays:

 Controlling external devices (LED blinking, motor control)


 Debouncing switches
 Generating baud rates for serial communication
 Creating precise timing intervals for tasks
I/O Programming in 8051:

The 8051 microcontroller contains four 8-bit parallel ports named Port 0,
Port 1, Port 2, and Port 3, used for performing input/output (I/O) operations. Each port
can be programmed to function as input or output using simple instructions in assembly or
embedded C.

1. 8051 I/O Port Structure:


Port 0 (P0.0 – P0.7):

 Dual-function port
 Used for general I/O or multiplexed address/data bus (AD0–AD7)
 Requires external pull-ups for I/O

Port 1 (P1.0 – P1.7):

 Dedicated I/O port


 No alternate functions
 Has internal pull-ups

Port 2 (P2.0 – P2.7):

 Used as I/O or as higher-order address bus (A8–A15)

Port 3 (P3.0 – P3.7):

Has alternate functions:

 P3.0 – RXD, P3.1 – TXD


 P3.2 – INT0, P3.3 – INT1
 P3.4 – T0, P3.5 – T1
 P3.6 – WR, P3.7 – RD

Also used as general I/O.

2. I/O Port Operation:

Each port pin consists of:

1. Latch (SFR)
2. Input buffer
3. Output driver

To configure a port as:

 Output → Write 0 or 1 directly to the port


 Input → Write 1 to the pin (makes it high impedance)
3. I/O Programming Instructions:
A. Writing to Ports (Output Mode):

Example: Send a value to Port 1

MOV P1, #55H ; Send 55H to Port 1

Toggle an LED on P2.0:

SETB P2.0 ; Make P2.0 high


CLR P2.0 ; Make P2.0 low
B. Reading from Ports (Input Mode):

To read a switch connected to Port 3.2:

MOV A, P3 ; Read Port 3 into A


JB P3.2, SWITCH_OPEN ; If P3.2 = 1
JNB P3.2, SWITCH_CLOSED

To configure a pin as input, write 1:

MOV P1, #0FFH ; Make all pins of Port 1 input


MOV A, P1 ; Read input value

Logic Operations in 8051:

Logic operations are essential instructions in the 8051 microcontroller, used for
manipulating data bits, bytes, and for decision-making. These operations include AND, OR,
XOR, NOT, rotate, and Boolean (bit-level) operations. They help in controlling hardware,
setting flags, reading/writing bits, and performing arithmetic decisions.

The 8051 supports the following major logic operations:

1. AND Operation:

AND is used for bit clearing, masking, and isolating specific bits.

Instructions:

 ANL A, Rn
 ANL A, direct
 ANL direct, A
 ANL A, #data

Example:
ANL A, #0F0H ; Mask lower 4 bits
3. OR Operation:

OR is used for setting bits, combining data, and generating control signals.

Instructions:

 ORL A, Rn
 ORL A, direct
 ORL A, #data

Example:
ORL A, #0FH ; Set lower 4 bits

4. XOR Operation:

XOR is used for bit toggling and digital signal processing.

Instructions:

 XRL A, Rn
 XRL A, direct
 XRL A, #data

Example:
XRL A, #55H ; Toggle bits based on mask

5. NOT (Complement) Operation:

Used to reverse all bits in the accumulator.

Instruction:

 CPL A
 CPL bit (bit complement)

Example:
CPL A ; Invert all bits of A
CPL P1.2 ; Toggle P1.2 pin

Accessing Code ROM Space in 8051:


. What is Code ROM Space?

 The 8051 stores program code in on-chip ROM (4 KB/8 KB depending on the
version).
 This memory is read-only during program execution.
 Constant data such as lookup tables, strings, waveforms are stored here.
2. Why Access Code ROM?

 To read constant values without using internal RAM.


 Useful for LCD messages, sine tables, font maps, etc.

3. code Keyword in Embedded C (Keil C51):

 The code memory type is used to store constants in program memory.

const unsigned char code table[5] = {1, 2, 3, 4, 5};

This keeps the array in program ROM, not in RAM.

4. Accessing Data Stored in Code ROM:

8051 can only read code memory using the MOVC instruction internally, but in Embedded
C, the compiler handles this automatically.

Example: Read from code memory:


#include <reg51.h>

const unsigned char code msg[] = "HELLO";

void main() {
unsigned char x;
x = msg[0]; // fetches 'H' from code ROM
while(1);
}

5. Lookup Table Example:


const unsigned char code lookup[] = {10, 20, 30, 40};

void main() {
unsigned char i, value;
i = 2;
value = lookup[i]; // Reads 30 from code ROM
while(1);
}

Data Serialization in 8051:


1. What is Data Serialization?

 Serialization means sending data bit-by-bit or byte-by-byte in a sequential format.


 Used for communication between microcontroller and external devices such as PC,
sensors, modules (GSM, GPS, Bluetooth).
2. Methods of Serialization in 8051:

8051 supports two main methods:

A. Hardware Serialization (Using UART):

 The 8051 has an inbuilt serial port (UART).


 Data is sent/received as a serial stream.
 Uses registers SCON, SBUF, TMOD, TH1.

B. Software Serialization (Bit-Banging):

 GPIO pins are manually toggled in software to create serial data.


 Used when UART is busy or additional serial ports are required.

3. Hardware Serial Communication – Key Registers:

 SBUF: Holds data to send/receive


 SCON: Configures serial mode (8-bit, variable baud rate)
 TMOD/TH1: Used for baud rate generation (Mode 2 timer)

4. Basic Embedded C Example (UART Serialization):


Initialize UART at 9600 baud:
#include <reg51.h>

void UART_Init() {
TMOD = 0x20; // Timer1 Mode2 (8-bit auto reload)
TH1 = 0xFD; // Baud rate 9600 for 11.0592 MHz
SCON = 0x50; // 8-bit UART, REN enabled
TR1 = 1; // Start Timer1
}
Send a byte (Serialize a byte):
void UART_Tx(unsigned char d) {
SBUF = d; // Load data to serial buffer
while(TI == 0); // Wait until transmit complete
TI = 0;
}
Send a string (Serializing multiple bytes):
void UART_SendString(char *s) {
while(*s) {
UART_Tx(*s++);
}
}
UNIT-IV 8051 SERIAL PORT AND INTERRUPT PROGRAMMING IN C

Basis of Serial Communication in Embedded C:


. [Link] is Serial Communication?

 Serial communication is a method of transferring data one bit at a time over a single
data line.
 Used when microcontroller needs to communicate with devices such as PC, GSM,
GPS, Bluetooth, sensors, or another microcontroller.

2. Why Serial Communication?

 Requires fewer wires than parallel communication.


 Supports long-distance data transfer.
 Saves microcontroller pins.
 Standard method for device communication.

3. Types of Serial Communication:

1. Synchronous – Clock signal is shared (SPI, I2C).


2. Asynchronous – No clock line; uses start/stop bits (UART).

8051 primarily uses asynchronous UART.

4. Basic Terms:

 Baud Rate: Speed of serial communication (e.g., 9600 baud).


 Start Bit: Indicates beginning of data frame.
 Stop Bit: Indicates end of data frame.
 Data Bits: Usually 8 bits.
 Parity Bit: Used for error checking (optional).

5. Serial Communication in 8051 (UART):

8051 has a built-in serial port controlled by:

 SBUF: Serial data buffer


 SCON: Serial control register
 TMOD/TH1: Timer registers for baud rate
 TI/RI: Transmit and receive interrupt flags

8051 Interface to RS232:


1. What is RS232?

 RS232 is a serial communication standard used to connect microcontrollers to PCs


and other devices.
 It uses ±12V voltage levels, which are not compatible with 8051’s 0–5V logic.
2. Need for a Level Converter (MAX232):

 8051 operates at TTL (0–5V)


 RS232 uses ±12V
 MAX232 IC is used to convert TTL ↔ RS232 voltage levels.

Connections:

 8051 TXD (P3.1) → MAX232 → RS232 RX


 8051 RXD (P3.0) → MAX232 → RS232 TX
 VCC = 5V, capacitors for charge pump

3. Steps to Interface 8051 with RS232:

1. Connect P3.0 (RXD) and P3.1 (TXD) to MAX232


2. Set up UART registers (SCON, TMOD, TH1)
3. Initialize baud rate (commonly 9600)
4. Transmit/receive data using SBUF register

4. UART Initialization in Embedded C:


void UART_Init() {
TMOD = 0x20; // Timer1 Mode2
TH1 = 0xFD; // 9600 baud @ 11.0592 MHz
SCON = 0x50; // Mode 1, 8-bit UART, REN enabled
TR1 = 1; // Start Timer1
}

5. Transmitting Data to RS232:


void UART_Tx(unsigned char d) {
SBUF = d; // Load data
while(TI == 0); // Wait for transmit
TI = 0; // Clear flag
}

6. Receiving Data from RS232:


unsigned char UART_Rx() {
while(RI == 0); // Wait for receive
RI = 0;
return SBUF; // Return received byte
}

7. Sending a String to PC:


void UART_SendString(char *s) {
while(*s)
UART_Tx(*s++);
}
Serial Port Programming in 8051:
1. What is the Serial Port in 8051?

 8051 has an inbuilt UART (Universal Asynchronous Receiver/Transmitter).


 It uses two pins:
o P3.0 (RXD) – Receive data
o P3.1 (TXD) – Transmit data
 Used for communication with PC (RS232), GSM, GPS, Bluetooth, or another MCU.

2. Registers Used for Serial Programming:

1. SBUF – Serial buffer (for TX and RX)


2. SCON – Serial control register (mode selection)
3. TMOD – Timer mode (Timer1 for baud rate)
4. TH1 – Baud rate generator
5. TI – Transmit interrupt flag
6. RI – Receive interrupt flag

3. Serial Port Initialization in Embedded C:

To set UART in Mode 1 (8-bit UART) with 9600 baud, we configure Timer1.

void UART_Init() {
TMOD = 0x20; // Timer1 Mode 2 (8-bit auto reload)
TH1 = 0xFD; // Baud rate 9600 for 11.0592 MHz crystal
SCON = 0x50; // Mode 1, 8-bit UART, REN enabled
TR1 = 1; // Start Timer1
}

4. Transmitting Data:
void UART_Tx(unsigned char ch) {
SBUF = ch; // Load data into buffer
while(TI == 0); // Wait for transmit completion
TI = 0; // Clear flag
}

5. Receiving Data:
unsigned char UART_Rx() {
while(RI == 0); // Wait for data
RI = 0; // Clear flag
return SBUF; // Return received byte
}

6. Sending a String:
void UART_SendString(char *s) {
while(*s) {
UART_Tx(*s++);
}
}
Time Configuration in 8051:
What is Time Configuration?

 Time configuration refers to setting up the 8051 timers (Timer0 and Timer1) to
generate delays, counters, and clock signals.
 Timers are 16-bit and driven by the system clock.

2. Timer Operating Modes:

Timers are controlled using the TMOD register.

Mode Bits Function

Mode 0 13-bit Rarely used

Mode 1 16-bit Full range delay/counter

Mode 2 8-bit auto-reload Baud rate generation

Mode 3 Split timer Two 8-bit timers

3. Important Registers:

 TMOD: Selects timer mode


 TCON: Controls timer start/stop
 TH0/TL0: Timer0 high/low register
 TH1/TL1: Timer1 high/low register
 TR0/TR1: Run control bits
 TF0/TF1: Timer overflow flags

4. Basic Steps for Timer Configuration:

1. Select timer mode in TMOD


2. Load initial timer value in THx/TLx
3. Start timer by setting TRx
4. Wait for overflow (TFx = 1)
5. Clear TFx and repeat

5. Simple Delay Using Timer0 (Embedded C):


#include <reg51.h>

void Timer0_Delay() {
TMOD = 0x01; // Timer0 Mode 1 (16-bit)
TH0 = 0xFC; // Load initial value
TL0 = 0x66; // for approx 1ms delay
TR0 = 1; // Start timer
while (TF0 == 0); // Wait for overflow
TR0 = 0; // Stop timer
TF0 = 0; // Clear flag
}

8051 Interrupts:
What is an Interrupt?

 An interrupt is a signal that temporarily halts the main program to execute a special
routine (Interrupt Service Routine – ISR).
 After ISR execution, the main program resumes from where it was interrupted.

2. Types of Interrupts in 8051:


Interrupt Source Vector Address Type

External 0 (INT0) 0x0003 External

Timer0 Overflow 0x000B Timer

External 1 (INT1) 0x0013 External

Timer1 Overflow 0x001B Timer

Serial (UART) 0x0023 Serial

 IE (Interrupt Enable) register enables/disables interrupts.


 IP (Interrupt Priority) register sets high/low priority.

3. Interrupt Registers:

 IE: EA, EX0, ET0, EX1, ET1, ES


 TCON: TF0, TF1, IE0, IE1
 SCON/SBUF: Used for serial interrupts

4. Enabling Interrupts in Embedded C:


#include <reg51.h>

void main() {
EA = 1; // Enable global interrupts
EX0 = 1; // Enable external interrupt 0
while(1) {
// Main program loop
}
UNIT-V 8051 INTERFACING

ADC Interfacing with 8051:

1. ADC (Analog-to-Digital Converter):

 Converts analog signals (0–5V) into digital values for 8051.

2. Common ADCs:

 ADC0804: 8-bit, single-channel


 ADC0808/0809: 8-bit, 8-channel

3. Pin Connections (ADC0804 Example):

 CS → Chip select
 RD → Read data
 WR → Start conversion
 INTR → Conversion complete
 D0–D7 → Data to 8051 port

4. Steps for ADC Interfacing:

1. Apply analog signal to Vin


2. Start conversion (WR pulse)
3. Wait for INTR = 0
4. Read digital data from D0–D7

5. Embedded C Example:

unsigned char ADC_Read() {


CS=0; WR=0; WR=1;
while(INTR); // wait for conversion
RD=0;
unsigned char value = P1;
RD=1; CS=1;
return value;
}

6. Applications:

 Sensor measurement (temperature, light)


 Data acquisition
 Embedded control systems
DAC Interfacing with 8051:
[Link] is DAC?

 DAC (Digital-to-Analog Converter) converts digital values from 8051 into analog
voltage.
 Used for analog output devices like speakers, voltage controllers, and waveform
generators.

2. Common DACs for 8051:


DAC Type Resolution Example

DAC0808 8-bit Multi-channel DAC

DAC0800 8-bit Single-channel DAC

3. DAC Pin Connections:

 Digital Inputs (D0–D7): Connect to 8051 port (e.g., P1)


 Vref: Reference voltage for output
 Vout: Analog output voltage
 GND & Vcc: Power supply

4. Steps for DAC Interfacing:

1. Connect digital data lines to 8051 port


2. Provide Vref and power supply
3. Write digital value to port
4. Analog voltage appears on Vout

5. Embedded C Example (DAC0808):


#include <reg51.h>
void main() {
unsigned char data;
while(1) {
data = 0x80; // Example digital value
P1 = data; // Send to DAC
}
}

 Output voltage: Vout=(D/255)×VrefV_{out} = (D/255) \times V_{ref}Vout


=(D/255)×Vref
where D = digital value, Vref = reference voltage

6. Applications:

 Analog waveform generation


 Audio output (speakers)
 Motor speed control
 Voltage control in embedded systems

Sensor Interfacing with 8051:


[Link] is Sensor Interfacing?

 Connecting sensors to 8051 to measure physical parameters like temperature, light,


or pressure.
 Sensors output analog or digital signals that the microcontroller can process.

2. Types of Sensors:
Sensor Type Output Example

Analog Voltage LM35 (Temp), LDR

Digital Logic 0/1 PIR, Switch

Serial Data bits Ultrasonic, GPS

3. Interfacing Steps:

1. Connect sensor output to MCU (analog → ADC, digital → GPIO)


2. Initialize MCU port (input)
3. Read data from port or ADC
4. Process and display/control (LED, LCD, motor)

4. Embedded C Example – Digital Sensor (Switch):


#include <reg51.h>
void main() {
while(1) {
if(P1 & 0x01) // Check if sensor is HIGH
P2 = 0xFF; // Turn on LED
else
P2 = 0x00; // Turn off LED
}
}
5. Embedded C Example – Analog Sensor (LM35 with ADC0804):
unsigned char ADC_Read();
void main() {
unsigned char temp;
while(1) {
temp = ADC_Read(); // Read analog temperature
P2 = temp; // Display on LEDs/LCD
}
}
6. Applications:

 Temperature monitoring (LM35)


 Light sensing (LDR)
 Motion detection (PIR sensor)
 Industrial automation and robotics

LCD Interfacing with 8051:


[Link] is LCD Interfacing?

 LCD (Liquid Crystal Display) is used to display characters and numbers.


 Common type: 16x2 LCD (16 characters × 2 lines)
 Can be interfaced in 8-bit or 4-bit mode.

2. LCD Pins:
Pin Function

RS Register Select (0 = Command, 1 = Data)

RW Read/Write (0 = Write, 1 = Read)

E Enable (High-to-Low pulse to latch data)

D0–D7 Data pins (8-bit or 4-bit)

Vss, Vcc, Vee Power & contrast

3. Interfacing Steps:

1. Initialize LCD (function set, display ON, clear display)


2. Send command or data using RS, RW, E, and data pins
3. Display characters or strings

4. Embedded C Example – 16x2 LCD:


#include <reg51.h>
sbit RS = P2^0;
sbit RW = P2^1;
sbit EN = P2^2;

void LCD_Command(unsigned char cmd) {


P1 = cmd;
RS = 0; RW = 0;
EN = 1; EN = 0;
}

void LCD_Data(unsigned char data) {


P1 = data;
RS = 1; RW = 0;
EN = 1; EN = 0;
}

void main() {
LCD_Command(0x38); // 8-bit, 2 lines
LCD_Command(0x0C); // Display ON
LCD_Command(0x01); // Clear display
LCD_Data('H'); // Display character
}
5. Applications:

 Display sensor readings (temperature, ADC data)


 Menu-based embedded systems
 Industrial process display
 Microcontroller debugging output

Stepper Motor Interfacing with 8051:


[Link] is a Stepper Motor?

 A stepper motor rotates in discrete steps, allowing precise position control.


 Types: Unipolar and Bipolar

2. Pin Connections:

 Usually 4 control pins connected to 8051 port (e.g., P1.0–P1.3)


 Requires driver circuit (ULN2003, transistor array) to handle current.

3. Interfacing Steps:

1. Connect motor coils to driver circuit


2. Connect driver inputs to 8051 output port
3. Send step sequence to rotate motor
4. Control direction and speed using sequence and delay

4. Step Sequence Example (Unipolar 4-Wire Motor):


Step P1.0 P1.1 P1.2 P1.3

1 1 0 1 0

2 0 1 1 0

3 0 1 0 1

4 1 0 0 1

5. Embedded C Example:
#include <reg51.h>
void delay() {
unsigned int i, j;
for(i=0;i<100;i++)
for(j=0;j<100;j++);
}

void main() {
while(1) {
P1 = 0x09; delay(); // Step 1
P1 = 0x0C; delay(); // Step 2
P1 = 0x06; delay(); // Step 3
P1 = 0x03; delay(); // Step 4
}
}
6. Key Points:

 Speed controlled by delay between steps


 Direction controlled by sequence order
 Use driver IC for higher current motors

7. Applications:

 CNC machines
 Robotics
 Precise position control systems
 Automated industrial equipment.

You might also like