Procedure - 5 | Experiment No. 8: 8051 Microcontroller - Serial Communication and Interrupts | Microcontroller Lab
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skills—perfect for learners of all ages.

5 - Procedure

Practice

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Serial Communication Setup

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Today, we’ll discuss setting up serial communication using the 8051 microcontroller. Let's start by recalling what serial communication is. Can anyone define it?

Student 1
Student 1

It's a way to send data bit by bit over a single wire, allowing for simpler connections between devices.

Teacher
Teacher

Exactly! Now, for this experiment, you'll connect the 8051's TxD and RxD pins to a PC. Can anyone tell me what those pins do?

Student 2
Student 2

TxD is the Transmit Data pin, and RxD is the Receive Data pin.

Teacher
Teacher

Correct! Remember, TxD sends data out, and RxD receives data in. We will later talk about baud rates. Can someone explain what a baud rate is?

Student 3
Student 3

It’s the speed of data transmission measured in bits per second.

Teacher
Teacher

Well done! Setting it to 9600 bps is common for beginners. Let's review the C program, where we will transmit and receive a string. Who can describe the main tasks in the code?

Student 4
Student 4

We’ll initialize the UART, transmit a 'Hello' message, and echo characters received from the PC.

Teacher
Teacher

Spot on! Alright, let's perform the initial hardware setup and get programming. We’ll discuss our observations afterward.

External Interrupts

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Now we’ll shift gears to external interrupts. Who can tell me what an external interrupt does?

Student 1
Student 1

It allows the microcontroller to respond immediately to external events, like pressing a button.

Teacher
Teacher

Right! For our experiment, you’ll connect a push button to the overlineINT0 pin. What other component will you control with this interrupt?

Student 2
Student 2

An LED! It will toggle when the button is pressed.

Teacher
Teacher

Excellent! In the provided C code, we define an Interrupt Service Routine (ISR) for the button press. What happens in our ISR?

Student 3
Student 3

It toggles the state of the LED.

Teacher
Teacher

Good! Now, let’s compile the code and observe the LED behavior when the button is pressed. What do you expect to see?

Student 4
Student 4

The LED should turn on or off each time the button is pressed, demonstrating a successful interrupt response.

Timer Interrupts

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Moving on to timer interrupts! Can someone define a timer interrupt?

Student 2
Student 2

It’s an interrupt triggered when a timer reaches a specified count, allowing periodic tasks to run.

Teacher
Teacher

Exactly! In our experiment, we’ll use Timer 0 to update an LCD every 100 milliseconds. What hardware setup is needed?

Student 1
Student 1

We need to connect the LCD to the 8051 and configure Timer 0 in the code.

Teacher
Teacher

Great! We reload TH0 with a value that generates the condition for the desired timing. Can anyone explain how we calculate that value?

Student 3
Student 3

We use the formula based on the crystal frequency and desired delay to find the initial value.

Teacher
Teacher

Right! Now, let's compile the C code and see the LCD update in action. How will you verify it's working?

Student 4
Student 4

We'll observe the counter incrementing on the LCD every 100 milliseconds as expected.

Introduction & Overview

Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

This section outlines the experimental procedure for implementing serial communication and interrupts using the 8051 microcontroller.

Standard

The procedure is divided into three parts: setting up serial communication, handling external interrupts, and implementing timer interrupts. Each part describes hardware and software setup, C programming instructions, and observations from executing the code.

Detailed

In this section, we investigate three primary tasks with the 8051 microcontroller:

  1. Serial Communication (Transmit and Receive): This part includes connecting the 8051 to a PC via a USB-to-Serial converter, configuring serial communication settings, writing a C program for echoing messages, and observing the functionality via a terminal emulator. The 8051 utilizes its built-in UART for full-duplex communication.
  2. External Interrupt Handling: In this section, we configure the external interrupt system to toggle an LED each time a button is pressed. It encompasses hardware setup (including push buttons and LED connections), writing C code to manage the interrupt, and testing its responsiveness.
  3. Timer Interrupt for Periodic Task: Lastly, we explore timer interrupts by connecting an LCD display to show a counter that increments every 100 milliseconds, demonstrating real-time tasks handled by the microcontroller. Each section involves detailed steps for programming, compilation, and flashing onto the microcontroller, followed by observations and analyses of the results from each experiment.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Part A: Serial Communication Setup

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

  1. Hardware Setup:
  2. Connect the 8051 development board's serial port (TxD - P3.1, RxD - P3.0) to the PC via a USB-to-Serial converter. Ensure correct RxD-TxD cross-connection (TxD of 8051 to RxD of PC, RxD of 8051 to TxD of PC).
  3. Power on the 8051 board.
  4. Software Setup (PC):
  5. Open a terminal emulator (e.g., PuTTY).
  6. Configure the serial port settings:
  7. Serial line: Select the COM port assigned to your USB-to-Serial converter (check Device Manager).
  8. Speed (Baud): Set to 9600 (or desired baud rate).
  9. Data bits: 8
  10. Stop bits: 1
  11. Parity: None
  12. Flow control: None.

Detailed Explanation

This chunk explains the initial hardware and software setup required for serial communication using the 8051 microcontroller. First, the microcontroller's serial port needs to be connected to a PC using a USB-to-Serial converter. It's essential to connect the transmitter (TxD) and receiver (RxD) correctly to ensure proper communication. After connecting the hardware, the next step involves configuring the terminal emulator on the PC to match the communication settings of the 8051 microcontroller, ensuring they can communicate correctly at a baud rate of 9600 bps.

Examples & Analogies

Think of the hardware setup as setting up a phone call. The TxD and RxD are like the microphone and speaker. If you connect them incorrectly, the other person won’t hear you or understand what you say. Similarly, configuring the software settings is like telling your friend which number to call and what language you're going to use so both of you understand each other.

Part A: C Program for Serial Communication

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

  1. C Program for Serial Communication (Transmit & Receive Loopback):
  2. Aim: Transmit a string 'Hello from 8051!' and then echo back any character received from the PC.
  3. Microcontroller: 8051
  4. Crystal Frequency: 11.0592 MHz (for accurate baud rate)
  5. Baud Rate: 9600 bps
  6. C Code (using Keil C51 syntax):
#include 
#include 
void delay_ms(unsigned int ms) {
    unsigned int i, j;
    for(i = 0; i < ms; i++) {
        for(j = 0; j < 120; j++); // Approx. 1ms delay for 11.0592MHz
    }
}
void UART_Init() {
    TMOD = 0x20; // Timer 1, Mode 2 (8-bit auto-reload) for baud rate
    TH1 = 0xFD; // Reload value for 9600 baud rate
    SCON = 0x50; // Serial Mode 1 (8-bit UART, variable baud rate), REN = 1 (Enable Rx)
    TR1 = 1; // Start Timer 1
    PCON &= 0x7F; // Clear SMOD bit
}
void UART_TxChar(char ch) {
    SBUF = ch; // Load data to SBUF for transmission
    while (TI == 0); // Wait until transmit interrupt flag is set
    TI = 0; // Clear TI flag for next transmission
}
char UART_RxChar() {
    while (RI == 0); // Wait until receive interrupt flag is set
    RI = 0; // Clear RI flag for next reception
    return SBUF; // Return received data
}
void main() {
    char message[] = 'Hello from 8051!\\r\\n'; // Message to send
    char received_char;
    UART_Init(); // Initialize UART
    // Transmit initial message
    for (int i = 0; i < strlen(message); i++) {
        UART_TxChar(message[i]);
        delay_ms(10); // Small delay between characters
    }
    while(1) {
        received_char = UART_RxChar(); // Receive character from PC
        UART_TxChar(received_char); // Echo back character
    }
}

Detailed Explanation

This chunk presents the C code necessary for the 8051 microcontroller to perform serial communication. The program includes functions for initializing the UART (Universal Asynchronous Receiver/Transmitter), sending characters, and receiving characters. It begins by transmitting a greeting string 'Hello from 8051!' to the connected PC. Following that, it enters a loop where it continuously waits for input from the PC, receiving characters, and echoing them back. Each function is designed to ensure smooth data transmission and reception by handling timing and data buffering.

Examples & Analogies

Imagine sending a postcard: you write a message, drop it in the mailbox, and wait for a reply. In this analogy, the UART_Init function is like ensuring the post office can send and receive mail (setting up the system). The UART_TxChar function is the act of sending your postcard (transmitting), while UART_RxChar is waiting for your friend to send a reply (receiving). Each time you write a character on the postcard and send it, you’re echoing back responses just like the microcontroller echoes back received characters.

Part A: Compilation and Execution Process

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

  1. Compilation and Flashing:
  2. Compile the C code using Keil uVision. Resolve any errors.
  3. Flash the generated .hex file to the 8051 microcontroller using your programmer.
  4. Execution and Observation:
  5. Open the terminal emulator.
  6. Reset the 8051 board.
  7. Observe the 'Hello from 8051!' message appearing on the terminal.
  8. Type characters on your PC's keyboard within the terminal. Observe if the 8051 echoes back the characters you type.

Detailed Explanation

Once the C code is written, the next steps involve compiling the code to check for errors and to generate a binary file that the 8051 can understand. This is typically done using an IDE like Keil uVision. After compilation, the binary (or .hex) file needs to be flashed to the microcontroller using a programming tool. Once the code is successfully uploaded, the microcontroller is reset to start executing the program. The expected outcome is that the microcontroller sends a greeting message to the terminal, and any character typed into the terminal should be echoed back, confirming that the communication is functional.

Examples & Analogies

Think of this as the final steps before a play starts. Compilation is like rehearsals where you ensure every line is correct and ready to be performed. Flashing the code is like putting together the actual performance in front of an audience. When you reset the board, it’s like the curtain going up, and you watch your actors (in this case, the microcontroller) deliver lines as the audience (the terminal) reacts to it.

Part B: External Interrupt Handling

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

  1. Hardware Setup:
  2. Connect a push button to the overlineINT0 pin (P3.2) of the 8051. Connect the other end of the button to ground. Use a pull-up resistor (e.g., 10k Ohm) for P3.2 if the internal pull-up is not strong enough or disabled.
  3. Connect an LED with a current-limiting resistor (e.g., 220 Ohm) to a general-purpose I/O pin (e.g., P1.0).

Detailed Explanation

In this part, the focus is on setting up the hardware for handling external interrupts. A push button is connected to one of the interrupt pins (overlineINT0) on the 8051. When this button is pressed, it sends a signal to the microcontroller indicating that an event has occurred (the button press). A pull-up resistor ensures that the pin reads a high signal when the button is not pressed. Additionally, an LED is connected to provide a visual indication of the interrupt action, which will toggle its state each time the button is pressed.

Examples & Analogies

Imagine a doorbell connected to a light that turns on when pressed. The button acts like the doorbell, sending a signal when someone is at the door. In the same way, the push button sends a notification to the microcontroller, and the LED acts like the light turning on to indicate someone pressed the button (the interrupt). The pull-up resistor is like making sure the doorbell has power even when not pressed so it can react promptly when needed.

Part B: C Program for External Interrupt

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

  1. C Program for External Interrupt:
  2. Aim: Toggle an LED connected to P1.0 every time a button connected to overlineINT0 (P3.2) is pressed.
  3. Microcontroller: 8051
  4. C Code (using Keil C51 syntax):
#include 
sbit LED = P1^0; // Assign P1.0 to LED
void External_Int0_ISR() interrupt 0 // Interrupt Vector 0 for INT0
{
    LED = ~LED; // Toggle the LED
}
void main() {
    IT0 = 1; // Configure INT0 for falling edge triggered
    EX0 = 1; // Enable External Interrupt 0
    EA = 1; // Enable Global Interrupt
    LED = 0; // Initialize LED to OFF state
    while(1) {
        // Main program can do other tasks or simply wait
    }
}

Detailed Explanation

This chunk contains the C code for handling external interrupts specifically for the push button. The main function sets up the interrupt to respond to a falling edge signal from the button (when it is pressed). An Interrupt Service Routine (ISR) is defined, which toggles the state of the LED each time the interrupt occurs. The main loop can have other tasks to perform, but in this case, it primarily waits for the button press to trigger the LED toggle.

Examples & Analogies

Think of a waiter in a restaurant who responds to the ringing of a bell (the push button). The waiter would toggle the state of a light (turn it on or off) every time the bell rings. Here, the ISR acts as the waiter who jumps into action each time the button sends an interrupt signal, ensuring the light toggles its state just like the LED in response to the button press.

Part B: Compilation and Execution of External Interrupt Program

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

  1. Compilation and Flashing: Compile and flash the code to the 8051.
  2. Execution and Observation:
  3. Press the button connected to P3.2.
  4. Observe the LED connected to P1.0. Each press (falling edge) should toggle the LED's state (ON to OFF, OFF to ON).

Detailed Explanation

After writing the C code for external interrupt handling, the code must be compiled and flashed to the 8051 microcontroller, similar to previous steps. Once the code is up and running, pressing the button connected to the microcontroller will cause the LED to toggle its state. This serves as a practical demonstration of the interrupt mechanism working correctly, responding immediately to user input.

Examples & Analogies

This is akin to setting a motion sensor light. When someone walks in front of it (presses the button), the light turns on (the LED toggling). In our scenario, the code enables the microcontroller to detect the button press and respond by changing the state of the LED, similar to how the light turns on or off when the sensor is triggered.

Part C: Timer Interrupt Setup

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

  1. Hardware Setup:
  2. Connect an LCD (e.g., 16x2 LCD) to the 8051's ports (typically P2 for data, and some P0/P1 pins for control RS, RW, E). (Assume LCD interfacing is already familiar or use a pre-wired setup on the trainer kit).
  3. (No additional external components specific to timer interrupt for this task, as the LCD updates are internal).

Detailed Explanation

This part requires setting up an LCD to display outputs from the microcontroller using timer interrupts. The LCD connects to the 8051's ports, allowing the microcontroller to send data that can be displayed. The setup doesn't require additional components since the timer intwerface will directly control the LCD functionality through the generated interrupts within the program.

Examples & Analogies

Imagine a digital clock that requires regular updates every second. The LCD here serves the same purpose, needing timely updates to reflect changes in count just as a clock updates every minute. The timer interrupts act as a routine reminder to ensure the display is updated at the right interval, just like an internal mechanism keeps the clock ticking accurately.

Part C: C Program for Timer Interrupt

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

  1. C Program for Timer Interrupt and LCD Update:
  2. Aim: Use Timer 0 interrupt to update a counter on an LCD display every 100 milliseconds.
  3. Microcontroller: 8051
  4. Crystal Frequency: 11.0592 MHz
  5. Timer 0 Mode: Mode 1 (16-bit timer)
  6. C Code (using Keil C51 syntax):
#include 
#include 
// LCD control pins - adjust according to your hardware
sbit RS = P2^0; // Register Select
sbit EN = P2^1; // Enable
#define LCD_DATA P2 // Assuming D4-D7 for data (4-bit mode)
unsigned int timer_count = 0;
char lcd_buffer[16]; // Buffer for LCD display
void LCD_Cmd(unsigned char cmd) {
    LCD_DATA = cmd & 0xF0; // Higher nibble
    RS = 0; EN = 1; delay_ms(1); EN = 0; delay_ms(1);
    LCD_DATA = (cmd << 4) & 0xF0; // Lower nibble
    RS = 0; EN = 1; delay_ms(1); EN = 0; delay_ms(1);
}
void LCD_Char(unsigned char dat) {
    LCD_DATA = dat & 0xF0; // Higher nibble
    RS = 1; EN = 1; delay_ms(1); EN = 0; delay_ms(1);
    LCD_DATA = (dat << 4) & 0xF0; // Lower nibble
    RS = 1; EN = 1; delay_ms(1); EN = 0; delay_ms(1);
}
void LCD_Init() {
    delay_ms(20);
    LCD_Cmd(0x02); // Return Home (for 4-bit init)
    LCD_Cmd(0x28); // 4-bit mode, 2 lines, 5x7 dots
    LCD_Cmd(0x0C); // Display ON, Cursor OFF
    LCD_Cmd(0x06); // Increment cursor, No shift
    LCD_Cmd(0x01); // Clear display
    delay_ms(2);
}
void LCD_String(char *str) {
    while (*str) {
        LCD_Char(*str++);
    }
}
void Timer0_ISR() interrupt 1 // Interrupt Vector 1 for Timer 0
{
    TH0 = 0x4C; // Reload TH0 for 100ms
    TL0 = 0x00; // Reload TL0 for 100ms
    timer_count++; // Increment counter on each 100ms interrupt
}
void main() {
    LCD_Init(); // Initialize LCD
    // Configure Timer 0
    TMOD = 0x01; // Timer 0, Mode 1 (16-bit timer)
    TH0 = 0x4C; // Load initial value for 100ms delay
    TL0 = 0x00; // (0x4C00 = 19456 decimal)
    ET0 = 1; // Enable Timer 0 interrupt
    EA = 1; // Enable Global Interrupt
    TR0 = 1; // Start Timer 0
    LCD_String('Counter: '); // Display static text
    while(1) {
        sprintf(lcd_buffer, '%u', timer_count); // Convert integer to string
        LCD_Cmd(0xC0); // Go to second line
        LCD_String(lcd_buffer);
        delay_ms(50);
    }
}

Detailed Explanation

This chunk contains the C code for utilizing Timer 0 interrupts to increment a counter and display its value on an LCD every 100 milliseconds. The program initializes the LCD and configures Timer 0 for generating interrupts. Each time the Timer 0 interrupt occurs, the ISR increments the timer_count variable, which is displayed on the LCD. Thus, the loop continuously updates the LCD, showing the current value of the counter, while the timer ensures updates happen consistently at the specified interval.

Examples & Analogies

Consider a countdown timer that ticks every second and updates its display accordingly. Each tick functions like the Timer 0 interrupt, prompting the display (LCD) to refresh its count. The program is set up so that whenever the timer ticks, the counter increment mirrors a clock that keeps track of the seconds passing by, ensuring a steady and accurate representation of time.

Part C: Compilation and Execution of Timer Interrupt Program

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

  1. Compilation and Flashing: Compile and flash the code to the 8051.
  2. Execution and Observation:
  3. Observe the LCD display. A counter should be incrementing approximately every 100 milliseconds.
  4. Verify the periodicity of updates. If an oscilloscope is available, you could toggle an unused pin in the ISR to visually confirm the interrupt frequency.

Detailed Explanation

Following the writing of the C code for handling timer interrupts, it is crucial to compile the program for any errors before flashing it to the 8051 microcontroller. Once the code is successfully running, the LCD should display a counter that increments every 100 milliseconds. This demonstrates that the timer interrupt is working as expected. If available, using an oscilloscope can visually confirm that the interrupts are firing correctly at the intended frequency.

Examples & Analogies

Think of it like launching a new app that’s supposed to give you updates every few seconds. If it works perfectly, you see updated information on your screen each time the app refreshes. In the case of our program, once everything is compiled and uploaded, we expect to see constant updates on the LCD, confirming that it operates as reliably as a well-designed app.

Definitions & Key Concepts

Learn essential terms and foundational ideas that form the basis of the topic.

Key Concepts

  • Serial Communication: Sending data one bit at a time using UART.

  • Interrupts: Events that stop the normal flow of execution to handle urgent tasks.

  • Timer Interrupts: Periodic signaling to perform tasks at defined intervals.

Examples & Real-Life Applications

See how the concepts apply in real-world scenarios to understand their practical implications.

Examples

  • Example of UART communication by echoing a received character back to the sender.

  • Example of an LED toggling upon an external button press.

  • Example of a counter on an LCD updating every 100 milliseconds using timer interrupts.

Memory Aids

Use mnemonics, acronyms, or visual cues to help remember key information more easily.

🎵 Rhymes Time

  • For UART communication, bits go one by one,

📖 Fascinating Stories

  • Imagine a postman (UART) delivering letters (bits), one by one, to various houses (devices) in a street (serial line), ensuring everything is delivered in the right order.

🧠 Other Memory Gems

  • Remember the acronym TI-RI (Transmit Interrupt-Receive Interrupt): Think of a reporter (TI) sending news while another reporter (RI) is waiting for news from someone else!

🎯 Super Acronyms

I.C.E for Interrupts

  • Interrupts Cause Execution.

Flash Cards

Review key concepts with flashcards.

Glossary of Terms

Review the Definitions for terms.

  • Term: UART

    Definition:

    Universal Asynchronous Receiver/Transmitter, a hardware peripheral that facilitates serial communication.

  • Term: Baud Rate

    Definition:

    The speed of data transmission in bits per second.

  • Term: Interrupt

    Definition:

    A hardware or software event that temporarily halts normal processing to execute an Interrupt Service Routine.

  • Term: ISR

    Definition:

    Interrupt Service Routine, a specific function designed to execute in response to an interrupt.

  • Term: External Interrupt

    Definition:

    An interrupt caused by an external event, such as a button press.

  • Term: Timer Interrupt

    Definition:

    An interrupt generated when a timer reaches a predetermined count, allowing for periodic function execution.