Hey, I'm trying to write code to measure an input and determine if it is within five cents of the period of a guitar note. The input from a function generator is 110 Hz and the buttons are set up correctly. What doesn't work is the comparison if(tau>period_low & tau<period_high) which should cause an LED to blink. I noticed that the code also never enters the if statement if(capreg_new>capreg_old) either. I don't know if there is a timing error somewhere? Thanks for the help.
Rich (BB code):
//Tuner Program/\/\/\
#define _LEGACY_HEADERS
#include <htc.h>
__CONFIG(INTIO & WDTDIS & PWRTDIS & BORDIS & BORDIS & LVPDIS & DEBUGEN & DUNPROTECT & UNPROTECT);
#define stop 0
#define forward 1
#define backward 2
//void motor_forward(void);
//void motor_backward(void);
unsigned long long get_period(void);
volatile unsigned int notes[4][6]= {12134, 9091, 6811, 5102, 4050, 3034, //E Standard
13620, 9091, 6811, 5102, 4050, 3034, //Drop D
13620, 9091, 6811, 5102, 4545, 3405, //DADGAD
12857, 9631, 7216, 5405, 4290, 3214 }; //Eb
volatile unsigned long long capreg_new, capreg_old;
volatile char overflow;
volatile unsigned long long tau,period, period_high, period_low;
unsigned int portb=0;
char num_times=0;
void main(void){
ANSEL=0x00;
ANSELH=0x00;
PORTD=0;
TRISB=0b11111111;
TRISC=0b00000010; //CCP2 pin as input
TRISD=0b00000000;
T1CON=0x01;
PEIE=1;
GIE=1;
CCP2IF=0;
CCP2IE=0;
TMR1IF=0;
TMR1H=0;
TMR1L=0;
TMR1IE=0;
CCP2CON=0b00000111;
while(1){
period=get_period();
period_high=(period*4108)>>8; //calculating 5 cent off period (4108=2^12*1.00289)
period_low=(period*4084)>>8; //(4084=2^12*(1/1.00289)
TMR1IE=1;
CCP2IE=1;
while(num_times==0);
capreg_old=(CCPR2H<<8)+CCPR2L;
while(num_times==1);
capreg_new=(CCPR2H<<8)+CCPR2L;
CCP2IE=0;
TMR1IE=0;
num_times=0;
if(capreg_new>capreg_old){ //Code never enters here
tau=(capreg_new-capreg_old)+65536*overflow; //calculate period
}
else{
tau=65536-(capreg_old-capreg_new)+65536*overflow;
}
if(tau>period_low & tau<period_high){
PORTD=PORTD^0b11111111;
}
}
}
void interrupt isr(void){
if(TMR1IF=1){ //If Timer 1 overflows and nothing has been captured do not increase overflow
TMR1IE=0;
if(num_times!=0){
overflow++;
}
TMR1IF=0;
TMR1IE=1;
}
if(CCP2IF=1){
CCP2IE=0;
CCP2IF=0;
num_times++;
}
}
unsigned long long get_period(void){
char portb, string, i;
unsigned long long period=0; //Function to get the period associated with
portb=PORTB; //the string being tuned
for(i=0;i<4;i++){
if((portb&0b11000000)==(i<<6)){
for(string=0;string<6;string++){
if(portb&(0b00000001<<string)){
period=notes[string];
}
}
}
}
return period;
}