/*
Filename: intEx1
Author:
Date:
Description:
Code to test external interrupts: every time PCINT0 is triggered,
the red shield LED7 is toggled
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
//user-defined function for the initialisation of the external interrupt PCINT0
volatile unsigned char Pin0Change = 0; //global variable, initialised to False
volatile unsigned char buttons = 0b00000000; // Global variable for debugging code
int main(void)
{//--- User initializations.
Serial.begin(115200);
DDRB = 0b11111100; // NOTE: configure only PB0 (PCINT0) as input and
PORTB = 0b00000011; // activate only its pull up resistor, and turn off LED
DDRA = 0xFF; // All Port A configured as output
//SREG = SREG | 0x80;
pcint0_init(); // initialise registers to enable PCINT0
while(1)
{
if(Pin0Change) // Check if pin change detected
{
//buttons=0b11110000| buttons;
Serial.println(buttons);
switch(buttons)
{
case 0x01:
Serial.println("button 1");
// Pin0Change=0;
blink_led();
break;
case 0x02:
Serial.println("button 2");
blink_led();
break;
case 0x04:
Serial.println("button 3");
blink_led();
break;
case 0x08:
Serial.println("button 4");
blink_led();
break;
}
Pin0Change=0;
}
}
}
//user-defined function for the initialisation of the external interrupt PCINT0
void pcint0_init(void) //enable pcint0 (all port b) as an interrupt
{
cli(); // SREG = 0 stop seeing others INTERRUPTS
PCICR = PCICR | (1 << PCIE0); //PCICR PIN CHANGE INTERUPT CONTROL REGISTER, LIKE CHECKING ALL THE PINS ON PORT B
PCMSK0 = PCMSK0 | (1<<PCINT0)|(1<<PCINT1)| (1<<PCINT2) | (1<<PCINT3); //define which pins to check in port B
PCIFR |= (1 << PCIF0);
sei(); // SREG = 1 starts seeing all interrupts again
}
//interrupt-service routine
ISR(PCINT0_vect)
{
Pin0Change = 1;
buttons = PINB;
PCIFR = PCIFR | (1 << PCIF0); // re-arm the interrupt – IMPORTANT!!!
}
void blink_led(void)
{
PORTA |= 0x80;
_delay_ms(1000);
PORTA &= ~0x80;
Pin0Change = 0;
}