turn on/off with one button

Hey i need help please
I would like to have one button to turn on and off a led or somthing else. So a button that changes position every time you press it

const int buttonPin1 = 2;

const int Relay1 = 8;

void setup() {

pinMode(buttonPin1, INPUT);

pinMode(Relay1, OUTPUT);
}
void loop() {

if (Relay1 == LOW){
if (buttonPin1 == HIGH){
delay(500);
digitalWrite(Relay1, HIGH);

}}else{
if (Relay1 == HIGH){
if (buttonPin1 == HIGH){
delay(500);
digitalWrite(Relay1, LOW);

}
}}}

Test_1.ino (402 Bytes)

You're missing digitalRead on each of the input pins.

if (buttonPin1 == HIGH){

buttonPin1 is defined as 2. HIGH is defined as 1. 2 will never equal 1.

if (Relay1 == LOW){

Same problem here.

In addition, you should check out the state change example. Right now your code will cycle through the loop function a few thousand times per second. You won't be able to take your finger off the button fast enough to keep it from rapidly cycling between on and off for the entire time the button is held down.

This example does exactly what you want. https://www.arduino.cc/en/Tutorial/Debounce It is even comes with the installation of the IDE, no need to type it or copy it from the web.