#define LED_PIN 11
#define IR_PIN 2
volatile int stato = LOW;
volatile bool irReceived = false;
volatile unsigned long irValue = 0;
#define NEC_BITS 32 // Il protocollo NEC trasmette 32 bit
// Variabili per la decodifica IR
volatile unsigned long startTime = 0;
volatile unsigned long duration = 0;
volatile unsigned int bitIndex = 0;
volatile unsigned long rawValue = 0;
void setup() {
Serial.begin(115200);
// Configura LED_PIN (PD5 su Arduino Uno) come uscita
DDRB |= (1 << DDB5);
// Configura IR_PIN (PD2 su Arduino Uno) come ingresso
DDRD &= ~(1 << DDD2);
// Abilita interrupt per pin change su IR_PIN (PD2 su Arduino Uno)
PCICR |= (1 << PCIE2); // Abilita PCINT23..16 (pin change interrupt su PD2)
PCMSK2 |= (1 << PCINT18); // Abilita interrupt su PCINT18 (PD2)
Serial.println("SETUP");
}
void loop() {
// Se un valore IR è stato ricevuto
if (irReceived) {
irReceived = false; // Reset la variabile
if(irValue == 268457301){
Serial.print("PLUS");
}
if(irValue == 21058901){
Serial.print("MINUS");
}
// Esegui un'azione basata sul valore IR ricevuto
// Qui puoi aggiungere il tuo codice per gestire il comando ricevuto
}
}
// Interrupt Service Routine per pin change su PD2 (PCINT18)
ISR(PCINT2_vect) {
unsigned long currentTime = micros();
duration = currentTime - startTime;
startTime = currentTime;
// Verifica se il segnale è un intervallo di sincronizzazione NEC
if (duration > 8500 && duration < 9500) {
bitIndex = 0;
rawValue = 0;
return;
}
// Verifica se il segnale è un intervallo di ripetizione NEC
if (duration > 2000 && duration < 2500) {
return; // Ignora gli intervalli di ripetizione
}
// Verifica se il segnale è uno zero o uno nel protocollo NEC
if (duration > 400 && duration < 700) {
// Zero logico, non fare nulla, solo incrementare il bitIndex
bitIndex++;
} else if (duration > 1600 && duration < 1800) {
// Uno logico, impostare il bit corrispondente
rawValue |= (1UL << (31 - bitIndex));
bitIndex++;
}
// Se tutti i bit sono stati ricevuti
if (bitIndex >= NEC_BITS) {
irValue = rawValue;
irReceived = true;
bitIndex = 0; // Reset del bitIndex per la prossima ricezione
}
// Cambia lo stato del LED per indicare che un segnale è stato ricevuto
stato = !stato;
if (stato) {
PORTB |= (1 << PORTB5); // Accende il LED
} else {
PORTB &= ~(1 << PORTB5); // Spegne il LED
}
}