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); }
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
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