Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagecpp
// LEDs and switchs
const byte ledPin1 = 11;
const byte ledPin2 = 13;
const byte buttonPin1= 2;
const byte buttonPin2 = 7;

// Booleans for input states
volatile bool D2_state = LOW;
volatile bool D7_state = LOW;

void setup() {

  // Set LEDs as output
  pinMode(ledPin1, OUTPUT) ;
  pinMode(ledPin2, OUTPUT) ;

  // Set Switches as input with pullup
  pinMode(buttonPin1, INPUT_PULLUP) ;
  pinMode(buttonPin2, INPUT_PULLUP) ;

  // Enable PCIE2 Bit3 = 1 (Port D)|
  PCICR |= 800000100;

  //Enable interrupt on Pin D2 & D7 - Select PCINT18 & PCINT23 (Pin D2 & D7)
  PCMSK2 |= B10000100;
}

void loop(){
 // No code in Loop
}

ISR (PCINT2_vect)
{
  // Port D Interrupt occured

  // Check if this was D2
  if (digitalRead(buttonPin1) == LOW) {

    //Pin D2 triggered the ISR on a Falling pulse
    D2_state = !D2_state;

    //Set LED 1 to state of D2 state boolean
    digitalWrite(ledPin1, D2_state);
  }

  // Check if this was D7
  if (digitalRead(buttonPin2) == LOW) {

    //Pin D7 triggered the ISR on a Falling pulse
    D7_state = !D7_state;
    //Set LED 2 to state of D7_state boolean
    digitalWrite(ledPin2, D7_state);
  }

}


Timer Interrupts

Do not use a timer that is used by another process.


Arduino Uno Timers

Image Added

Image Added

Image Added

Image Added

Image AddedImage AddedImage Added


Image AddedImage Added


Image Added

Replace x with 0,1, or 2 representing the timer #.


Code Sample 

Code Block
//define the LED pin
#define ledPin 13

//Define timer compare match register value
int timer1_compare_match;

ISR(TIMER1_COMPA_vect){
//Interrupt Service Routine for Compare Mode

  //Preload timer with compare match value
  TCNT1 = timer_compare_match;

  //Write opposite value to LED
  digitalWrite(ledPin, digitalRead(ledPin) ^ 1);
}

void setup(){

  //Set LED as output
  pinMode(ledPin, OUTPUT);
  
  //Disable all interrupts
  noInterrupts();

  //Initialize Timer1
  TCCR1A = 0;
  TCCR1B = 0;
  
  //Set timerl_compare_match to the correct compare match register value
  // 256 prescaler & 31246 compare match = 2Hz
  timer_compare_match = 31249;  
  
  //Preload timer with compare match value
  TCNT1 = timer1_compare_match;

  // Preload timer with compare match value
  TCNT1 = timer1_compare_match;

  // Set prescaler to 256 - set CS12 bit in TCCR1B
  TCCR1B = (1 < CS12) ;

  // Enable timer interrupt for compare mode
  TIMSK1 |= (1 < OCIE1A);

  // Enable all interrupts
  interrupts ();

}

void loop() {
  //nothing
}
















Analyzing the Following Code

...