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.

Microcontroller Programming » Question About Interrupts

May 22, 2011
by mike49823
mike49823's Avatar

I recieved my NerdKit last week and am having fun learning. Trying to understand interrupts I wrote the following code. It works in that the red led (PC5) flashes and when I use a jumper to connect PC2 to ground (or disconnect the jumper sending PC2 High) the green led (PC4)flashes twice. However the green led always flashes twice rather than just once as I would expect. Any insight would be greatly appreciated. Mike

ISR(PCINT1_vect){

//Flash Green once

PORTC |= (1<<PC4);

delay_ms(200);

PORTC &= ~(1<<PC4);

delay_ms(200);

}

int main() {

// LED as output

DDRC |= (1<<PC4);//Green

DDRC |= (1<<PC5);//Red

// PC2 as Input

DDRC &= ~(1<<PC2);

//PC2 pull up resistor on

PORTC |= (1<<PC2);

PCICR |= (1<<PCIE1);

PCMSK1 |= (1<<PCINT10);

//global enable interrupts

sei();

// PC3 as Input

DDRC &= ~(1<<PC3);

//PC3 pull up resistor on

PORTC |= (1<<PC3);

// Infinite loop

while(1) {

//Flash Red

PORTC |= (1<<PC5);

delay_ms(200);

PORTC &= ~(1<<PC5);

delay_ms(200);
}

return 0; }

May 22, 2011
by bretm
bretm's Avatar

When you connect or disconnect the jumper, it bounces. The interrupt fires once, starting the green blink, and then fires multiple times while the 400ms worth of delays is happening. Only one of those subsequent bounces is remembered by the MCU because it only has one bit to keep track of those things. So as soon as the first interrupt is done, a second one is fired off. The bouncing has stopped by then so it doesn't happen a third time.

May 22, 2011
by mike49823
mike49823's Avatar

Thanks, I really appreciate the response. Regards Mike

May 25, 2011
by huzbum
huzbum's Avatar

Bretm has it correct. The micro controller is so much faster than us. You couldn't possibly make a solid connection fast enough that it doesn't look like multiple on-off-on states. I set up a counter once, and each time I touched two wires together it counted anywhere between 2 and 200 or more per touch.

Try using a diode and/or capacitor. I think a diode worked for me, but I think a capacitor would work better. You could also clear the interrupt flag while the interrupt is running to prevent it from running again.

Post a Reply

Please log in to post a reply.

Did you know that NerdKits make a great gift? Learn more...