Hi, I want to know how many pulses the magnet of the reed switch in the sensor produces in 1 second, this because I know that 4 pulses/s are 10 km/h . I don't want to use interrupts because i'm a beginner with arduino and i don't know how to change the pin for interrupts because pins 2 and 3 are busy. This is the code that i have tried but it gives wrong counts, more counts than real.
int state; //the state of the input
int oldstate;
unsigned long t; //timer
unsigned long s; //samples
unsigned long c; //count
unsigned long f; //frequency
int sigPin=8;
void setup(){
Serial.begin(9600);
pinMode(sigPin,INPUT);
digitalWrite(sigPin,HIGH); //pullup resistor on
}
void loop(){
c = 0;
t = millis(); // read time at start of sampling
while(millis()-t<1000){
state = digitalRead(sigPin); //read state
if (state != oldstate){ //if state changes:
c++; //increment counter
oldstate = state; //and reset current state
}
}
t = millis() - t; //read time at end of sampling
c = c/2; // need to divide by 2 because counter incremented on each change - two changes per cycle
f = 1000*c/t; //calculate frequency
Serial.print("Count: ");
Serial.print(c);
Serial.println("Freq: ");
Serial.print(f);
delay(1000);
}
while(millis()-t<1000){
state = digitalRead(sigPin); //read state
if (state != oldstate){ //if state changes:
c++; //increment counter
oldstate = state; //and reset current state
}
}
Detecting transitions is good. Counting both transitions is bad. Do you want to count the LOW to HIGH transitions or the HIGH to LOW transitions.
You are not debouncing the switch. A short delay between reads is the usual method (10 milliseconds or so).
t = millis() - t; //read time at end of sampling
You know how long sampling took. That was the 1000 in the while statement (one second).
I think i need the low to high transition , this code is only to see if the counts are right, after i will calculate in km/h, but i'm interested to the counts. The frequency is a plus, not important, only counts are important.
It really wasn't clear how you determined that the code is producing incorrect results. Toggling an LED each time you detect a pulse (they are relatively far apart, aren't they?) would enable you to compare counted pulses with counting LED state changes.
Though, I suspect that the reed switch bouncing is your biggest problem.
Switches are mechanical devices with springs and moving metal pieces. When a switch is pressed or released, contact may be made and broken several times before the parts stop bouncing around. Some switches are worse than others, with reed switches being about the worst.
What you need to do is detect the first make or brake, and then stop reading the switch for a while. Generally, "for a while" means 10 milliseconds, or so. A simple delay(10); after a transition is detected will cause the program to miss all the bounces.