Hi,
I came across a problem when I tried to extract the frequency of a rectangular input.
What I want to do it to wait for the input signal goes LOW (as initially it is a 3V constant voltage), and then trigger the frequency measurement. I.e. when there is no change in signal, nothing happens.
But as soon as I upload the code, the interrupt triggered continuously even when no change in input value. (How to know? --Because on the serial monitor, it displays "state=0" and frequency all the time, which means interrupt occurs. (also attached a screenshot))
Can someone point out where could be wrong in my code? Or could it have anything to do with my input signal? I attached the input signal on oscilloscope (the blue waveform in the graph).
Thanks a lot!!!!
Shell
And here's my code:
/*
Coded by Dilip Raja
Read the length of pulse signal (either HIGH or LOW)
Modifiyed by Shell on 20/02/2018
This code is used to measure the frequency of a retangular signal.
The measurement principle is : f=1/T, where T = (logic high time)+(logic low time) of the input pulse
The measurement is triggered by an interrupt. When no interrupt, no measurement.
*/
int Htime; //integer for storing high time
int Ltime; //integer for storing low time
float Ttime; // integer for storing total time of a cycle
float frequency; //storing frequency
volatile byte state = 1; // initialise the state=1
void setup()
{
pinMode(2,INPUT); // IO pin D2 as input
//The retangular input signal is initially HIGH (3.3V). Whenever it goes LOW it triggers the interruption
attachInterrupt(digitalPinToInterrupt(2), interupt , LOW);
Serial.begin(9600);
Serial.println("Frequency Counter");
}
void loop()
{
Serial.print ("State: "); // to check whether interrupt occurs or not
Serial.print (state); // state = 1, no interrupt; state = 0, interrupt happens
Serial.print('\n');
while (state == 0){ //state=0 means interrupt occurs, so execute the frequency extraction. Otherwise nothing happens
delay(5000); //wait for 5 sec
Htime=pulseIn(2,HIGH); //read high time
Ltime=pulseIn(2,LOW); //read low time
Ttime = Htime+Ltime;
frequency=1000000/Ttime; //getting frequency with Ttime is in Micro seconds
Serial.print ("Frequency: ");
Serial.print (frequency);
Serial.println (" Hz.");
state = 1; // set state back to 1 to stop the measurement
break;
}
delay(1000); //wait for 1 sec
}
void interupt()
{
state = 0;
}
Moderator edit: image tag added