this causes problem.. sometimes it works but sometimes i need to hold the button for 2 seconds and release to break out of the loop..
this problem does not happen if i have a delay of.. say.. delay_ms(10); (with smaller delay_ms, i can just push the button once and it breaks out of the loop everytime)
What should i do to solve the issue? and still retaining a delay_ms(300) or higher..
In the shown code, key input is at least ignored for a dead time 600 ms. When you say it's even 2 seconds, then there's probably more succeeding dead time without port test.
This behavior is simply by design of the code. Waiting for 600 ms (or more) and wanting to detect key presses in between can't work this way.
There are many ways to make it differently. Personally I would get rid of long delays with delay_ms statement. Instead have an interrupt based tic timer and perform any long delays by counting tics and performing all necessary housekeeping like key tests meanwhile. Or shift the key input to an interrupt routine and set a flag for the key press. Or use interrupt on change for the keyboard input.
In the shown code, key input is at least ignored for a dead time 600 ms. When you say it's even 2 seconds, then there's probably more succeeding dead time without port test.
This behavior is simply by design of the code. Waiting for 600 ms (or more) and wanting to detect key presses in between can't work this way.
(Thought invoked by FvM's connect about using interrupts)
I don't know what 'btn1' is (i.e. a variable that is set by some other code or a macro that expands to a port pin reference) but, if it is driven by a mechanical button or switch, then it needs to be debounced. Contact bounce is one of the reasons why it is almost never a good idea to connect a switch/button to an interrupt source directly.
Susan
Agreed. My usual options are
- scan the switch in timer interrupt with a period > bounce time.
- use hardware interrupt, e.g. PIC port change with a dead time after first occurrence.