# One action per switch press with microcontroller

I've been trying to find out a way for quite a while now on how to have a momentary switch only latch for a short time, and then unlatch. I can't seem to wrap my head around what to do. If this helps, I was going to work on a laser tag gun, so when the trigger is pressed, only a short burst happens once, not continually. Thanks in advance, sorry if this has been posted about, I simply can't find any resources about it.

• Switch on, delay, switch off. Easy. Nov 6, 2015 at 20:15
• Look into Interrupts and Timers on your chosen microcontroller platform. The usual way to do this is an interrupt triggered by button press, which sets a flag (or simply turns on the diode), and sets a timer interrupt to unset that flag after a predefined delay. You can do this without interrupts using a polling loop and busy wait delays, but it prevents you from using the MCU for other tasks while that is happening (or responding to input) Nov 6, 2015 at 20:16
• The issue I've had with that in trying to do that in the past, is that the micro controller still reads the input as pressed, and won't turn off. I'm just a little confused Nov 6, 2015 at 20:16
• Of course the input is pressed, if it is actually pressed. You want to detect the transition. Nov 6, 2015 at 20:17
• Ah ok, thanks crasic. That helps a lot. I understand how do use both, I just wasn't sure the approach. Nov 6, 2015 at 20:17

Here's some simple pseudo code that is not interrupt based and is not debounced.

void main( void ) {
uint8_t last_state = 0;
uint8_t btn_state = 0;

for(;;) {