Quantcast
Channel: SparkFun Electronics Comments
Viewing all articles
Browse latest Browse all 44542

Josh_Hawley on COM-11310 - Toggle Switch and Cover - Illuminated (Red)

$
0
0

Thanks for writing this! I was having quite a bit of trouble with this switch until I read this. I wrote a little sample code to go with your comment. It will blink the switch LED, and also turn on/off another LED using a third pin when the switch is toggled. I thought it might help others. In addition to your wiring listed above another LED will need to be hooked up to another output pin.

// define pin constants
#define SW_LED_PIN 2
#define SW_IO_PIN 3
#define OUT_LED_PIN 4

void setup()
{
  pinMode(SW_LED_PIN, OUTPUT);   // LED on the top of the switch
  pinMode(SW_IO_PIN, INPUT);         // reading the state of the switch
  pinMode(OUT_LED_PIN, OUTPUT); // used to turn on and of another LED based on switch state
}

boolean switch_LED_State = false; // used to blink the LED on the switch
void loop()
{
  if (digitalRead(SW_IO_PIN) == HIGH) // read the state of the switch
  {
    digitalWrite(OUT_LED_PIN, HIGH); // if switch is on, turn on the LED
  }
  else
  {
    digitalWrite(OUT_LED_PIN, LOW); // if switch is off turn off the LED
  }

  delay(75); // control the rate of blinking
  if (switch_LED_State)
  {
     // note that the HIGH/LOW state is reversed from the LED state
    switch_LED_State = false;
    digitalWrite(SW_LED_PIN, HIGH);
  }
  else
  {
     // note that the HIGH/LOW state is reversed from the LED state
    switch_LED_State = true;
    digitalWrite(SW_LED_PIN, LOW);
  }
}

EDIT: Added some documentation… shame on me for posting code without


Viewing all articles
Browse latest Browse all 44542