NerdKits - electronics education for a digital generation

You are not logged in. [log in]

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
DrNoExpert's Avatar

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
N3Roaster's Avatar

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:

counter += n; // Replace n with how much you want to increment the counter

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
DrNoExpert's Avatar

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
N3Roaster's Avatar

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:

if(the button is pressed) {
    increment the counter;
    while(the button is pressed) {
        do nothing;
    }
}

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
DrNoExpert's Avatar

I get it. Thanks a billion.

Post a Reply

Please log in to post a reply.

Did you know that you can use printf and scanf functions to talk to your computer from your USB NerdKit? Learn more...