NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.
Support Forum » Increment Counter
January 23, 2010 by DrNoExpert |
for a lot of my projects, i need a counter that goes up by n amount every time i hit a button, and won't go up again until i hit the button again. Can someone please help me. |
---|---|
January 23, 2010 by N3Roaster |
Incrementing a counter by a set amount isn't a problem. Create a variable (say, int counter) to hold the value of the counter. When you want to increment that, just use something like:
Since you want to do this in response to a button press, you would connect a button to an MCU pin and in your program, set that pin as an input. Then your program needs to detect a change in the state of the pin. You can do this either by periodically polling the state of the pin or by setting an interrupt on the pin change. The tricky part (I'm assuming a momentary switch) is that you're really interested in two separate events: both the press of that button and its release. In the case of polling, not taking this into account will have you incrementing your counter very rapidly as the button is still down for arbitrarily many trips through your loop. If you've set an interrupt on the pin change, that will fire on both the press and the release so you'll need to check the state of the pin before incrementing (or not). There are lots of ways to do this and which way you choose may depend on other aspects of your projects. Sections 11–13 of the ATmega168 datasheet should have all the details you need, though I'd recommend reading them in the opposite order as you can get something hooked up and going with just what's in section 13. |
January 23, 2010 by DrNoExpert |
That's what i followed, it continues to go up until i release the button. I want it to go up by n only once until i release the button and press it again. |
January 23, 2010 by N3Roaster |
Right. You're polling the state of the pin, but you're not taking into account the button release. The structure should be along the lines of:
That if portion takes care of detecting the initial press of the button. The while portion stops the program until the button has been released. |
January 23, 2010 by DrNoExpert |
I get it. Thanks a billion. |
Please log in to post a reply.
Did you know that an analog comparator can tell when one voltage input crosses another? Learn more...
|