Search code examples
ccountarduinointerrupt

Counting magnet apperance using reed switch on arduino nano


I'm simply trying to count every time magnet appears in an area using a reed switch. I'm stuck on a little problem. When launching the program, it does not count correctly. Sometimes it follows the order but often it jumps by 2 or 3 units. Could anyone help? Here is the code:

#include <SPI.h> 

int count=0;
volatile bool check = true;
volatile bool revcheck = true;

void setup() {
  Serial.begin(9600);
  SPI.begin();
  pinMode(2, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), magnet_detect, LOW);
}

void loop() {
 if(digitalRead(2) == HIGH) {
    check = true; }
 if(!revcheck) {
    Serial.println(count);
    revcheck = true; }
    }
  

void magnet_detect() 
{
  if(check) {
  count++;
  check = false;
  revcheck =false;
  }
}

Hardware set-up and output: [1]: https://i.sstatic.net/kJSr7.png [2]: https://i.sstatic.net/xBC1q.jpg


Solution

  • You need some form of debouncing. There are standard ways to achieve this,but a simple, "poor-mans" version would look like this:

    beginning of function()
      oldState = 0;
      do stuff
      if(the sensor reads 1 AND oldState is 0):
         counter ++
         oldState = 1
    
      if (the sensor reads 0 AND oldState is 1):
         oldState = 0
    

    You know, the looping is faster than the physical magnet passing the switch (because a microprozessor calculates in milli, often nanoseconds). so you have to check if you actually already have scanned the magnet.