arduino frequency measure

I’m new to arduino .So for a project i need to measure frequency so i found this code can anyone explain me this code .I do understand the LCD interfacing part but the rest is not much understandable

#include <LiquidCrystal.h>

LiquidCrystal lcd(13,12,11,10,9,8);

long freq, tempo;
int pulsos;
boolean pulso;
void setup() {
pulso=HIGH;
pinMode(2,INPUT);
lcd.begin(20, 4);
lcd.setCursor(0,0);
lcd.print(“Frequency =”);
lcd.setCursor(1,2);
lcd.print(“www.TheEngineering”);
lcd.setCursor(4,3);
lcd.print(“Projects.com”);
}

void loop() {
tempo = millis();
if(digitalRead(2)==HIGH)
{
if(pulso==HIGH)
{
pulsos = pulsos + 1;
}

pulso=LOW;

}
else{
pulso=HIGH;
}

if(tempo%2000==0){
freq = pulsos/2;
lcd.setCursor(12,0);
lcd.print(freq);
lcd.print(“Hz”);
pulsos=0;
}
}

It is counting the pulses received on pin 2 every 2000 mS and deriving the frequency from that.

If you need details

tempo = millis(); record current time when entering loop() in ms(bad coding should be unsigned long) if(digitalRead(2)==HIGH) { if pin 2 is HIGH if(pulso==HIGH) { and last time it was LOW (so pulso was set to HIGH) pulsos = pulsos + 1; then count that as a new UP transition } pulso=LOW; and record we wait for LOW so that we don't count multiple times } else{ pulso=HIGH; pin 2 is LOW, we got our LOW transition, say we wait for HIGH }

if(tempo%2000==0){ if tempo is a multiple of 2000 (i.e. every 2 seconds) freq = pulsos/2; the frequency is half the number of HIGH transition because we counted for 2 seconds lcd.setCursor(12,0); display on LCD (messed up if frequency has for example 3 digits first then 2, the last digit will stay --> bad coding) lcd.print(freq); lcd.print("Hz"); pulsos=0; and reset the frequency counter }

then loop

Looks like a pretty thorough analysis.

Incidentally, it appears to me that this if construct:

if(tempo%2000==0){   
    freq = pulsos/2;
    lcd.setCursor(12,0);
    lcd.print(freq);
    lcd.print("Hz");
    pulsos=0;  
}

will be executed multiple times, depending on the number of loop iterations in 1 mS. This may have the effect of overwriting the first frequency measured at the end of each 2 seconds with a value of 0.

Definitely a few issues in that code. The % 2000 thing can't work across millis() value-wrapping, it would normally be done in the standard way:

unsigned long last_time = 0 ;

void loop ()
{
  if (millis () - last_time >= 2000)
  {
    last_time += 2000 ;
    freq = pulsos/2 ; 
    // etc etc
  }
  ...

And the pulse counting would usually be done with standard edge-detection logic:

  current = digitalRead (pin) ;
  if (current != previous)  // detect change
  {
    previous = current ;    // save for next time
    if (current)
      pulsos ++ ;   // count rising edges only
  }

And all the LCD presentation stuff ought to be in separate functions really, not mixed up with the counting logic.