Hi guys.
Pretty sure I am doing something very wrong, but I think I need your help putting the finger on what, exactly.
So I have this sketch that reads an analog value from a SAMD21 (Seeed XIAO) pin. After reading it, I want to constrain it to a range smaller than 10bit and subtract the difference to have a number with a minimum value of 0.
I have encountered the following strange behaviour:
The snippet below created (seemingly) random underflows with analogRead values between 0 and 7, where fader_1 will be 65535 (always that, never a different value),
uint16_t fader = constrain(analogRead(potPin), 4, 1023) - 4;
while this works as expected, ie, no underflows:
uint16_t f = analogRead(potPin);
uint16_t fader = constrain(f, 4, 1023) - 4;
I tested the cause by using print statements like this:
Serial.println("//");
Serial.println(analogRead(potPin));
uint16_t fader = constrain(analogRead(potPin), 4, 1023) - 4;
Serial.println(fader);
Serial.println("\\\\");
and got value pairs like 6, 0 and then 6, 65535
or 6, 1 followed by 7, 65535.
No pattern visible in the pairs leading up to the underflow.
How does that even happen? If analogRead is 6, and I constrain it and subtract 4, why does that equal 1 or even 0?
I am being dumb, but I don't know HOW I'm being dumb, which is just the worst.
I suspect it has something to do with typecasting, but honestly, I'm at a loss.
If someone could explain to me exactly what is causing this behaviour, I think that would deepen my understanding of programming.
Thank you very much in advance.