Using COMPA and COMPB correctly

Hi johnwasser,
I improved my sketch and the compA and compB are working. I let the LED on pin13 switch on (compA) and off (compB) which works well.

What is missing/ not working is:

  • External interrupt on INT0 on rising flag
  • this interrupt starts the timer1 starting at zero
  • stopping the timer1 with compB

Is that possible?

// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>
#define LEDPIN 13
// int timer;
// unsigned int counter;

void setup()
{
  Serial.begin(115200);
  pinMode(LEDPIN, OUTPUT);
  pinMode(2, INPUT);        // Enable Pin2 as input to interrupt

  cli();                    // disable global interrupts
  EIMSK |= (1 << INT0);     // Enable external interrupt INT0  (see table 13-2-2 in Atmel 328 spec)
  EICRA |= (1 << ISC00);    // Trigger INT0 on rising edge (see table 13-1 and 13-2 in Atmel 328 spec)
  EICRA |= (1 << ISC01);    // Trigger INT0 on rising edge (see table 13-1 and 13-2 in Atmel 328 spec)


    // set compare match register to desired timer count:
  OCR1A = 100;            // COMPA
  OCR1B = 50000;          // COMPB

  TCCR1B = 0;               // set entire  TCCR1B register to 0
  TCCR1B |= (1 << CS12);    // prescaler 256- see table 16-5

//***Not shiure if this is right...
  TCCR1A = 0;               // set entire TCCR1A register to 0
  TCCR1A |= (1 << COM1B0);    // Set OC1A/OC1B on Compare Match (Set output to high level).- see table 16-1
  TCCR1A |= (0 << COM1B1);    // Set OC1A/OC1B on Compare Match (Set output to high level).- see table 16-1
  TCCR1A |= (1 << COM1B0);    // Set OC1A/OC1B on Compare Match (Set output to high level).- see table 16-1
  TCCR1A |= (0 << COM1B1);    // Set OC1A/OC1B on Compare Match (Set output to high level).- see table 16-1
//***Not shiure if this is right...

  
  TIMSK1 |= (1 << OCIE1B);  // enable timer compare interrupt channel B:
  TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt channel A:


  sei();                    // Enable global interrupts
  attachInterrupt(0, start, RISING);
}

void loop()
{
}

ISR(EXT_INT0_vect){    
//Reset Timer1
TCCR1A = 0;               // set entire TCCR1A register to 0
TCCR1B = 0;               // same for TCCR1B and setting timer1 to 0
}


void start()
{
//want to start the timer here

//TCNT1H=0; //To do a 16-bit write, the high byte must be written before the low byte
//TCNT1L=0; //To do a 16-bit write, the high byte must be written before the low byte

}

ISR(TIMER1_COMPA_vect){
  digitalWrite(LEDPIN, HIGH);
  Serial.println("NUN");
}

ISR(TIMER1_COMPB_vect){
  digitalWrite(LEDPIN, LOW);

 // digitalWrite(LEDPIN, !digitalRead(LEDPIN));
 Serial.println("AHA");
//want to stop the timer here
}