Timed Frequency counter

Hey, I'm trying to write a code that counts the frequency from a signal generator for 2s. This is the code i wrote:

const int input = 48;  //this is the digital input
int pulse = 0;   //variable to count the pulse
int var = 0; 


void setup() {
  pinMode(input, INPUT);
  Serial.begin(115200); //can't do more than this or the program crashes
  Serial.println(F("No pulses yet...")); //message to send when no pulse are detected
}  


void loop() {
  unsigned long time;
  time = millis();
  while(millis() - time < 2UL * 1000UL){
    if(digitalRead(input) > var){
      var = 1;
      pulse++;
      Serial.println(pulse);
      
    if(digitalRead(input) == 0) {var = 0;}
  }
  }

}

The output I get is:

No pulses yet...
1

Is my code wrong, and if it is what do i do to make it work?

One of many problems is you do not specify the pin number to be read from, which tells me you are not using the documentation while you are writing that program.
Paul

It's 48. Did the OP go back and edit the first post? BTW I wonder what board has pin 48?

The forum software should be able to flag that for historical purposes.
Paul

while( millis( ) - time < 2UL * 1000UL ) {
    if( digitalRead( input ) > var ) {  // entry means var was "0"
                                        //  ...pin read was "1"
        var = 1;                        // so set var == the pin read
        pulse++;
        Serial.println( pulse );
      
        if( digitalRead( input ) == 0 ) {// possibly the pin could have
                                        //  ...chaged to "0" but not likely 
            var = 0;    // if this des not happen now, it never will
        }
    }
 }

The problem is that the second "if" shoud not be in the block
with the first "if". If you would indent your code properly as
you write it, you would immediately see your problem.
Also fix your pin reading problems as already suggested.

Perhaps there wouldn't be quite as much mystery if the thread had not been split off...
https://forum.arduino.cc/t/building-a-photon-counter-for-double-slit-experiment/905495

BTW I wonder what board has pin 48?

its arduino due

what is the max frequency you want to measure?

even if using an interrupt, it will be limited

a better approach would be to use a hardware counter that is read periodically and using initial and final values along with overflows to determine the final result.

a 10bit counter measure every msec would only be able to measure ~1 MHz

How short are the pulses now? In the other thread you were talking about 10ns.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.