Headlamp / flashlight programming - Use switch case? - Need advice

Hi,

Im makeing a headlamp from scratch with several functions.
The headlamp will have several light sources controlled by an Atmega328 and two push buttons.

Push button 1:

  • First press: LED 1 at 50% brightes
  • Second press: LED 1 at 100% brightnes
  • Third press: LED 2 at 50% brightnes (and LED 1 off)
  • Forth press: LED 2 at 100% brightnes
  • Fifth press: LED 1 and 2 at 50%
  • Sixth press: LED 1 and 2 at 100%
  • Seventh press: All off

Push button 2:

  • First press: Show battery level for 5 seconds (5 LEDs connected to 5 digital outputs, and battery level connected to one analog input)
  • Second press: RGB RED at 100% (and all other LEDs off)
  • Forth press: RGB GREEN at 100% (and all other LEDs off)
  • Fift press: RGB BLUE at 100% (and all other LEDs off)
  • Sixth press: All off

I also want Push button 1 to turn off all "Push button 2 lights" when pressed and vice versa.

Excample:
Push button 1 is pushed two times turnes LED 1 on at 100%, but if I then push button 2 one time, LED 1 turns off and first "case" for push button 1 starts (battery indicator).

I have made a code using switch case and it works fine for one push button, but I dont know how to add a secon button and code it like I described over. Also if I use "Digital High - delay Digital Low - delay" in a case I cant jump to the next case using the pushbutton?

Is switch case the correct thing to use here, or should I use something else?
Can I use PWM in a case to set a LED at 50%?

Thanks

I suggest you create a class to encapsulate the button actions and implement it using the state pattern. That way, on every button press you just call Button.doAction().

Let's show that code :slight_smile: PWM works fine everywhere :slight_smile:

And for counting presses, I assume you already implemented state change? Next would be to make a state machine. To make it easier I would make two state machines and link them later. (aka, let them both react to both buttons).

To make reading a button (including state change detection and debounce) I can suggest the ounce2-library.

Yes, you can encapsulate it all in a class but for now I don't really see the advantage (for a single project) of it.

HansiFansi:
I also want Push button 1 to turn off all "Push button 2 lights" when pressed and vice versa.

Does this mean also setting the button 2 state machine to its initial state?