sghr220
Junior Member level 3
Hi all,
Found the following code while searching the subject. It uses two external interrupts (INT0 and INT1) for detecting the zero crossing of the voltage and current signals and timer 0 is loaded with a predetermined 10 us period, each time the timer overflows the code increment the variable "cnt_pf". The measured time difference is taken 5 times then averaged to achieve some kind of accuracy. The problem is upon simulation (Proteus) with a simple clock signals and time difference of 1 ms, the reading of the variable is wrong which i can't figure why!!! so any help is appreciated.
Found the following code while searching the subject. It uses two external interrupts (INT0 and INT1) for detecting the zero crossing of the voltage and current signals and timer 0 is loaded with a predetermined 10 us period, each time the timer overflows the code increment the variable "cnt_pf". The measured time difference is taken 5 times then averaged to achieve some kind of accuracy. The problem is upon simulation (Proteus) with a simple clock signals and time difference of 1 ms, the reading of the variable is wrong which i can't figure why!!! so any help is appreciated.
Code:
unsigned int cnt_pf = 0;
unsigned int sample[5];
unsigned int avg_pf;
unsigned int final_pf_cnt;
float count1;
short int i;
long tlong;
float angle;
void Interrupt()
{
if (TMR0IF_bit)
{
TMR0IF_bit = 0;
TMR0L = 0xD5;
//Enter your code here
cnt_pf++;
}// Timer0
while(INT1IF_bit)// first zerocrossing found
{
TMR0IE_bit = 1;// enables timer0 interrupt
TMR0IF_bit = 0;// clear flag
cnt_pf = 0;
INT1IF_bit = 0;// clear flag for INT1
break;
}
while(INT0IF_bit)// second zerocrossing found
{
TMR0IE_bit = 0; //disable timer0
TMR0IF_bit = 0; // clear flag
INT0IF_bit = 0;//clear flag for INT0
i++;
sample[i] = cnt_pf;
avg_pf+=sample[i];
if(i==5)
{
i = 0;
avg_pf/=5;
final_pf_cnt = avg_pf;
}
break;
}
}