I am working on an altimeter project and I'm trying to get the code to take an integer value and send it out as a series of beeps on a buzzer. I've got the code working except for some error I believe is associated with the modulo math.
int buzzerPin = 2;
void setup()
{
pinMode(buzzerPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(buzzerPin, 0); //make sure the buzzer is off
int beepAltitude = 24245;
char x = 4; //initialize the power of ten variable to 4 (ten thousand)
if(beepAltitude < 10000)
x--;
if(beepAltitude < 1000)
x--; //remove the need to parse (and report) higher altitudes if they aren't present
Serial.println(beepAltitude, DEC);
delay(5000); //pause between reportings of the altitude
for(x; x >= 0; x--) //this loop starts at a high power of ten and works down counting the amount of altitude of that power
{
int divisor = pow(10, x); //calculate the power of ten to report on this run through the loop
char beepCount = beepAltitude / divisor; //count how many there are of that power of ten (thousands, hundreds, etc)
beepAltitude = beepAltitude % divisor; //remove that power of ten once it has been counted (ex: 542 --> 42)
Serial.println(beepAltitude, DEC);
if(beepCount == 0)
{
digitalWrite(buzzerPin, 1); //long pulse if the number is zero
delay(500);
digitalWrite(buzzerPin, 0);
delay(250);
}
else
for(char a = 0; a < beepCount; a++) //this loop makes a beep for each count (ex: 542 would beep 5 times at the 100 power)
{
digitalWrite(buzzerPin, 1);
delay(250);
digitalWrite(buzzerPin, 0);
delay(250);
}
delay(750); //longer delay between powers of ten
}
}
It beeps out the correct values, but every time it performs the modulo math it adds the integer quotient to the remainder. So the above code yields (on the serial port):
24245
4247
251
53
3
0
Only the last 2 remainders are the correct math and the code beeps out the incorrect values (2, 4, 2, 5, 3). No matter what values I try, it always adds whatever the quotient would be to the modulo result. Is there something goofy in my code that I'm not noticing? Can you only modulo up to a certain sized divisor? If the reported altitude is off by a few feet it's not critical, but this shouldn't be happening.