Notifications
Clear all

Basic On/Off switch code

3 Posts
3 Users
1 Likes
705 Views
(@awpologies)
Member
Joined: 2 years 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)
Father of a miniature Wookie
Joined: 3 years ago
Posts: 6911
 

Try using the Auto Format under Tools in the IDE

First computer 1959. Retired from my own computer company 2004.
Hardware - Expert in 1401, and 360, fairly knowledge in PC plus numerous MPU's and MCU's
Major Languages - Machine language, 360 Macro Assembler, Intel Assembler, PL/I and PL1, Pascal, Basic, C plus numerous job control and scripting languages.
Sure you can learn to be a programmer, it will take the same amount of time for me to learn to be a Doctor.


   
ReplyQuote
robotBuilder
(@robotbuilder)
Member
Joined: 5 years ago
Posts: 2042
 

   
darup reacted
ReplyQuote