I have two square wave signals with the same frequency. I want to measure the phase shift between these two signals. There will be a small phase difference between two signals. (0-90 degree) and the frequency will vary in the range 100mHz - 50kHz. I am using an Arduino DUE (ATMEL ATSAM3X8E AU ,ARM)
I tried to use "micros()" for timer functionality to get 2 different times and then calculate the phase shift using the following code:
int led=47,count1=0,count2=0,temp=0;
int i=0,j=0;
float time1[3]={0,0};
float time2[3]={0,0};
float freq1=0,freq2=0;
float period1=0,period2=0;
float ps=0;
void setup()
{
Serial.begin(9600);
Serial.println();
Serial.println();
pinMode(31,INPUT);
pinMode(33,INPUT);
pinMode(led,OUTPUT);
digitalWrite(led,HIGH);
noInterrupts();
attachInterrupt(31,in1,RISING);
attachInterrupt(33,in2,RISING);
interrupts();
}
void in1()
{ noInterrupts();
switch(i){
case 0 : time1[i]=micros(); i++; break;
case 1 : if(j==1){time1[i]=micros(); i++; break;}
}
interrupts();
}
void in2()
{ noInterrupts();
switch(j){
case 0 : if(i==1){time2[j]=micros(); j++; break;}
case 1 : if(i==2){time2[j]=micros(); j++; break;}
}
if(j==2){
period1 = (time1[1]-time1[0]);
period2 = (time2[1]-time2[0]);
freq1 = 1000.0/period1;
freq2 = 1000.0/period2;
ps = (((time2[1]-time1[1])*360.0)s/period1);
if(freq1==freq2){
Serial.println("");
Serial.print("TIME1[0] = ");
Serial.print(time1[0],6);
Serial.print("\t TIME1[1] = ");
Serial.print(time1[1],6);
Serial.print("\t DEL1 = ");
Serial.println(time1[1]-time1[0],6);
Serial.print("TIME2[0] = ");
Serial.print(time2[0],6);
Serial.print("\t TIME2[1] = ");
Serial.print(time2[1],6);
Serial.print("\t DEL2 = ");
Serial.println(time2[1]-time2[0],6);
Serial.print("\t x = ");
Serial.print(time2[0]-time1[0],6);
Serial.print("period1(ms) = ");
Serial.print(period1,6);
Serial.print("\t period2(ms) = ");
Serial.println(period2,6);
Serial.print("freq1 = ");
Serial.print(freq1,6);
Serial.print("\t freq2 = ");
Serial.print(freq2,6);
Serial.print("\t Phase Shift = ");
Serial.println(ps,6);
}
else {
i=0;j=0;
interrupts();
}
}
interrupts();
}
void loop()
{
;
}
When I run this code I am not getting any errors, but in high frequency (above 400 Hz) Ihave a problem. When I tested at 0 degrees, this code produced this output:
400 Hz 1.152 degree
500 Hz 1.440 degree
600 Hz 1.727 degree
700 Hz 2.015 degree
800 Hz 2.304 degree
900 Hz 2.592 degree
1 kHz 2.880 degree
2 kHz 5.760 degree
3 kHz 8.649 degree
.
.
.
10 kHz 28.8 degree
Each frequency has lowest degree that this code can calculate.
How can I fix this code? Is it possible to calculate the phase shift between two square wave signals this way?