I am trying to set up the internal oscillator on my PIC to oscillate at 16MHz and am trying to test if it's working correctly by blinking an LED. As I understand it, each command takes 4 clock cycles to execute, and I have two statements in my while loop. I increment of my counter and have if statement to check if the counter has reached 4000000 yet. If it has reached it, then it toggles the LED and resets the counter.
If both the increment and if statement take 4 clock cycles to execute, that means that the LED should roughly toggle once every 2 seconds as it should take roughly 32000000 clock cycles for i to equal 4000000. However my LED is only toggling once every 20 seconds. Could someone please tell me what am I doing wrong/What do I not understand?
// PIC12F1822 Configuration Bit Settings
// 'C' source line config statements
// CONFIG1
#pragma config FOSC = INTOSC // Oscillator Selection (INTOSC oscillator: I/O function on CLKIN pin)
#pragma config WDTE = OFF // Watchdog Timer Enable (WDT disabled)
#pragma config PWRTE = OFF // Power-up Timer Enable (PWRT disabled)
#pragma config MCLRE = OFF // MCLR Pin Function Select (MCLR/VPP pin function is digital input)
#pragma config CP = OFF // Flash Program Memory Code Protection (Program memory code protection is disabled)
#pragma config CPD = OFF // Data Memory Code Protection (Data memory code protection is disabled)
#pragma config BOREN = OFF // Brown-out Reset Enable (Brown-out Reset disabled)
#pragma config CLKOUTEN = OFF // Clock Out Enable (CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin)
#pragma config IESO = ON // Internal/External Switchover (Internal/External Switchover mode is enabled)
#pragma config FCMEN = ON // Fail-Safe Clock Monitor Enable (Fail-Safe Clock Monitor is enabled)
// CONFIG2
#pragma config WRT = OFF // Flash Memory Self-Write Protection (Write protection off)
#pragma config PLLEN = ON // PLL Enable (4x PLL enabled)
#pragma config STVREN = ON // Stack Overflow/Underflow Reset Enable (Stack Overflow or Underflow will cause a Reset)
#pragma config BORV = LO // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (Vbor), low trip point selected.)
#pragma config LVP = ON // Low-Voltage Programming Enable (Low-voltage programming enabled)
// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.
#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main(int argc, char** argv) {
OSCCONbits.SCS=0b11;//needs to be 1x for high frequency oscillator
OSCCONbits.IRCF = 0b1111; //sets to 16MHz
unsigned long i=0x0;
TRISA=0X00; //portA as an output
PORTA=0X00; //LED off
while (1)
{
i++;//increment counter
if (i>4000000) //is time to toggle?
{
i=0; //reset counter
PORTA=~PORTA; //toggle LED
}
}
return (EXIT_SUCCESS);
}