embedded C program for the 8051 microcontroller that counts the number of times a switch is pressed
and released. The program assumes that the switch is connected to a specific pin (e.g., P1.0) and uses a
debouncing mechanism to avoid multiple counts due to switch bouncing.
#include <reg51.h>
sbit SWITCH = P1^0; // Define the switch pin (P1.0)
#define DEBOUNCE_DELAY 20 // Define debounce delay in milliseconds
#define LED_PORT P2 // Define LED_PORT as P2 (entire port for LEDs)
unsigned int press_count = 0; // Variable to store the number of times the switch is pressed
void delay_ms(unsigned int ms) {
unsigned int i, j;
for (i = 0; i < ms; i++)
for (j = 0; j < 123; j++); // Approximate delay for 1ms
void main() {
SWITCH = 1; // Configure switch pin as input (pull-up resistor assumed)
LED_PORT = 0x00; // Initialize all LEDs on P2 to off
while (1) {
if (SWITCH == 0) { // Check if switch is pressed (active low)
delay_ms(DEBOUNCE_DELAY); // Wait for debounce
if (SWITCH == 0) { // Confirm switch is still pressed
press_count++; // Increment the press count
P3 = press_count; // Display press_count on P3 (optional)
LED_PORT = ~LED_PORT; // Toggle all LEDs on P2
while (SWITCH == 0); // Wait for switch release
delay_ms(DEBOUNCE_DELAY); // Wait for debounce
Explanation:
1. Switch Pin Configuration:
- The switch is connected to `P1.0` and is assumed to be active low (i.e., it reads `0` when pressed and
`1` when released).
- The pin is configured as an input by setting it to `1` (pull-up resistor assumed).
2. Debouncing:
- Mechanical switches often bounce when pressed or released, causing multiple transitions. A simple
debouncing mechanism is implemented using a delay (`delay_ms`).
3. Counting Presses:
- The program checks if the switch is pressed (`SWITCH == 0`).
- If pressed, it waits for the debounce delay and confirms the switch is still pressed.
- If confirmed, it increments the `press_count` variable and toggles an LED (optional).
- The program then waits for the switch to be released and applies another debounce delay.
4. LED Indication:
- An LED connected to `P2.0` is toggled each time the switch is pressed (optional).
5. Main Loop:
- The program continuously monitors the switch in an infinite loop.
Notes:
- The `delay_ms` function is a simple loop-based delay and may not be accurate. For precise timing,
consider using a timer.
- The program assumes a pull-up resistor is used with the switch. If a pull-down resistor is used, the logic
will need to be inverted.
- The `press_count` variable can be displayed on an LCD or sent over a serial port for further use.