Hello, i have a cat feeder project where i want to adjust the amount of portion served with potentiometer. Portion is regulated by amount of seconds the motor is spinning, so i mapped potentiometer 0 to 1023 value from 15000ms to 50000ms. So i can adjust that from 15 seconds to 50 seconds. But on my serial display I cannot see full value, it gets around 32000 and then goes back to zero up until the very far point of the potent is reached. If I use my code with smaller number, 0 to 10 as an example, it works fine. Not much code is needed here, so i pasted only part of it. What can i do to have potentiometer value mapped correctly between 15s and 50s. Thanks
val = analogRead(potent_pin);
val = map(val, 0, 1023, 0, 50000);
val = constrain(val, 0, 50000);
val = val/1000;
Serial.println(val);
I guess val is an integer. the range for an integer on a 8-bit processor is from -32,768 .. 32,767. You don't mention the board that you're using so this is just a guess.
"Rolling over" variables is a common problem (bug) and it can be confusing because of the two's complement representation of signed variables.
It can be obvious if things go wrong at 256 or around 32,000 or around 64,000 but it's tricky If you are using the rolled-over variable "indirectly" in a formula and you just see the result acting screwy.
If I want to convert 0 to 1023 using integers, I'd use longs and calculate using microvolts and have 3 places to lose in divides while holding millivolts.
cast long reading * 5000000L uV / 1023000L = long mV never > 5000
Volts is value / 1000 and mV is value % 1000, the remainder.
Dividing the analog read by 1023 is a cheat well within the tolerance of the device that before hardware error (that could by chance be right) never measures the top interval, /1023 assumes the 1 interval and the ADC has a 2 interval accuracy.
Rolling over can be made into a problem. We cross rollover when calculating time intervals but as with rollover we have to use variables that can store the biggest values you might use. You can cast 16 bit values to 32 bit in an equation, when scaling 16 bit I x 16 bit J / 16 bit K where K >= I, the answer will fit in 16 bits while the calculations are done safe in 32 bits.
Before internet, I was given or mainly bought tech manuals to learn from. And before the code was a chapter about variables and what the bits represented including floats. But that was after punching FORTRAN on cards in an intro course that taught much less. It was only when I had hardware that tech manuals became useful to me.
Add Serial.print()s when things don't work as expected:
int val = 1023;
val = map(val, 0, 1023, 0, 50000);
Serial.println(val);
val = constrain(val, 0, 50000);
Serial.println(val);
val = val/1000;
Serial.println(val);
(unexpectedly?) prints:
-15536
0
0
because 50000 is larger than the maximum int of 32767. Which in your code would then get constrained to 0, and then divided by 1000 to produce 0;