microcontrollerpicmicroprocessorsmicroc

1 second delay to invert the value of PORTB in mikroC with PIC16F887


Microcontroller: PIC16F887

The task says: Write a program who will invert PORTB and will make it an output port. And in every second, it will make inverse ON/OFF on the LED diodes.

Here is my code:

unsigned cnt;

void interrupt() {
    if(TMR0IF_bit) { // If there is interrupt in timer0
        cnt++;          // Increase the counter
        TMR0IF_bit = 0; // Reset the timer
        TMR0 = 96;      // Set the TMR0 to its default value
    }
}

void main() {
    ANSEL = 0;
    ANSELH = 0;
    OPTION_REG = 0b00000100; // 1:32 prescaler (last 3 bits are 100)
    INTCON = 0xA0;           // Enable interrupt generated by TMR0
    TRISB = 0x00;            // Make PORTB output port
    PORTB = 0xFF;            // Set PORTB to 1s
    cnt = 0;                 // Initialize counter
    TMR0 = 96;               // Starting value of TMR0

    do {
        if(cnt == 391) {
            PORTB = ~PORTB;  // Invert PORTB
            cnt = 0;         // Reset the timer
        }
        cnt++;               // Increase counter if it's not 391
    } while(1);
}

Important

TMR0 = 96 is starting value and 256-96 = 160. OPTION_REG = 1:32, so the prescaler is 32. We need to make a close value to 2M, because 2M instructions are nearly 1 second, as they say.

2 000 000 / 32 (prescaler) * 160 (256-96) = ~ 391. So one second delay should be 2M / 32 * 160 when the counter reaches 391. But when I start it on an 8 MHz simulation, the LED diodes invert in a much faster time than 1 second.

What's the problem and how can I make it to invert on every second?


Solution

  • I suggest you to go through the datasheet of the PIC16F series. It is really important to understand each register and its significance before start using it.

    You have mentioned that, if you remove the increment of cnt from the while loop, it takes more than 10 seconds which clearly indicates that the clock, TMR0 value, and loop value are out of sync.

    For the simple timer implementation explained in PIC16F877 Timer Modules tutorials - Timer0, which may help you.