Bike Speedometer

Hi Forums,

I’ve been working for a few days on the idea of a bike speedometer using a magnetic reed switch to count the number of tire rotations to determine the speed. What I decided to do was to write a code that would count the number of rotations in a set interval. This is only a basic code as a proof of concept. I would have to add some few things for the LCD display and conversion from rotations to km/h.

The problem is that the numbers seem to be completely sporadic. I have it all hooked up to my bike and as I watch the rotations being printed on the screen they seem to show no real pattern, i.e slowing down or speeding up. I assume that there could be many problems with this entire project so that’s why I come to you.

This is my code, tell me what you think of my method:

unsigned long start;
int count = 0;

void setup() {
  pinMode(A0, INPUT);

void loop() {
  start = millis(); 
  count = 0; 
  while (millis()-start < 3000)
    if (start > millis()) {
      start = millis();
      count = 0;
    int sensorValue = analogRead(A0);

    if (sensorValue == 0) {
      digitalWrite(13, HIGH);
    else {
      digitalWrite(13, LOW);

Another thing that I feel may be problematic is that the reed switch I am using is NC (Normally closed). This means that the switch is outputting random numbers constantly and the program is designed to count all of the zeros, as that is when it is passing the magnet. I was wondering if anyone would know if the switch would be more accurate if it was normally open.

Any input would be lovely to hear, and I thank you all for taking a look at my project. This is one of the first projects I have really embarked on, and I have little to no coding experience, especially when it comes to Arduino. So perhaps I am missing something.

Search for 'debounce' on the main site.

If it is a switch, maybe you should use digitalRead() instead of analogRead().

The other thing is that it isn't really counting how many times the magnet goes past the switch. It is counting how many times the pin is low when the loop executes. Exactly how that turns out depends on how it is wired up. For example, are you using a pull-up resistor and connecting the switch to the ground, or are you using a pull-down resistor and connecting the switch to Vcc?

Probably what you really want to count is how many times it changes from low to high, or high to low. And, as Henry_Best points out, you'll probably need to debounce it.