4 way traffic signal code

 #include <reg51.h>


// North

sbit N_RED = P2^0;

sbit N_YELLOW = P2^1;

sbit N_GREEN = P2^2;


// South

sbit S_RED = P2^3;

sbit S_YELLOW = P2^4;

sbit S_GREEN = P2^5;


// East

sbit E_RED = P3^0;

sbit E_YELLOW = P3^1;

sbit E_GREEN = P3^2;


// West

sbit W_RED = P3^3;

sbit W_YELLOW = P3^4;

sbit W_GREEN = P3^5;


// 7-segment

unsigned char digits[10] = {

    0x3F,0x06,0x5B,0x4F,

    0x66,0x6D,0x7D,0x07,

    0x7F,0x6F

};


void delay1s(void) {

    unsigned int i;

    TMOD = 0x01;


    for(i=0; i<20; i++) {

        TH0 = 0x3C;

        TL0 = 0xB0;

        TR0 = 1;

        while(TF0 == 0);

        TR0 = 0;

        TF0 = 0;

    }

}


void display(unsigned char num) {

    P1 = digits[num];

}


void countdown(unsigned char t) {

    int i;

    for(i=t; i>=0; i--) {

        display(i % 10);

        delay1s();

    }

}


// 🔴 Set ALL RED

void all_red() {

    N_RED=1; S_RED=1; E_RED=1; W_RED=1;

    N_YELLOW=0; S_YELLOW=0; E_YELLOW=0; W_YELLOW=0;

    N_GREEN=0; S_GREEN=0; E_GREEN=0; W_GREEN=0;

}


void main(void) {


    while(1) {


        // 🚗 NORTH

        all_red();

        N_RED = 0;

        N_GREEN = 1;

        countdown(9);


        N_GREEN = 0;

        N_YELLOW = 1;

        countdown(3);


        // 🚗 EAST

        all_red();

        E_RED = 0;

        E_GREEN = 1;

        countdown(9);


        E_GREEN = 0;

        E_YELLOW = 1;

        countdown(3);


        // 🚗 SOUTH

        all_red();

        S_RED = 0;

        S_GREEN = 1;

        countdown(9);


        S_GREEN = 0;

        S_YELLOW = 1;

        countdown(3);


        // 🚗 WEST

        all_red();

        W_RED = 0;

        W_GREEN = 1;

        countdown(9);


        W_GREEN = 0;

        W_YELLOW = 1;

        countdown(3);

    }

}

Post a Comment

Post a Comment (0)

Previous Post Next Post
Update cookies preferences