variable blues

Hello,

I am a beginner with programming and arduinos etc, and I am having some problem with variables in my project. I am trying to build a device to measure the distance that I have ridden on my bike, by counting the number of times the wheel rotates, but the distance variable (an unsigned long) jumps to a huge number when it gets to the maximum size of a signed integer (32,767).

This is the serial output:

...
27432
29718
32004
4294936050
4294938336

This is my code:

const int circumference = 2286;
volatile int value = HIGH;
int rotations = 0;
unsigned long distance = 0;

void setup()
{
  Serial.begin(9600);
  attachInterrupt(1, flick, LOW);
}

void flick(){
  value = LOW;
}

void loop(){
  if (!value) {
     rotations++;
     distance = (rotations * circumference);
     Serial.println(distance);
     delay(70);
     value = HIGH;
  }
}

Thanks for your help,

Cheers,
Earl

Hi Earl, welcome to the arduino :slight_smile:

I noticed a couple of things in your sketch:

Your interrupt flag 'value' is an integer so there could be a problem if an interrupt occurs while the main loop is in the middle of reading the two bytes. You could fix this by disabling interrupts when reading value, but in this case make 'value' a single byte by declaring it : volatile boolean value = HIGH;

Your distance will go negative when you have travelled more than around 70km. That is probably not the problem you are seeing, but making rotations an unsigned long would be more robust.

It may be where you're assigning an int to a long distance = (rotations * circumference);

try casting the result as a long instead:

distance = (long) (rotations * circumference);

-j

Hooray! Problem solved! I tried them all and it worked straight away.

cheers,
Earl