0

I want to let the led blink for 3 seconds then 2 seconds then one second using the button one time and without using if/else

void setup() {
 // put your setup code here, to run once: 
 pinMode(5, INPUT); 
 pinMode(6, OUTPUT);
} 
void loop() { 
 // put your main code here, to run repeatedly: 
 digitalRead(5, HIGH);
 digitalWrite(6, HIGH); 
 delay(3000);
 digitalWrite(6, LOW);
 digitalWrite(6, HIGH); 
 delay(2000); 
 digitalWrite(6, LOW); 
 digitalWrite(6, HIGH); 
 delay(1000); 
}
asked Sep 23, 2019 at 5:57
10
  • Why don't you want to use if/else? Or is this a school assignment? Commented Sep 23, 2019 at 6:07
  • it is a school assignment actually Commented Sep 23, 2019 at 6:08
  • 1
    switch case is your friend ;) Commented Sep 23, 2019 at 6:30
  • 1
    Switch is an alternative to if --- unless are you at the "interrupts" section of your class... Commented Sep 23, 2019 at 8:20
  • 1
    @FilipFranik I agree and did not advocate that. You definitely don't want to include any lengthy operations in an interrupt service routine. My comment was more of a suggestion that switch is an obvious alternative to using an if - but it is also possible that the OP was at the "interrupts" section of their class and thus would require a completely different approach to the serial code as posted in the question - and as you suggest, definitely should not be using delay. Hopefully that was also taught in the class... I should perhaps in hindsight been more clear in my original comment. Commented Oct 20, 2020 at 9:15

3 Answers 3

1

As the required operation is finite and short, you can just hard code the sequence.

answered Sep 23, 2019 at 11:27
1

You could you simple inversion of boolean variable to set state of LED.

const int LedPin = 5;
bool ledState = true;
// in your loop
// bool will be transformed from true to 1 (HIGH)
digitalWrite(LedPin, (int)ledState);
// invert LED state to be false
ledState = !ledState;
// false -> 0 (LOW)
digitalWrite(LedPin, (int)ledState);
answered Oct 19, 2020 at 7:00
1

Ternary operator maybe helpful. [Reference]

answered Nov 18, 2020 at 11:52
1
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. Commented Nov 18, 2020 at 12:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.