Reed switch - count +1

Hi everyone!

So i am fairly new to arduino and it's language and in need of some help!
I am building a display for my kids ride on car to calculate remaining range and so on as it doesn't have a neutral gear, and if we are far from home one will have to carry it, and now of all the things i could be stuck on i am stuck on the most ridicoulous thing!

To measure the distance driven i want to count the rotations on one of the rear wheels, and the idea is to do so by using a reed switch (ky-025) and count +1 each time the magnet passes, and then take the wheels diameter to count how far it has been driving.

The issue: serial monitor is printing several lines everytime the magnet passes as it is in HIGH state, and it keeps counting as long as this is the fact, and i need it to just be 1 or 0, and if it is 1, count +1 to get the total amount of rotations on the wheel.

int ledOpen=2; //Led is not going to be used, just here while testing on breadboard
int ledClose=2; //Led is not going to be used, just here while testing on breadboard
int switchReed=4;
int rotationcount = 0; 

void setup(){
  pinMode(ledOpen, OUTPUT); //Led is not going to be used, just here while testing on breadboard
  pinMode(ledClose, OUTPUT); //Led is not going to be used, just here while testing on breadboard
  pinMode(switchReed, INPUT);
  Serial.begin(9600);
}

void loop(){
  
  if (digitalRead(switchReed)==HIGH){
    rotationcount ++;
    Serial.println(rotationcount);

what i would have wanted is
22:52:17: 1
22:52:26: 2
And so on.

If anyone have a answer or solution this would help me so much! I am going nuts over here lol :o

You want to detect when the switch opens or closes, not whether the digital port reads HIGH.

The Arduino State Change example shows you how. In the Arduino IDE, choose File>Examples>02.Digital>StateChangeDetection

You may also have to debounce the switch.

It may be worth considering using a Hall effect transducer and a magnet over a mechanical reed switch.

Thank you guys! Managed to get the issue solved today after alot of thinking and some help! :smiley:

Adding the code in case anyone else need something similar!

int switchReed=4;
int rotationcount = 0; 
int switchstate= 0;

void setup(){
  pinMode(switchReed, INPUT);
  Serial.begin(9600);
}
 
void loop(){
  
  if (digitalRead(switchReed)==HIGH&& switchstate == 0){
    switchstate=1;
    rotationcount ++;
    Serial.println(rotationcount);
    //delay(1000);
  }
  if (digitalRead(switchReed)==LOW&& switchstate == 1){
    switchstate=0;
  }
}

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