Example Code for Arduino-Read Switch Position

Last revision 2026/01/07

This article offers a comprehensive guide to reading switch positions with Arduino, featuring sample code, hardware setup, and wiring diagrams to achieve precise position detection for various switches.

Wiring Diagram

Rotary_Switch_Module_Connection_Diagram1.png

Other Preparation Work

The same position value of each switch is different.So, by sample code 1, the each position value can be read, and modify the appropriate reference value in the following code.

Sample Code

/*
 # This Sample code is reading Switch position.
 */
int adc_key_val[12] ={630,680,750,810,845,860,890,905,920,940,950,980};
int NUM_KEYS = 12;
int adc_key_in;
int key=-1;
int oldkey=-1;
void setup()
{
  Serial.begin(9600);                   // 9600 bps
}
void loop()
{
  adc_key_in = analogRead(0);            // read the value from the sensor
  key = get_key(adc_key_in);             // convert into position
  if (key != oldkey)                     // if a position is detected
   {
    delay(50);  // wait for debounce time
    adc_key_in = analogRead(0);          // read the value from the sensor
    key = get_key(adc_key_in);           //convert into position
    if (key != oldkey)
    {
      oldkey = key;
      if (key >=0){\
        switch(key)
        {\
           case 0:Serial.println("S1 OK");
                  break;
           case 1:Serial.println("S2 OK");
                  break;
           case 2:Serial.println("S3 OK");
                  break;
           case 3:Serial.println("S4 OK");
                  break;
           case 4:Serial.println("S5 OK");
                  break;
           case 5:Serial.println("S6 OK");
                  break;
           case 6:Serial.println("S7 OK");
                  break;
           case 7:Serial.println("S8 OK");
                  break;
           case 8:Serial.println("S9 OK");
                  break;
           case 9:Serial.println("S10 OK");
                   break;
           case 10:Serial.println("S11 OK");
                  break;
           case 11:Serial.println("S12 OK");
                  break;
        }
      }
    }
  }
 delay(100);
}
// Convert ADC value to key number
int get_key(unsigned int input)
{
    int k;
    for (k = 0; k < NUM_KEYS; k++)
    {
      if (input < adc_key_val[k])
     {
            return k;
        }
   }
       if (k >= NUM_KEYS)k = -1;
       return k;
}

Was this article helpful?

TOP