Momentary push button and loops

Hi,

New to arduino and stuck!!

Wondered if anyone could help me. I have the code below but cant get it to do what i want!

I basically want it so that when i push the button it stays in the first part of the loop with the LED flashing on and off for a set amount of time. Obviously as its a momentary switch it only does the first loop once as the button goes low straight away again.

const int pushButton = 12;     
const int ledPin =  13;      


int buttonState = 0;         

void setup() {

  pinMode(ledPin, OUTPUT);
  pinMode(pushButton, INPUT);
}

void loop() {

  buttonState = digitalRead(pushButton);
  
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin, LOW);
    delay(200);
  }
  else {
    
    digitalWrite(ledPin, LOW);
  }
}

Any help very much appreciated.

Thanks,
Paul

try this (untested) :

const int pushButton = 12;     
const int ledPin =  13;     

unsigned long timeout ;

// int buttonState = 0;         

void setup() {

  pinMode(ledPin, OUTPUT);
  pinMode(pushButton, INPUT);
}

void loop() {

  // button HIGH when pressed !
  if ( digitalRead(pushButton) == HIGH ) { timeout = millis() + 4000 } ;  // 4 secs.
 
  if ( timeout > millis() ) {
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin, LOW);
    delay(200);
  }
  else {
   
    digitalWrite(ledPin, LOW);
  }
}

Got it working how I want now!

Thank you very much for your help 6v6gt. :slight_smile: :slight_smile:

Hi guys and gals

I've a really simple problem that I just cannot seem to get my head around !

I'm looking for a sketch that :

On startup gives a PWM output of 50

On the push of a button (rising edge) the PWM output rises at a definable rate to 255

Then after a set time or the button is released the PWM value drops at the same rate as before down to 50

That's literally it and I just can't work it out ! - major mind block happening right now !

Any help would be greatly appreciated :slight_smile:

Sam

In principle it is simple.

You've got an arduino or similar configured with a push button on a digital pin, and a LED connected to one of the PWM pins so you can test it ?

Then start by writing a sketch to which uses analogWrite() to write a value of 50 to the LED pin.
When you've got that far, then in the loop, write a message using Serial.print() if the button is held in and another message if the button is not being held in.
Then start thinking how you'd increment a counter when the button is held in ( myCounter++ ) and how you'd decrement the counter during the period the button is released (myCounter--). Then maybe, try to apply that to the analogWrite() statement.
Ask for help if you get stuck at a specific point.