boolean pinState;
byte interruptPin = 19;
volatile boolean pinStateChanged = false;
volatile uint32_t overflowCounter = 0;
volatile uint32_t us;
void setup()
{
noInterrupts();
pinMode(interruptPin, INPUT);
attachInterrupt(digitalPinToInterrupt(interruptPin), on_change_state, CHANGE);
Serial.begin(2000000);
Serial.println(F(" Arduino Mega overflow interrupts"));
//Serial.println(digitalPinToInterrupt(interruptPin));
// Set timer1
TCCR1A = 0;
TCCR1B = 0;
TCCR1B |= (1 << CS10); // No prescaler
TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt ISR(TIMER1_OVF_vect)
OCR1A = 65535; // compare match register
// enable timer compare interrupt, reset if function not exist
//TIMSK1 |= (1 << OCIE1A);
//TCCR1A |= (1 << WGM11); // WGM 2 (CTC)
//TCCR1A = (1 << COM1B0); // Toggle OC1B on overflow
//TCCR1B |= (1 << WGM12); // CTC mode
//TCCR1B |= (1 << CS10); // Continue counting in TCNT1
TCNT1 = 0; // preload timer
_NOP();
_NOP();
_NOP();
_NOP();
_NOP();
volatile uint16_t t1 = TCNT1; // 2 cycles
//TCCR1B |= (1 << CS10); // Continue counting in TCNT1
volatile uint16_t t2 = TCNT1;
//TCCR1B &= ~(1 << CS10); // Stop counting in TCNT1
volatile uint16_t t3 = TCNT1;
Serial.println(t1);
Serial.println(t2);
Serial.println(t3);
interrupts();
us = micros();
overflowCounter = 0;
TCNT1 = 0;
TCCR1B |= (1 << CS10); // Continue counting in TCNT1
}
// interrupt service routine that wraps a user defined function supplied by attachInterrupt
ISR(TIMER1_OVF_vect)
{
overflowCounter++;
}
void on_change_state() {
pinStateChanged = true;
}
void loop()
{
//if (micros() - us >= 500000)
// pinStateChanged = true;
if (pinStateChanged)
{
uint16_t cnt = TCNT1;
TCNT1 = 0;
uint32_t ovf = overflowCounter;
overflowCounter = 0;
pinStateChanged = false;
uint32_t t = micros();
us = t - us;
Serial.print("OVF: ");
Serial.print(ovf);
Serial.print(" CNT: ");
Serial.print(cnt);
//pinState = digitalRead(interruptPin);
// For Arduino Mega 2560 and pin 19, related chip pin is PD2.
// Following should generate the same machine code
// pinState = PIND & (1 << PD2);
pinState = bitRead(PIND, PD2);
if (pinState)
Serial.print(F(" HIGH "));
else
Serial.print(F(" LOW "));
uint32_t cycles = ((uint32_t)ovf << 16) + cnt;
Serial.print(cycles);
Serial.write(' ');
Serial.print( (uint32_t) ((uint64_t)cycles * 625 / 10));
Serial.print("ns");
Serial.write(' ');
Serial.print(us);
Serial.print("us");
Serial.println();
us = t;
}
};