Writing Embedded C Programming for Momentary Switch Connected to P2.0 and 8 LEDs Connected to P1

30 Apr 2023 Balmiki Mandal 0 Embedded C

Programming an Embedded C Momentary Switch (SW)

Today, we'll be programming an embedded C momentary switch (sw) connected to P2.0 and 8 LEDs connected to P1. This program will turn the LEDs on and off when the switch is passed.

Step 1: Create a project

Create a new project in your embedded C development environment and define the Pin 2.0 as a digital input pin. Since this switch is a momentary switch, program it to trigger an interrupt.

Step 2: Create an interrupt service routine

Create an interrupt service routine that will be triggered each time the switch is passed. In this procedure, write code to read the state of the switch and toggle the status of the LEDs accordingly.

Step 3: Compile the code

Compile the code and upload it to the development board. If everything is correct, the LEDs should turn on and off when you pass the switch.

Conclusion

In this tutorial, we have learned how to program an embedded C momentary switch connected to P2.0 and 8 LEDs connected to P1. The program toggles the status of LEDs each time the switch is passed.

 

Here's an example code in embedded C programming language that will turn on 8 LEDs connected to Port 1 when a momentary switch connected to P2.0 is pressed and turn off the LEDs when the switch is released:

#include<reg52.h>  // include header file for 8051 microcontroller

sbit LED1 = P1^0;   // define LED pins
sbit LED2 = P1^1;
sbit LED3 = P1^2;
sbit LED4 = P1^3;
sbit LED5 = P1^4;
sbit LED6 = P1^5;
sbit LED7 = P1^6;
sbit LED8 = P1^7;
sbit SW = P2^0;   // define switch pin

void main()
{
    SW = 1;     // set switch pin as input
    P1 = 0x00;  // clear port 1 initially
    
    while(1)   // infinite loop
    {
        if(SW == 0)    // check if switch is pressed
        {
            P1 = 0xFF;   // turn on all LEDs
            while(SW == 0);  // wait until switch is released
            P1 = 0x00;   // turn off all LEDs
        }
    }
}

In this code, we have used the sbit keyword to define each LED and the switch pins. The SW pin is set as an input and the P1 is cleared initially. In the infinite loop, we continuously check if the switch is pressed or not using the if statement. If the switch is pressed, we turn on all the LEDs using P1 = 0xFF and wait until the switch is released using the while loop. Once the switch is released, we turn off all the LEDs using P1 = 0x00. This loop will keep running continuously and the LEDs will turn on/off based on the switch's state.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.