#include "wiring_private.h"
#define MFLAG GPIOR0
#define IR_DONE 0
#define IR_RUN 1
volatile uint16_t pulsesCount = 0;
volatile uint16_t pulses[256];
void setup() {
noInterrupts(); // Disabilita temporaneamente le interruzioni
TCCR1A = 0; // imposta tutti i bit di controllo del Timer1 a 0
TCCR1B = _BV(CS11); // Impostazioen del prescaler a 8
sbi(TIMSK1, TOIE1); // Abilita l'interruzione Timer1 overflow
// Configurazione del Pin Change Interrupt PCINT18
sbi(PCMSK2, PCINT18); // Abilita l'interruzione sul pin PCINT18
sbi(PCICR, PCIE2); // Abilita il gruppo di interrupt PCIE2
cbi(MFLAG, IR_DONE);
cbi(MFLAG, IR_RUN);
interrupts(); // Riabilita le interruzioni
Serial.begin(9600);
Serial.println("Ready");
}
void loop() {
// put your main code here, to run repeatedly:
if(bit_is_set(MFLAG, IR_DONE)) {
cbi(TIMSK1, TOIE1); // Disabilita l'interruzione Timer1 overflow
cbi(PCMSK2, PCINT18); // Disabilita l'interruzione Pin Change su PCINT18
Serial.print("Pulses Count: ");
Serial.println(pulsesCount);
for(uint8_t i = 0; i < pulsesCount; i++) {
Serial.println(pulses[i]);
}
pulsesCount = 0; // Resetta il contatore
cbi(MFLAG, IR_DONE); // Cancella il bit IR_DONE
sbi(TIMSK1, TOIE1); // Riabilita l'interruzione Timer1 overflow
sbi(PCMSK2, PCINT18); // Riabilita l'interruzione Pin Change su PCINT18
}
}
//Interrupt Service Routine (ISR) per Timer1 overflow
ISR(TIMER1_OVF_vect) {
if(bit_is_set(MFLAG, IR_RUN)) {
sbi(MFLAG, IR_DONE);
cbi(MFLAG, IR_RUN);
if(pulsesCount < 255)
pulses[pulsesCount++]=0;
}
}
// Interrupt Service Routine (ISR) per Pin Change Interrupt su PCINT18
ISR(PCINT2_vect) {
if(bit_is_set(MFLAG, IR_RUN)) {
// inserisco il tempo del timer all'interno dell'array
pulses[pulsesCount] = TCNT1;
if(pulsesCount < 255) {
pulsesCount++;
} else {
pulses[pulsesCount]=0xFFFF;
}
} else {
sbi(MFLAG, IR_RUN);
}
// Resetto l'array
TCNT1 = 0;
}