Notifications
Clear all

Basic On/Off switch code

3 Posts
3 Users
1 Likes
495 Views
(@awpologies)
Active Member
Joined: 1 year ago
Posts: 3
Topic starter  

Hi there!

Total beginner here. I just made a simple on/off switch for a LED that "remembers" the state of the LED when the button is released. I laid out a 1k pullup resistor and an output LED on a breadboard and then combined some code examples to end up with this code:

intledPin = 14;
intbuttonPin = 34;


boolbuttonState;
boolbuttonDown;
boolledOn;


voidsetup()
{
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}


voidloop()
{
  // Check the status of the loop (0 = closed)
buttonState = digitalRead(buttonPin);


  // If the loop is closed
if(!buttonState)
  {
    // And if the loop wasn't already closed
if(buttonDown == false)
    {
      // Remember that the loop is closed, change the LED status to the opposite, output the LED status
buttonDown = true;
ledOn = !ledOn;
digitalWrite(ledPin, ledOn);
    }


  }
  // When the loop opens again, forget that the loop is closed
else
  {
buttonDown = false;
  }


delay(100);
}
 
 
I added some comments above the lines of code, to try and understand it better. Could anyone confirm my reasoning here is correct?
 
Also if you know a better / smarter way to make a switch that does the same, I would love to hear it and learn why it's better!
 
Thanks in advance for helping out!
 
-AWPologies
 

   
Quote
Ron
 Ron
(@zander)
Illustrious Member
Joined: 3 years ago
Posts: 4801
 

Try using the Auto Format under Tools in the IDE

Arduino says and I agree, in general, the const keyword is preferred for defining constants and should be used instead of #define
"Never wrestle with a pig....the pig loves it and you end up covered in mud..." anon
My experience hours are >75,000 and I stopped counting in 2004.
Major Languages - 360 Macro Assembler, Intel Assembler, PLI/1, Pascal, C plus numerous job control and scripting


   
ReplyQuote
robotBuilder
(@robotbuilder)
Noble Member
Joined: 4 years ago
Posts: 1796
 

 

 

int ledPin = 14;
int buttonPin = 34;

bool buttonState;
bool buttonDown;
bool ledOn;

void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // Check the status of the loop (0 = closed)
  buttonState = digitalRead(buttonPin);

  // If the loop is closed
  if(!buttonState)
  {
    // And if the loop wasn't already closed
    if(buttonDown == false)
    {
      // Remember that the loop is closed, change the LED status to the opposite, output the LED status
      buttonDown = true;
      ledOn = !ledOn;
      digitalWrite(ledPin, ledOn);
    }

  }
  // When the loop opens again, forget that the loop is closed
  else
  {
    buttonDown = false;
  }


  delay(100);
}

 

 

https://create.arduino.cc/projecthub/SBR/working-with-an-led-and-a-push-button-71d8c1

 


   
darup reacted
ReplyQuote