We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
Hello, I have beginners problem with getting to work volatile variable. Trying to get reusable function for debouncing and detecting key_up state for all declared keys but can't get it to work as expected. Situation is as follows:
declaration:
sbit key1=P3^7; sbit key2=P3^6; bit key_up(volatile bit key);
usage:
if (!key_up(key2)) { green=~green; } if (!key_up(key1)) { ... do something... {
function:
bit key_up(volatile bit key) { if (key==0) // check if key is pressed { delay1ms(20); // debounce if (key==0) // really pressed { while(key==0) // hold until pressed { ; } // key is released delay1ms(20); // debounce when key released if (key!=0) // check if still released { key=1; // reset key return 0; // return key is up } } } return 1; // key was not pressed at all }
Program compiles with no errors but problem is that variable 'key' is not rechecked inside a function and I think it should be if it is declared 'volatile'. Please help to get my function working.
Seem's you are right. But Ok, here is enchanced version with shortened variable names :) of my tunnel which becomes uglier with every new version :) Thanks for a revision.
bit debounce(unsigned char pKey) { bit localKey; if (pKey=='1') localKey=key1; if (pKey=='2') localKey=key2; if (localKey==0) { delay1ms(20); if (pKey=='1') localKey=key1; if (pKey=='2') localKey=key2; while(localKey==0) { if (pKey=='1') localKey=key1; if (pKey=='2') localKey=key2; } delay1ms(20); if (localKey!=0) return 0; } return 1; }
As a beginner in first steps with microcontroller I have never need to check multiple buttons at once but I mostly understand those bunch of useful tips on how to set a problem in such situation.
Thanks for that!