Hi! Hope you're enjoying this blog. I have a new home at www.goldsborough.me. Be sure to also check by there for new posts <3

Monday, October 14, 2013

Reading potentiometers more efficiently

It recently occured to me when sending MIDI Control Changes with my Microcontroller that having a potentiometer spew out values continuously is quite impractical when you don't want it to interfere with other potentiometers. I came up with a swift solution that could be packed in a function or so.

int nstate;
int state;

void setup()
  //For demonstration I'll just use Serial

void loop()
  nstate = analogRead(0)/8; //Read - Divide by at least 2 to prevent floating
  if (nstate != state)
  state = analogRead(0)/8; //Read again

  delay(10); //Only to stabilize Serial printing

So what I did here is I just created two variables into which I read the potentiometer's state at two different times (I don't know how fast the processor is but the time difference is probably in the microseconds) and if in that time the potentiometer was changed, the second reading will not match the first one anymore and the message is sent/ the action is executed. In my opinion an awesome way to:

  1. Keep delay() out of the game (Delay shuts down the entire system, not so practical)
  2. Get values only when the potentiometer is actually used, this is a huge advantage to just reading the values continously and changing something in "real time" (I hope you understand what I mean). E.g. when sending MIDI signals, you don't have the knob in your MIDI software always getting signals, rather only when a change actually occured. 

Attention! I recommend dividing the range of the potentiometer (0-1023) by at least 2 (you do so anyway when sending MIDI, because it only ranges from 0-127). Why? Even when the potentiometer is at rest, the values "float" a little (I hope it's the right term), meaning it might jump + or - 1 even when you're not touching it. I guess that's common for cheaper pots, so to prevent that, you need to divide it by at least 2 (= 0 - 512). Since the values are rounded and aren't as easily moved, the little inaccuracy never really changes the value. So the fewer the steps, the less fluctuation. 

I'm not really good with the words yet, but to give you an example: If a flight of stairs has 1023 steps each 20cm high and you then divide that by two, leaving you with only 512 steps, the steps need to be twice as high to make you complete the same distance. Thus, if you have Parkinson disease and shiver a lot, it's not as easy for you to move up a 40cm step than it is a 20cm one. There you go. The best metaphor in the history of the english language. 

Anyway, I'm probably waffeling already too much for the small piece of code, I'm so thankful for any comments, so please :)

1 comment :