Hi! Hope i can find some help for my project. Basically I'm matching the movement of a log potentiometer (slider) to the change of led on a led strip using specific values. But the problem seems to be that when at the "extermes" of the potentiometer, so moving from first to second and from second-last to last, there might be little jumps. So I'm asking if anyone can help me fixing this little problem. I'm also attaching the code part regarding the ranges, if needed.
Thanks in advance!
int mapToRange(int value) {
if (value >= 0 && value <= 26) return 0;
else if (value >= 27 && value < 53) return 1;
else if (value >= 53 && value < 285) return 2;
else if (value >= 285 && value < 530) return 3;
else if (value >= 530 && value < 780) return 4;
else if (value >= 780 && value < 970) return 5;
else if (value >= 970 && value <= 998) return 6;
else if (value >= 999) return 7;
}
What about just averaging a number of readings ?
There's a few other schemes too, which I've tried, but this is light-weight and easy to understand. It's quite reusable in different sketches because you can adjust the number of readings and delays to suit other timing requirements.
int i; // used in for loops
float Sensor_Average;
const int Sensor_Readings = 10; // number of repeated sensor readings to average, maximum 30
const int Sensor_Delay = 5; // ms delay between repeated sensor readings
void setup()
{
} // end void setup
void loop()
{
Value = Get_Sensor_Val(Pot_Pin);
// now call your mapToRange here
} // end void loop
int Get_Sensor_Val(byte Sensor_Pin)
{
// Arithmetic average
Sensor_Average = 0;
for (i = 1; i <= Sensor_Readings; i++)
{
Sensor_Average += analogRead(Sensor_Pin);
delay(Sensor_Delay);
}
Sensor_Average = Sensor_Average / float(Sensor_Readings);
return int(Sensor_Average + 0.5);
} // end void Get_Sensor_Val
If you really mean a LOG potentiometer (Ataper), you could create a lookup array or formula to flatten out the curve, or simply replace it with a LINEAR (Btaper) pot.
The contacts in the pot may be a bit dirty, and occasionally give you a bad reading.
Are you using any other analog inputs? Alternating between analog inputs might cause errors in the reading, a common technique is to read the analog input twice, ignoring the first reading.
Incidentally, your code can be written in a much simpler way, since an "else if" statement will never be reached if the previous if condition is true.
int mapToRange(int value) {
if (value < 27) return 0;
else if (value < 53) return 1;
else if (value < 285) return 2;
else if (value < 530) return 3;
else if (value < 780) return 4;
else if (value < 970) return 5;
else if (value < 990) return 6;
else return 7;
}