Try Embedded

Revolution counter (Hall sensor)

A magnet on a wheel passes a Hall effect switch once a turn; an interrupt counts the turns and the sketch works out the speed.

Sensors · Beginner

In a real product: Bicycle computer (Consumer electronics): A magnet on the wheel gives speed and distance.

A Hall effect switch senses a magnet without touching it. Glue a magnet to a wheel or a fan blade and the sensor's output goes LOW once each turn. Counting those pulses with an interrupt gives the turns, and the turns per second the speed.

What you'll learn

  • An open-collector sensor output that goes LOW when active
  • Counting edges with attachInterrupt() so no pulse is missed while the loop is busy
  • Reading a variable an interrupt changes: volatile, and a copy taken with interrupts off

How it works

The A3144 switches on (OUT LOW) when a south pole comes within its operate point and off again only once the field drops past a lower release point, so it gives one clean edge per pass. Each falling edge on pin 2 runs onMagnet(), which adds one to turns. Once a second the loop copies and clears the count with interrupts briefly off, and prints the turns that second as revolutions per minute. The LED copies the sensor so you can see each pass.

Try this

  • Click the sensor a few times while it runs to bring the magnet past: each click is half a turn (near, then away).
  • Turn the magnet's field down below 100 G: the switch no longer operates. Real magnets weaken with distance.
  • Switch the sensor's kind to analog and read OUT with analogRead(): a 49E linear sensor measures the field.

sketch.ino

// A revolution counter: an A3144 Hall switch on pin 2 goes LOW each time the magnet passes; an interrupt counts the
// turns, and once a second the sketch prints them as rpm. The LED on pin 13 shows the sensor.
volatile unsigned int turns = 0;
unsigned long total = 0;

void onMagnet() { turns++; }

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT_PULLUP);
  pinMode(13, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(2), onMagnet, FALLING);
}

void loop() {
  static unsigned long lastReport = 0;
  digitalWrite(13, digitalRead(2) == LOW);
  if (millis() - lastReport < 1000) return;
  lastReport = millis();
  noInterrupts();
  unsigned int counted = turns;
  turns = 0;
  interrupts();
  total += counted;
  Serial.print(counted * 60);
  Serial.print(" rpm, ");
  Serial.print(total);
  Serial.println(" turns in all");
}

Lessons behind it