I have been trying to set up Timer 1 on my pic32mx320f128h based development board (Uno32 by Digilent). The clock speed is supposed to be 80MHz which should mean each clock cycle takes 12.5ns. a 500Hz signal should take 2,000,000ns. By that logic this is 160,000 clock cycles. I decided to use prescalar of 8 so that the 16bit timer 1 does not roll over. This should mean the timer hits a value of 20,000 for a 500Hz frequency.
However on my oscilloscope I measure a much lower frequency of only 1.57Hz
If i change the prescalar to 1, the speed increaes as expected to 1.57x8 =12.56Hz. However if I then lower PR1 by half to 9999, the speed does not exactly double resulting in only 25.2Hz
I must be missing something here, can anyone guide me on what I might try?
I have tried adjusting the priority levels, and using non multi vectored interrupts to no avail.I have also tried using timer 2 with similar speed issues.
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <plib.h>
#define TICKS_PER_SECOND 80000000 //80MHz
#define PIN2_TRIS TRISDbits.TRISD8
#define PIN2_BIT PORTDbits.RD8
#define PIN2_LAT LATDbits.LATD8
#define PIN3_TRIS TRISDbits.TRISD0
#define PIN3_BIT PORTDbits.RD0
#define PIN3_LAT LATDbits.LATD0
#define PINA0_TRIS TRISBbits.TRISB2
#define PINA0_BIT PORTBbits.RB2
#define PINA0_LAT LATBbits.LATB2
int8_t pwmActive = 0;
void __ISR(_TIMER_1_VECTOR, IPL5SOFT) Timer1ISR(void){
PIN3_LAT = ~PIN3_LAT;
IFS0bits.T1IF = 0; //set timer 1 int flag back to off
}
int main(int argc, char** argv) {
// PIN2_TRIS = 1;
// PINA0_TRIS = 1;
//
// PIN3_LAT = 0;
INTDisableInterrupts();
T1CONbits.TCKPS = 1; //prescale 8
T1CONbits.TCS = 0; //80MHz internal source
PR1 = 19999; //500Hz period
TMR1 = 0; //start timer at 0
T1CONbits.ON = 1; //start the timer
IPC1bits.T1IP = 5; //int priority 5
IPC1bits.T1IS = 0; //sub int priority 0
IFS0bits.T1IF = 0; //set timer 1 int flag off
IEC0bits.T1IE = 1; //enable interrupt for timer 1
INTEnableSystemMultiVectoredInt();
PIN3_TRIS = 0;
while(1){
}
return (EXIT_SUCCESS);
}
I expect to get a 500Hz square wave toggled on pin 3 but instead the frequency is much much lower at 1.57Hz