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
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.
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