#include <reg51.h>
// Traffic light pins
sbit RED = P2^0;
sbit YELLOW = P2^1;
sbit GREEN = P2^2;
// 7-segment codes (Common Cathode)
unsigned char digits[10] = {
0x3F, 0x06, 0x5B, 0x4F,
0x66, 0x6D, 0x7D, 0x07,
0x7F, 0x6F
};
// Function prototypes
void delay1s(void);
void display(unsigned char num);
void countdown(unsigned char t);
// 🔥 1-second delay using Timer0
void delay1s(void) {
unsigned int i;
TMOD = 0x01; // Timer0 mode1
for(i = 0; i < 20; i++) { // 20 × 50ms = 1 sec
TH0 = 0x3C; // Load for ~50ms
TL0 = 0xB0;
TR0 = 1; // Start timer
while(TF0 == 0); // Wait overflow
TR0 = 0; // Stop timer
TF0 = 0; // Clear flag
}
}
// Display number on 7-segment
void display(unsigned char num) {
P1 = digits[num];
}
// Countdown function
void countdown(unsigned char t) {
int i;
for(i = t; i >= 0; i--) {
display(i % 10);
delay1s();
}
}
// Main function
void main(void) {
while(1) {
// 🟢 GREEN (10 sec)
GREEN = 1;
YELLOW = 0;
RED = 0;
countdown(9);
// 🟡 YELLOW (3 sec)
GREEN = 0;
YELLOW = 1;
RED = 0;
countdown(3);
// 🔴 RED (10 sec)
GREEN = 0;
YELLOW = 0;
RED = 1;
countdown(9);
}
}
Post a Comment