Search code examples
arduinofrequency

How to measure frequency in arduino using pulseIn() function?


i am newbie in arduino and i have small project i read that pulseIn function return length of the pulse in microseconds and

frequency(HZ)=1/time(second)

so i hope below code to measure frequency value is correct otherwise please notify me

int senserpin=8;
int sensordelay=1000; 
float duration;
float freq;

void setup{
pinMode(senserpin,INPUT);
serial.begin(9600);
}

void loop()
{
duration=pulsein(senserpin,high)
freq=1/(duration*1000000)// multiply duration *1000000 to convert from microseconds to seconds 
serail.print("frequency");
serail.print(freq);

delay(sensordelay)
}

Solution

  • You measured only high time. You need to measure both for calculating frequency and period. I hope this will work for you.

    int highTime;    //integer for storing high time
    int lowTime;     //integer for storing low time
    float period;    // integer for storing period
    float freq;      //storing frequency
    
    void setup()
    {
        pinMode(8,INPUT);  //Setting pin as input
    }
    
    void loop()
    {
        highTime=pulseIn(8,HIGH);  //read high time
        lowTime=pulseIn(8,LOW);    //read low time
        period = highTime+lowTime; // Period = Ton + Toff
        freq=1000000/period;       //getting frequency with totalTime is in Micro seconds
        delay(1000);
    }