Hello Ross,
Since you have only a single switch input, and you require to monitor and time both the on and off states, the code will probably be more straightforward if you don't make use of the KBI module, but simply monitor the switch state by testing the input state of the pin.
For each switching event, there will need to be a debounce interval (perhaps 25-50ms), followed by a switch timeout interval of say 500ms. These timing periods would need to be applied to both states of the switch. Timeout would occur both for a "held" switch, and following switch release.
The easiest way to implement these timing periods is probably as an integral number of TIM overflow cycles. Enable TIM overflow interrupts, with an overflow period in the vicinity of say, 5 ms. This timing is not critical, but would allow both intervals to be handled with an 8-bit counter. Within the ISR code, the counter would be simply decremented, unless its value was already zero.
From within the main loop, a timeout period is started by setting the counter to the required value, and timeout will have occurred when the counter becomes zero.
It seems that, if one or both lights are already on, it might be a good idea to require that the switch be held on for greater than the timeout period, before the turn-off occurs.
The operation of the code within the main loop would effectively become a simple "state machine". The following is a possible sequence of events.
- Assuming the switch is currently off, wait for an on state, and then delay for the debounce period. If the switch has reverted to off, start over again to wait for an on state.
- If the debounced on state is present, start the 500ms timeout period, and then within a tight loop, test for either timeout (switch hold), or switch off. If switch hold occurs, turn on #1 light, and then wait for the switch to be released.
- If the switch is released within the timeout period, apply a debounce period, followed by a further 500ms timeout period. If timeout should occur, turn on #1 light.
- However, if the switch becomes again active, wait a further debounce period, and then turn on both lights. Then wait for the switch to be released.
Steps 1 and 2 would be followed for the turn-off sequence. If the switch is released prior to timeout occurring, there would be no action.
Regards,
Mac