Go Down

Topic: Analog read returning value higher than 1023? (Read 2414 times)previous topic - next topic

Fergo

May 09, 2010, 03:02 amLast Edit: May 09, 2010, 03:02 am by Fergo Reason: 1
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):

Code: [Select]
`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

Imahilus

#1
May 09, 2010, 03:18 amLast Edit: May 09, 2010, 03:19 am by Imahilus Reason: 1
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?

PaulS

#2
May 09, 2010, 03:22 am
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?

Fergo

#3
May 09, 2010, 05:49 amLast Edit: May 09, 2010, 05:50 am by Fergo Reason: 1

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:

Code: [Select]
`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

mowcius

#4
May 09, 2010, 11:26 am
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

Mowcius

Go Up