0% found this document useful (0 votes)
11 views22 pages

MDM QB

The document provides an overview of data types, operators, storage classes, and example C programs in Embedded C. It covers basic, derived, user-defined data types, various operators including arithmetic and logical, and storage classes like auto, register, static, and extern. Additionally, it includes C programs for tasks such as finding prime numbers, counting bits, and sending values to ports.

Uploaded by

Soham Birnale
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)
11 views22 pages

MDM QB

The document provides an overview of data types, operators, storage classes, and example C programs in Embedded C. It covers basic, derived, user-defined data types, various operators including arithmetic and logical, and storage classes like auto, register, static, and extern. Additionally, it includes C programs for tasks such as finding prime numbers, counting bits, and sending values to ports.

Uploaded by

Soham Birnale
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/ 22

1. Explain data types available in embedded C.

Ans:

1. Basic Data Types

Used for storing fundamental values.

Data Type Example Usage


char (1 byte) char ch = 'A';
int (2/4 bytes) int num = 100;
unsigned int uNum =
unsigned int (2/4 bytes)
255;
float (4 bytes) float temp = 36.5;
double (8 bytes) double pi = 3.14159;
2. Derived Data Types

Built using basic types.

Type Example Usage


Array int arr[5] = {1, 2, 3, 4, 5};
Pointer int *ptr; ptr = #
int add(int a, int b) { return a
Function
+ b; }

3. User-Defined Data Types

Defined by the user for better code management.

Type Example Usage


typedef typedef unsigned int uint; uint age = 25;
struct struct Sensor { int id; float temp; };
union union Data { int i; float f; };
enum enum Status {SUCCESS, FAILURE}; Status res = SUCCESS;

4. Bit-Fields

Used to save memory by defining variables at the bit level.

struct Flags {
unsigned int flag1 : 1;
unsigned int flag2 : 1;
};
struct Flags f = {1, 0};

2. Explain different types of operators in Embedded C.


Ans :Operators in Embedded C
Operators in Embedded C perform various operations on variables and values. They are categorized
as follows:
1. Arithmetic Operators
Used for mathematical operations.
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (Remainder) a % b
Example:
int a = 10, b = 3;
int sum = a + b; // 13
int remainder = a % b; // 1

2. Relational (Comparison) Operators


Used to compare values, returning true (1) or false (0).
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
Example:
if (a > b) {
// Do something
}
3. Logical Operators
Used to combine multiple conditions.
Operator Description Example
&& Logical AND (a > 5) && (b < 10)
` `
! Logical NOT !(a == b)
Example:
if ((a > 5) && (b < 10)) {
// Executes if both conditions are true
}

4. Bitwise Operators
Used for bit-level operations (useful in embedded systems).
Operator Description Example
& Bitwise AND a & b
` ` Bitwise OR
^ Bitwise XOR a ^ b
~ Bitwise NOT ~a
<< Left shift a << 2
>> Right shift a >> 2
Example:
int x = 5; // 00000101 in binary
int y = x << 1; // 00001010 (10 in decimal)

5. Assignment Operators
Used to assign values to variables.
Operator Description Example
= Assign a=b
Operator Description Example
+= Add and assign a += b (same as a = a + b)
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
Example:
int a = 5;
a += 3; // a becomes 8

6. Increment & Decrement Operators


Used to increase or decrease a variable’s value by 1.
Operator Description Example
++ Increment a++ (Post-increment), ++a (Pre-increment)
-- Decrement a-- (Post-decrement), --a (Pre-decrement)
Example:
int a = 5;
int b = ++a; // Pre-increment: a becomes 6, b = 6
int c = a--; // Post-decrement: c = 6, a becomes 5

7. Conditional (Ternary) Operator


Shortens if-else statements.
Operator Description Example
?: Ternary operator result = (a > b) ? a : b;
Example:
int max = (a > b) ? a : b; // If a > b, max = a; otherwise, max = b

8. Special Operators
a) Sizeof Operator
Finds the size of a data type or variable.
int a;
printf("%lu", sizeof(a)); // Output: 4 (on a 32-bit system)
b) Type Casting Operator
Converts one data type to another.
float f = (float) 5 / 2; // Result: 2.5
3. Illustrate the storage classes in Embedded C with examples of each.
Ans:

Storage classes in Embedded C define a variable’s storage, scope, lifetime, and visibility,
crucial for memory-efficient 8051 microcontroller programming. The reg51.h header
enables interaction with Special Function Registers (SFRs) like P0, P1, TMOD, and IE.

The four primary storage classes are:

• auto (default) – Local variables created/destroyed within functions.


• register – Suggests fast access in CPU registers, useful for loop counters.
• static – Retains values across function calls; global static limits access to the same
file.
• extern – Allows global variable sharing across multiple files.

1. auto Storage Class (Default for Local Variables)

Auto variables exist only within the function in which they are declared. They are allocated
memory when the function starts and deallocated when it exits.

Example: Simple LED Blinking with auto

#include <reg51.h>

sbit LED = P1^0; // Define LED pin at P1.0

void blinkLED() {
auto int i; // Auto variable (default for local variables)
for (i = 0; i < 5; i++) {
LED = ~LED; // Toggle LED
delay();
}
}

void delay() {
unsigned int j;
for (j = 0; j < 50000; j++); // Simple delay loop
}

void main() {
while (1) {
blinkLED();
}
}

Explanation:
• The auto keyword is optional since all local variables are auto by default.
• The i variable exists only within blinkLED(), and it gets reinitialized every time the
function runs.

2. register Storage Class (Optimized for Speed)

The register storage class is used for frequently accessed variables, such as loop counters. It
instructs the compiler to store the variable in a CPU register (if available), making access
faster. However, in 8051 microcontrollers, only a limited number of registers are available,
so the compiler may ignore this request.

Example: Fast LED Blinking with register

#include <reg51.h>

sbit LED = P1^1; // Define LED pin at P1.1

void fastBlink() {
register int i; // Attempt to store in a register
for (i = 0; i < 10; i++) {
LED = ~LED; // Toggle LED
delay();
}
}

void delay() {
unsigned int j;
for (j = 0; j < 30000; j++);
}

void main() {
while (1) {
fastBlink();
}
}

Explanation:

• The register variable i is suggested to be stored in a CPU register for faster access.
• However, since the 8051 microcontroller has limited registers, the compiler may store
i in RAM instead.

3. static Storage Class (Retains Value Between Calls)

A static variable declared inside a function maintains its value even after the function exits,
making it useful for counters or persistent flags. If a static variable is declared globally, it
restricts access to only the file in which it is declared.

Example: Static Counter for LED Toggle


#include <reg51.h>

sbit LED = P1^2; // Define LED at P1.2

void staticCounterBlink() {
static int count = 0; // Retains value across calls
count++;
if (count % 2 == 0) {
LED = ~LED; // Toggle LED on even calls
}
delay();
}

void delay() {
unsigned int j;
for (j = 0; j < 40000; j++);
}

void main() {
while (1) {
staticCounterBlink();
}
}

Explanation:

• The static variable count retains its value across function calls.
• Unlike auto, it does not get reinitialized to 0 every time the function is called.

4. static Global Variable (Restricted to a File)

Static global variables are accessible only within the file in which they are declared. This
prevents accidental modifications by other files in a multi-file project.

Example: Static Global Counter

#include <reg51.h>

sbit LED = P1^3;


static int counter = 0; // Accessible only in this file

void blinkWithGlobalCounter() {
counter++; // Increment counter
if (counter >= 5) {
LED = ~LED; // Toggle LED after 5 cycles
counter = 0; // Reset counter
}
delay();
}
void delay() {
unsigned int j;
for (j = 0; j < 30000; j++);
}

void main() {
while (1) {
blinkWithGlobalCounter();
}
}

Explanation:

• The static global variable counter cannot be accessed from other files.
• The LED toggles only every 5 function calls due to the persistent counter.

5. extern Storage Class (Access Global Variables Across Files)

The extern keyword allows global variables to be accessed across multiple files without
redefining them. This is useful in modular embedded programming.

File 1: main.c (Define Global Variable)

#include <reg51.h>

extern void toggleLED(); // Function declared in another file

int delay_time = 50000; // Global variable

void main() {
while (1) {
toggleLED();
}
}

File 2: led.c (Use extern to Access delay_time)

#include <reg51.h>

sbit LED = P1^4;


extern int delay_time; // Refer to delay_time in main.c

void toggleLED() {
LED = ~LED; // Toggle LED
delay();
}

void delay() {
unsigned int j;
for (j = 0; j < delay_time; j++);
}

Explanation:

• extern int delay_time; allows led.c to use delay_time without redefining it.
• This is useful in large projects where variables must be shared across multiple files.

Summary Table

Storage
Scope Lifetime Example
Class

Local (inside Temporary variables (loop


auto Function execution
function) counters)

Fast access variables (loop


register Local Function execution
counters)

Until program
static (local) Local Persistent function variables
terminates

static Until program


File-wide File-restricted global variable
(global) terminates

Until program
extern Global (across files) Shared variables between files
terminates

4. Write a C program to store first ten prime numbers into an array using for loop.
Ans:
#include <reg51.h>
#define SIZE 10 // Number of prime numbers to store
void UART_Init();
void UART_Transmit(char);
void UART_SendString(char *);
void findPrimes();
int primes[SIZE]; // Array to store prime numbers
void main() {
UART_Init(); // Initialize UART
findPrimes(); // Find and display prime numbers
while (1); // Infinite loop
}
// UART Initialization (9600 baud)
void UART_Init() {
TMOD = 0x20; // Timer1 Mode2
TH1 = 0xFD; // Baud rate 9600
SCON = 0x50; // 8-bit UART
TR1 = 1; // Start Timer1
}
// Send one character via UART
void UART_Transmit(char ch) {
SBUF = ch;
while (!TI);
TI = 0;
}
// Send string via UART
void UART_SendString(char *str) {
while (*str) {
UART_Transmit(*str++);
}
}
// Find first 10 prime numbers
void findPrimes() {
int count = 0, num = 2, i, isPrime;
while (count < SIZE) {
isPrime = 1;
for (i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
if (isPrime) {
primes[count] = num;
count++;
}
num++;
}
// Send prime numbers via UART
UART_SendString("First 10 primes: ");
for (i = 0; i < SIZE; i++) {
UART_Transmit(primes[i] + '0'); // Convert to char
UART_Transmit(' ');
}
}
5. Write a C program to count number of 1’s in the given 8-bit value and send the count to
Port 3.
Ans:
#include <reg51.h>

// Function to count number of 1's in an 8-bit value


unsigned char count_ones(unsigned char value) {
unsigned char count = 0;
while (value) {
count += value & 1; // Check least significant bit
value >>= 1; // Right shift value
}
return count;
}

void main() {
unsigned char input_value = 0x5A; // Example 8-bit value (01011010 in binary)
unsigned char ones_count;

ones_count = count_ones(input_value); // Count number of 1s


P3 = ones_count; // Send count to Port 3

while (1); // Infinite loop to keep the program running


}
6. Store first ten prime numbers into an array using for loop.
Ans:
#include <reg51.h>

// Function to count number of 1's in an 8-bit value


unsigned char count_ones(unsigned char value) {
unsigned char count = 0;
while (value) {
count += value & 1; // Check least significant bit
value >>= 1; // Right shift value
}
return count;
}

void store_primes(unsigned char primes[], unsigned char size) {


unsigned char num = 2, count = 0, i, is_prime;
while (count < size) {
is_prime = 1;
for (i = 2; i * i <= num; i++) {
if (num % i == 0) {
is_prime = 0;
break;
}
}
if (is_prime) {
primes[count] = num;
count++;
}
num++;
}
}

void main() {
unsigned char input_value = 0x5A; // Example 8-bit value (01011010 in binary)
unsigned char ones_count;
unsigned char primes[10];

ones_count = count_ones(input_value); // Count number of 1s


P3 = ones_count; // Send count to Port 3

store_primes(primes, 10); // Store first ten prime numbers

while (1); // Infinite loop to keep the program running


}
7. Write a C program to send the table of 5 onto Port 2 using function. Give delay after sending
each value onto Port 2.
Ans:
#include <reg51.h>

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

void send_table_of_5() {
unsigned char i;
for (i = 1; i <= 10; i++) {
P2 = 5 * i; // Send table value to Port 2
delay(); // Delay after sending each value
}
}

void main() {
send_table_of_5(); // Send table of 5 to Port 2
while (1);
}

8. Write an Embedded C program to transfer a block of five 8-bit values from RAM memory
address 0x40-0x44 to 0x50-0x54.
Ans:
#include <reg51.h>
void transfer_block() {
unsigned char i;
unsigned char xdata *src = (unsigned char xdata *)0x40; // Source address
unsigned char xdata *dest = (unsigned char xdata *)0x50; // Destination address

for (i = 0; i < 5; i++) {


*(dest + i) = *(src + i); // Transfer data from source to destination
}
}
void main() {
transfer_block(); // Call function to transfer block
while (1);
}
9. Explain TMOD & TCON registers in brief.
Ans:

TMOD (Timer Mode) Register:

The TMOD register is an 8-bit register in the 8051 microcontroller used to configure Timer 0
and Timer 1. It controls the mode of operation for both timers.

TMOD Register Format:

r
CopyEdit
| GATE | C/T | M1 | M0 | GATE | C/T | M1 | M0 |
|------|-----|----|----|------|-----|----|----|
| T1 | T1 | T1 | T1 | T0 | T0 | T0 | T0 |

• GATE: If set to 1, the timer runs only when the external interrupt (INT0/INT1) is
high.
• C/T: If set to 1, the timer works as a counter (counts external pulses); if 0, it works as
a timer.
• M1 & M0: Select the timer mode.
o 00 - Mode 0 (13-bit timer)
o 01 - Mode 1 (16-bit timer)
o 10 - Mode 2 (8-bit auto-reload)
o 11 - Mode 3 (Split timer mode)

TCON (Timer Control) Register:

The TCON register is an 8-bit register used to control Timer and External Interrupt
operations.

TCON Register Format:

CopyEdit
| TF1 | TR1 | TF0 | TR0 | IE1 | IT1 | IE0 | IT0 |

• TF1, TF0 (Timer Overflow Flags): Set when Timer 1 or Timer 0 overflows.
• TR1, TR0 (Timer Run Control): Start (1) or Stop (0) Timer 1 or Timer 0.
• IE1, IE0 (Interrupt Flags): Set when an external interrupt occurs.
• IT1, IT0 (Interrupt Type Control):
o 1 - Edge-triggered interrupt.
o 0 - Level-triggered interrupt.
10. Explain Timer Mode 1 block diagram.
Ans:

The lower 5 bits of TLX and 8 bits of THX are used for the 13 bit count.Upper 3 bits of
TLX are ignored. When the counter rolls over from all 0's to all 1's, TFX flag is set and an
interrupt is generated.
The input pulse is obtained from the previous stage. If TR1/0 bit is 1 and Gate bit is 0, the
counter continues counting up. If TR1/0 bit is 1 and Gate bit is 1, then the operation of the
counter is controlled by input. This mode is useful to measure the width of a given
pulse fed to input.

Timer Mode 1 Block Diagram Explanation (8051 Microcontroller)

Timer Mode 1 is a 16-bit timer mode, meaning the timer operates with a full 16-bit register
(THx and TLx) to count from 0000H to FFFFH (0 to 65535 decimal). Once the timer
overflows (FFFFH → 0000H), the TFx (Timer Overflow Flag) in the TCON register is set,
indicating that the timer has completed one full cycle.

1. Timer Register (THx & TLx):

• The timer is divided into two 8-bit registers:


o THx (Timer High Register) – Stores the high byte.
o TLx (Timer Low Register) – Stores the low byte.
• These registers increment as the timer runs.

2. Timer Clock Source:

• The timer can be incremented by the system clock (machine cycle) or external
clock pulses.
• Controlled by the C/T bit in the TMOD register:
o 0 → Uses the internal system clock (1/12th of the oscillator frequency).
o 1 → Uses an external event for counting.

3. Control Signals:

• GATE (TMOD Register): If 1, the timer only runs when the external interrupt pin
(INTx) is high.
• TRx (TCON Register): When set (1), the timer starts running; when cleared (0), the
timer stops.

4. Overflow Mechanism:

• The timer continuously counts up.


• When it overflows from FFFFH → 0000H, the TFx flag (TCON Register) is set.
• The flag can be used to generate an interrupt if enabled.

Working of Timer Mode 1:

1. Load initial values into THx and TLx.


2. Set the Mode 1 configuration in the TMOD register.
3. Start the timer by setting the TRx bit.
4. The timer increments until it reaches FFFFH, then resets and sets the TFx flag.
5. If interrupts are enabled, an interrupt can be triggered when TFx = 1.

This mode is commonly used for time delays, event counting, and waveform generation in
embedded applications.

11. Explain Timer Mode 2 block diagram.


Ans:

This is a 8 bit counter/timer operation. Counting is performed in TLX while THX stores a
constant value. In this mode when the timer overflows i.e. TLX becomes FFH, it is fed
with the value stored in THX. For example if we load THX with 50H then the timer in
mode 2 will count from 50H to FFH. After that 50H is again reloaded. This mode is useful
in applications like fixed time sampling.

Timer Mode 2 Block Diagram Explanation (8051 Microcontroller)

Timer Mode 2 is an 8-bit auto-reload mode, meaning the timer operates with an 8-bit
register (TLx) while the THx register holds a constant reload value. When the TLx
register overflows (FFH → 00H), it is automatically reloaded with the value stored in THx.

Timer Mode 2 Block Diagram Breakdown:

1. Timer Registers (THx & TLx):

• THx (Timer High Register): Holds the reload value that is automatically loaded
into TLx after an overflow.
• TLx (Timer Low Register): Increments with the clock and overflows at FFH.

2. Timer Clock Source:

• Controlled by the C/T bit in the TMOD register:


o 0 → Uses the internal system clock (1/12th of the oscillator frequency).
o 1 → Uses an external event for counting.

3. Control Signals:

• GATE (TMOD Register): If 1, the timer runs only when the external interrupt pin
(INTx) is high.
• TRx (TCON Register): When set (1), the timer starts running; when cleared (0), the
timer stops.

4. Overflow and Auto-Reload Mechanism:

• The timer counts from the initial value in TLx up to FFH.


• When it overflows (FFH → 00H), the TFx (Timer Overflow Flag) in TCON is set.
• Immediately, THx is copied into TLx, restarting the count without software
intervention.

Working of Timer Mode 2:

1. Load the reload value into THx.


2. Set the Mode 2 configuration in the TMOD register.
3. Start the timer by setting the TRx bit.
4. The timer counts up from TLx → FFH, then overflows.
5. When overflow occurs:
o THx is automatically copied into TLx.
o TFx flag is set, which can trigger an interrupt if enabled.
6. The process repeats without reloading manually.

Advantages of Timer Mode 2:

Auto-reload feature – Eliminates the need for software reload.

Efficient for baud rate generation – Used in serial communication timing.


Good for periodic events – Ideal for waveform generation or fixed interval delays.

This mode is mainly used when a constant time delay or baud rate generation is required
in 8051 microcontroller applications.
12. Write an embedded C program to toggle the port pin P3.7 after every 10ms using Timer0.
Also show the steps to design the timer value. Assume Crystal Freq=11.0592MHz.
Ans: Here’s an Embedded C program that toggles P3.7 every 10ms using Timer 0 in Mode 1 (16-bit
Timer Mode). The program calculates the timer's initial value based on a Crystal Frequency of 11.0592 MHz.

#include <reg51.h>

void Timer0_Init() {
TMOD = 0x01; // Timer0 in Mode 1 (16-bit timer)
TH0 = 0xDC; // Load high byte
TL0 = 0x00; // Load low byte
TR0 = 1; // Start Timer0
ET0 = 1; // Enable Timer0 interrupt
EA = 1; // Enable global interrupt
}

void Timer0_ISR() interrupt 1 {


TH0 = 0xDC; // Reload high byte
TL0 = 0x00; // Reload low byte
P3 ^= 0x80; // Toggle P3.7
}
void main() {
P3 = 0x00; // Initialize Port 3
Timer0_Init(); // Initialize Timer0
while (1); // Infinite loop
}
13. Write an embedded C program to generate the square wave of 500Hz frequency using
Timer1 on P1.5 pin of 8051. Also show the steps to design the timer value. Assume Crystal
Freq=11.0592MHz.
Ans: A 500Hz square wave has a time period of 1/500 = 2ms. Since a square wave consists of high and
low states of equal duration, each state lasts for 1ms.

#include <reg51.h>
void Timer1_Init() {
TMOD |= 0x10; // Timer1 in Mode 1 (16-bit timer)
TH1 = 0xFC; // Load high byte
TL1 = 0x67; // Load low byte
TR1 = 1; // Start Timer1
ET1 = 1; // Enable Timer1 interrupt
EA = 1; // Enable global interrupt
}

void Timer1_ISR() interrupt 3 {


TH1 = 0xFC; // Reload high byte
TL1 = 0x67; // Reload low byte
P1 ^= 0x20; // Toggle P1.5
}
void main() {
P1 = 0x00; // Initialize Port 1
Timer1_Init(); // Initialize Timer1
while (1); // Infinite loop
}
14. Write an embedded C program to toggle the port pin P2.0 of 8051 after every 100uS using
Timer0 in Auto reload mode. Assume Crystal Freq=11.0592MHz.
Ans: We need to toggle P2.0 every 100µs using Timer0 in Mode 2 (8-bit auto-reload mode).

#include <reg51.h>

void Timer0_Init() {
TMOD = 0x02; // Timer0 in Mode 2 (8-bit auto-reload)
TH0 = 0xA4; // Load auto-reload value for 100µS delay
TL0 = 0xA4; // Load initial value
TR0 = 1; // Start Timer0
ET0 = 1; // Enable Timer0 interrupt
EA = 1; // Enable global interrupt
}

void Timer0_ISR() interrupt 1 {


P2 ^= 0x01; // Toggle P2.0
}

void main() {
P2 = 0x00; // Initialize Port 2
Timer0_Init(); // Initialize Timer0
while (1); // Infinite loop
}

15. Write an embedded C program to generate the square wave of 10KHz frequency using
Timer1, Mode 2 on P1.5 pin of 8051. Also show the steps to design the timer value. Assume
Crystal Freq=11.0592MHz.
Ans:

#include <reg51.h>
void Timer1_Init() {
TMOD |= 0x20; // Timer1 in Mode 2 (8-bit auto-reload)
TH1 = 0xD2; // Load auto-reload value for 50µs delay
TL1 = 0xD2; // Load initial value
TR1 = 1; // Start Timer1
ET1 = 1; // Enable Timer1 interrupt
EA = 1; // Enable global interrupt
}
void Timer1_ISR() interrupt 3 {
P1 ^= 0x20; // Toggle P1.5
}

void main() {
P1 = 0x00; // Initialize Port 1
Timer1_Init(); // Initialize Timer1
while (1); // Infinite loop
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy