Search code examples
embeddedmicrocontroller8051mikroc

Executing for specific period of time for 8051


Please give a favor,

I am using MikroC compiler to write a program for 8051 microcontrollers, I am trying to find a way to execute and repeat the main program for 10 seconds, then stop for 2 seconds

Code below just an example, I need to toggle Port two each 200 msec, repeat that for 10 sec, then stop for 2 sec, then repeat this operation.

void main()
{
    P2 = 0xAE;

    while (1) {
        P2 = ~P2;
        Delay_ms(200);
    }
}

Thank you


Solution

  • You can use a counter to measure the time: For example:

    #define MS_PER_TICK       200
    #define BLINK_PERIOD_IN_S 10
    #define PAUSE_PERIOD_IN_S 2
    
    #define BLINK_PERIOD_IN_TICKS (BLINK_PERIOD_IN_S * 1000 / MS_PER_TICK)
    #define PAUSE_PERIOD_IN_TICKS (PAUSE_PERIOD_IN_S * 1000 / MS_PER_TICK)
    
    void main(void) {
        unsigned char ticks = 0;
    
        P2 = 0xAE;
    
        for (;;) {
            Delay_ms(MS_PER_TICK);
            ticks++;
    
            if (ticks <= BLINK_PERIOD_IN_TICKS) {
                P2 = ~P2;
            }
            if (ticks == BLINK_PERIOD_IN_TICKS + PAUSE_PERIOD_IN_TICKS) {
                ticks = 0;
            }
        }
    }