Search code examples
microcontrollerpicmicroprocessorsmicroc

1 second delay to inverse the value of PORTB in MicroC with PIC16F887


Micro controller PIC16F887 // The task says: Write program who will invert PORTB and will make it output port and in every SECOND it will make inverse ON/OFF on the Led Diods

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 prescalar (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 its not 391
}while(1);
}

IMPORTANT TMR0 = 96 is starting value and 256-96 = 160 OPTION_REG = 1:32 so prescalar is 32 we need to make close value to 2M cause 2M instructions are nearly 1 second as they say

2 000 000 / 32 (prescalar) * 160 (256-96) = ~ 391 so one second delay should be 2M / 32 * 160 when the counter reaches 391 but when i start it on 8Mhz simulation the LED DIODS inverse in much faster time than 1 second.

So can you help me figure out what's the problem and how to make it to invert on every second. Thank you


Solution

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

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

    For Simple timer implementation explained in below link, which may help you

    http://www.microcontrollerboard.com/pic-timer0-tutorial.html

    Sudhee