//#include <TimerOne.h>
#include <IRremote.hpp>
// This example creates a PWM signal with 25 kHz carrier.
//
// Arduino's analogWrite() gives you PWM output, but no control over the
// carrier frequency. The default frequency is low, typically 490 or
// 3920 Hz. Sometimes you may need a faster carrier frequency.
//
// The specification for 4-wire PWM fans recommends a 25 kHz frequency
// and allows 21 to 28 kHz. The default from analogWrite() might work
// with some fans, but to follow the specification we need 25 kHz.
//
// http://www.formfactors.org/developer/specs/REV1_2_Public.pdf
//
// Connect the PWM pin to the fan's control wire (usually blue). The
// board's ground must be connected to the fan's ground, and the fan
// needs +12 volt power from the computer or a separate power supply.
#define CMD_PWR 0xA2
#define PWM_PERIOD 40 // 1/25000Hz = 40us
#define IR_RECEIVE_PIN 4 // Signal Pin of IR receiver
const int PIN_PWM_FAN = 9;
volatile bool wakeup;
ISR(PCINT2_vect) {
wakeup = true;
}
struct PowerButton {
uint32_t saveTime;
bool state;
bool changed;
} powerButton;
inline void enableWakeupInterruptOnD4() {
// Enalble PIN CHANGE interrupt on D4 pin
PCICR |= _BV(PCIE2);
PCMSK2 |= _BV(PCINT20); // PIN D4 ha PCINT20, su PCIE2 e PCMSK2
}
inline void disableWakeupInterruptOnD4() {
// Disable PIN CHANGE interrupt on D4 pin
PCMSK2 &= ~_BV(PCINT20);
PCICR &= ~_BV(PCIE2);
}
void setup(void) {
IrReceiver.begin(IR_RECEIVE_PIN);
Serial.begin(115200);
uint16_t c = (F_CPU/100000 * PWM_PERIOD) / 20;
Serial.println(c);
toSleep();
}
void timer1Init() {
TCCR1B = _BV(WGM13); // set mode as phase and frequency correct pwm, stop the timer
TCCR1A = 0; // clear control register A
ICR1 = (F_CPU/100000 * PWM_PERIOD) / 20;
TCCR1B = _BV(WGM13) | _BV(CS10);
pinMode(PIN_PWM_FAN, OUTPUT); // set pin 9 as output
TCCR1A |= _BV(COM1A1);
}
void setDutyPercent(uint8_t dc) {
uint32_t dutyCycle = ICR1 * ((dc / 100.0) * 1023);
OCR1A = dutyCycle >> 10;
}
void toSleep() {
cli(); // clear global interrupt
enableWakeupInterruptOnD4();
sei(); // enable global interrupt
simSleep();
disableWakeupInterruptOnD4();
}
inline void simSleep() {
Serial.println("entro nel sonno");
while (!wakeup);
wakeup = false;
Serial.println("esco dal sonno");
}
void loop(void) {
uint8_t command = 0;
// Checks received an IR signal
if (IrReceiver.decode()) {
command = IrReceiver.decodedIRData.command;
Serial.println(command);
IrReceiver.resume(); // Receive the next value
}
switch(command) {
case CMD_PWR:
powerButton.saveTime = millis();
break;
}
}