Analog read returning value higher than 1023?

Hello everyone.

I'm working on an eDrum project and I'm getting some weird results. I'm using the code below to convert the 0-1023 range of the analog input into a 0-127 range (needed to work with MIDI):

hitavg = analogRead(pin); 
hitavg = 127 / (1023 / hitavg);

For some reason, sometimes I get a resulting "hitavg" of 254 and 255, which is impossible unless the analog read is more than 1023. Is it possible? Am I doing something wrong?

Thanks,
Fergo

How can it return value's in the 250's, if you're mapping it to 0~127?
And have you tried printing the value before you map it?
Also, did you consider the map() function?

128 = 1024/8. So, to map the 0 to 1023 range to 0 to 127, just divide by 8.

What happens in you code if the analogRead returns 0? 1023/0 is an error.

How do you know that hitavg is 254 or 255? What is hitavg before the strange manipulation?

Thanks for the answers.

The problem seems to be with division by zero or negative numbers (guess arduino uses two's complement for that, right?). I implemented some error checking and now it's working fine.

I can't just divide by 8 because that's a "preliminary" code. The I actually use is this one:

hitavg = 127 / ((1023 - threshold) / (hitavg - threshold)

If hitavg is equal or less than the threshold (which can occur in my code), I get a negative number and if it's in two's complement, that explains why I'm having 255 as a result in the software I'm using as the serial monitor.

Thanks!

Fergo

I find that constrain can be useful in situations like this to avoid negatives. You can also convert the negatives to positive if wanted by asking if it is less than 0, if so then multiply by -1.

Mot sure if any of that is helpful though as I don't quite fully understand what you want to do with the numbers but hey :stuck_out_tongue:

Mowcius