Ive been having issues with the coding to initiate a blinking LED using a push button. when there is no code for reading the button input the LED blinks as required (using built in LED at the moment), using this code:
start in the off state, start blinking when button is pressed, stop blinking next time button is pressed
something else?
Also, need to know if the button input is low when pressed, or high when pressed.
Showing us your wiring would help, though it's a simple circuit.
In your second example you have 4 nested if, is too much they won't do what you want ( I mean if you are learning this is a complicated way of doing things ).
An easier way is simply modify your first sketch, which is working as you want, before the digitalwrite check the status of the button, if it is not pressed set ledstate to off ( don't know if is high or low )
As @camsysca says how is your circuit connected? It seems that you have the button that connect the input to high when pressed, but this means that you have a floating input when the button is not pressed ( if you don't add a pulldown resistor ), never leave an input floating ( it means not connected to anything ).
You could simply enable the input_pullup in the setup function, connect the button so that it shorts to ground, when pressed, and now the button input state is high when not pressed and low when pressed.
thank you, this makes sense. I changed my circuit to have a pull up resistor and check button status and it seems to work as intended now. Here is what I've changed it to:
const int pushbutton = 4;
unsigned long buttonmillis = 0;
const int buttoninterval = 100;
int buttonstate = LOW;
unsigned long previousmillis = 0;
const int interval = 500;
int LEDstate = LOW;
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(pushbutton, INPUT_PULLUP);
}
void loop() {
unsigned long currentmillis = millis();
if (digitalRead(pushbutton)==LOW){
buttonstate = HIGH;
}
if(buttonstate == HIGH){
if(currentmillis - previousmillis >= interval) {
previousmillis += interval;
if (LEDstate == LOW) {
LEDstate = HIGH;
} else {
LEDstate = LOW;
}
}
digitalWrite(LED_BUILTIN, LEDstate);
}
}