# Dividing error ?

Hello. I’ts my first post on this forum, so please be patient if I’m doing something “not right”. Also - I’m from Poland, and my english is week - sorry.

Ok. In my project I’m using four LEDs and one potentiometer - nothing special in connections - just for proving my concept about coding. Whiole playing with arduino IDE (1.0.1) i found strange behavior - in his code:

``````int LEDPins[4] = {4,5,6,7};
unsigned long LEDuration[4];
int actLED;

unsigned long actAnalogValue = 0;

int RandBase = 500;
int actRandValue = 500;

void setup ()
{
for (actLED=0;actLED<4;actLED++)
{
pinMode(LEDPins[actLED],OUTPUT);
digitalWrite(LEDPins[actLED],HIGH);
LEDuration[actLED]=millis()+random(RandBase+actRandValue);
}
Serial.begin(9600);
}

void loop ()
{
for (actLED=0;actLED<4;actLED++)
{
if (millis()>=LEDuration[actLED])
{
LEDuration[actLED]=millis()+random(RandBase+actRandValue);
}
}
Serial.println(actAnalogValue);
{
}
else
{
Serial.print(actAnalogValue);
Serial.print(" : ");
actAnalogValue=actAnalogValue / 20;
Serial.print(actAnalogValue);
if (actAnalogValue<=500)
{
actRandValue=int(actAnalogValue*-0.7);
}
else
{
actRandValue=int(actAnalogValue*1.5);
}
actAnalogValue=0;
}
}
``````

take a look at line:

``````actAnalogValue=actAnalogValue / 20;
``````

maximum vale of “actAnalogValue” after 20 reads is 20460. When I divide by 20 - I should have avarage from this twenty reads. But it seems that division produce result shifted by one place of decimal separator.

20460 divided by 2 gives 102300 - like 20460 / 0.2
20460 divided by 20 gives 10230 - like 20460 / 2
20460 divided by 200 gives 1023 - like 20460 / 20 (thats what I’m looking for)

I pasted whole code, because maby I’m doing something wrong (not initialized something or other “need to” stuff).

The same result is produced by 0022 version of Arduino.

Does anyone have any idea whot I’m doing wrong ?

The code seems to work fine for me:

11050/20 = 552.

11027/20 = 521

If I connect the ADC to +5v, I get:

0 1023 2046 3069 4092 5115 6138 7161 8184 9207 10230 11253 12276 13299 14322 15345 16368 17391 18414 19437 20460 20460/20 = 1023

Strange. I have got:

391 782 1172 1563 1954 2345 2736 3127 3518 3909 4300 4691 5082 5473 5864 6254 6645 7036 7427 7818 7818 : 3900

Later I will put bootloader into another 328 chip and try again - mayby actually installed chip is broken ...

Finally I found an error and ... I'm so embarrased.

Each turn of the for statement end with Serial.print(actAnalogValue); and begins with Serial.println(actAnalogValue);

It means that ending zeros on each end of result of dividing comes not from dividing, but from next turn of the loop. I discowered this after adding "delay() " statement at the end of the program and suddenly whole problem becomes clear ;)

I'm so sorry for wasting Your time and thans a lot for fast response.