In this electronics engineering training blog post you can learn how to write C program code that turns ON and OFF a LED according the state of a Push Button. For beginners in C programming language for microcontroller, for learning how to install Keil Software see the first tutorial AT89C51 microcontroller programming.
The following shows the circuit schematic for the push button and LED with AT89C51 microcontroller.
If you have been following our training course on AT89C51 programming using C then you just need to ground the Port 2 pin 0.
C program code for push button using Keil C51 compiler
Below is the C program code for the push button with LED. When the LED is pushed the LED is turned ON otherwise it stays OFF.
sbit LED = P3^0;
sbit BTN = P2^0;
if(BTN == 0)
LED = 1;
LED = 0;
int i, j;
for(i=0; i<10; i++)
for(j=0; j<5000; j++)
In the program code, we have assigned the Port 2 pin 0, P2^0, to the push button, BTTN using the sbit. Then within the while loop, we have used the if else statement to check continously the state of the push button and if it LOW then the LED is turned ON. Otherwise using else the LED remains OFF.
If you have any questions please leave it as comment below. If you want the project files let us know.