AdSense

Wednesday, 11 September 2013

Pin Change Interrupt with the ATmega or Arduino

(Deutsche Version) Lots of microcontrollers (e.g. an ATmega168) do not only have external interrupts but also so called Pin Change Interrupts. These interrupts work on all channels. The basic idea is: When something changes at a channel, an interrupt function is called. These interrupts are not as comfortable as the "normal" external interrupts, you only get the information "something changed on some channel" and not which channel or if this channel is now high or low.


I will explain now with the ATmega168 how this works. I use the channels PB0, PD5..7 as interrupt channels. To activate the interrupts, I have to do the following:

PCICR |= (1 << PCIE0)|(1 << PCIE2);

This activates the interrupts for PCINT0 and PCINT2, this means PORTB and PORTD. Now I have to define the channels which shall cause these interrupts:

PCMSK0 |= (1 << PCINT0);
PCMSK2 |= (1 << PCINT23)|(1 << PCINT22)|(1 << PCINT21);


Now you only have to activate the interrupts (sei();). If you use the Arduino development environment, everything until now happens in the setup function. Now you have to define three functions which are called when an interrupt is triggered. They have to have the following names:

ISR(PCINT2_vect)
{
}


and

ISR(PCINT0_vect)
{
}


To find out which channel had an interrupt, you can read the channels and check if something changed. Or if you just have 4 switches, you can easily check which switch is pressed:

int Button0 = digitalRead(8); 
int Button1 = digitalRead(7); 
int Button2 = digitalRead(6);  
int Button3 = digitalRead(5);

No comments:

Post a Comment