# Power Factor Measurement using 18F4550

Status
Not open for further replies.

#### 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.

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;
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;
}
}

#### SunnySkyguy

If you want anything accurate, the p.f. is calculated by RMS Power/ Apparent Power not simply by the zero crossings.

#### sghr220

##### Junior Member level 3
That's assuming the current waveform isn't a pure sine or distorted which is not the case here. Not every load is switching.

#### albbg

I don't think that is the problem, however the variable "i" seems not to be initialized to any value.
How do you calculate the delay: final_pf_cnt * 10 us ?

#### sghr220

##### Junior Member level 3
I don't think that is the problem, however the variable "i" seems not to be initialized to any value.
How do you calculate the delay: final_pf_cnt * 10 us ?

The variable "i" is initialized in the main program this is just the ISR. yes, final_pF_cnt * 10 us is correct.