søndag den 23. oktober 2011

Rotary selector switch for Arduino using only one analog pin

Arduino is a great developer platform, but you quickly run out of pins, especially the digital ones. And you rarely use all 6 analog pins in an application. This selector switch uses only one analog pin.

The switch is a standard rotary selector switch with 12 positions:



In this example, I have build the switch with 8 x 1K/5% resistors and set the rotary selector switch to 8 positions. The easiest way to build it, is to solder the resistors directly onto the rotary selector switch.

Here is the diagram using 8 x 1K resistors as voltage divider:



Here is the necessary Arduino code for decoding the position:
int selectorPin;
int numOfSteps;
float divider;

void setup() 
{
  //pin for selector switch
  selectorPin = 0;

  //number of physical steps on the rotary switch
  numOfSteps = 8;
 
  //divider for decoding analog input
  divider = 1024.0 / numOfSteps; 
}

void loop() 
{
  //divide and round the input as float
  float selectorValueFloat = round(analogRead(selectorPin) / divider);
  
  //cast to integer for e.g. indexing arrays
  int selectorValue = selectorValueFloat;
}

Now we have an integer value for the position of the rotary selector switch. Hope you like it.



3 kommentarer:

MikMo sagde ...

Hej Jesper.

Tak for dette smarte trick.
Har rettet et par fejl i din kode.
Du manglede at erklære variable i topen, og så skulle denne linie:

round selectorValueFloat = round(analogRead(selectorPin) / divider); selectorValueFloat = round(analogRead(selectorPin) / divider);

have været:

float selectorValueFloat = round(analogRead(selectorPin) / divider); selectorValueFloat = round(analogRead(selectorPin) / divider);

Venligst
Mikael Mørup

Jesper Eklund sagde ...

hej Mikael

Ja, det har du da ret i. Hermed rettet.

hilsen Jesper

Natacha Watson sagde ...

Nice tips thanks! I hope I can do that with one of these rotary switches: http://www.directindustry.com/cat/switches-relays/switches-rotary-switches-coded-switches-AF-766.html

Om mig

Jeg er født på Frederiksberg 1966 af min mor. Nu bor jeg bare på Vesterbro. Jeg bærer briller.