I found the solution!
// This will store the last known state of the button
const int buttonPin = 6; // change as per your button attached.
//
const int ledPin = 4;
int x = 1;
// variables will change:
int buttonState = 0;
int oldButtonState = HIGH;
void setup() {
// initialize the LED pin as an output:
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
}
void loop()
{
// Get the current state of the button
int newButtonState = digitalRead(buttonPin);
// Has the button gone high since we last read it?
if (newButtonState == HIGH && oldButtonState == LOW) {
if (x == 0) {
// Toggle on
digitalWrite(ledPin, HIGH);
x = 1;
delay(500);
} else {
// Toggle off
digitalWrite(ledPin, LOW);
x = 0;
delay(500);
}
}
// Store the button's state so we can tell if it's changed next time round
oldButtonState = newButtonState;
}
My main issue is that I did not store the new statement so it always change.