//https://www.tutorialspoint.com/timer1-based-pwm-in-arduino-uno
//https://techexplorations.com/guides/arduino/peripherals/arduino-timer1/#:~:text=To%20initialize%20the%20timer1%20object,timer%20object%20to%201000%20microseconds.
#include <TimerOne.h>
const int fanPin = 9;
volatile float dutyCycle=0.0;
int ldr;
void (blinkLED)(void){
    //for (float dutyCycle = 0.0; dutyCycle < 100.0; dutyCycle++) {
      Serial.print("PWM Fan, Duty Cycle = ");
      Serial.println(dutyCycle);
      Timer1.pwm(fanPin, (dutyCycle / 100) * 1023);
      //delay(10000);
   //}
}
void setup(void)
{
   Timer1.initialize(500000); // 40 us = 25 kHz
   Timer1.attachInterrupt(blinkLED);
   Serial.begin(9600);
}

void loop(void)
{
   // slowly increase the PWM fan speed
   //
   /*
   for (float dutyCycle = 0.0; dutyCycle < 100.0; dutyCycle++) {
      Serial.print("PWM Fan, Duty Cycle = ");
      Serial.println(dutyCycle);
      Timer1.pwm(fanPin, (dutyCycle / 100) * 1023);
      delay(10000);
   }
   */
  ldr = map(analogRead(A0),0,1023,0,100);
  dutyCycle = ldr *1.0;
  Serial.println(dutyCycle);
  delay(200);
}








/*
#include <TimerOne.h>
const int led = 9;  // the pin with a LED
int analogIn = A0;
void setup(void)
{  
  pinMode(led, OUTPUT);
  pinMode(analogIn,INPUT);
  Timer1.initialize(100000);
  //Timer1.attachInterrupt(blinkLED);
  attachInterrupt(digitalPinToInterrupt(analogIn), blinkLED, RISING);
  Serial.begin(9600);
}

int ledState = LOW;
volatile unsigned long blinkCount = 0;

void blinkLED(void)
{
  if (ledState == LOW) {
    ledState = HIGH;
    blinkCount = blinkCount + 1;
  } else {
    ledState = LOW;
  }
  digitalWrite(led, ledState);
}

void loop(void)
{
  unsigned long blinkCopy;  // holds a copy of the blinkCount
  noInterrupts();
  blinkCopy = blinkCount;
  interrupts();
 Serial.print("blinkCount = ");
  Serial.println(blinkCopy);
  delay(200);
}
*/

/*
#include <TimerOne.h>

int analogIn = 4; //A0;
//float analogIn = A0;
float In = 0;
int Percentualminimoclaridade = 20;
int PinoLed = 9;
bool armado = false;


//void alarme();
//void set_ldr();

void setup() {
  Serial.begin(115200);
  pinMode(PinoLed , OUTPUT);
  pinMode(analogIn , INPUT);
  Timer1.initialize(1000000);
  attachInterrupt(digitalPinToInterrupt(analogIn), set_ldr, RISING);
}

void loop() {
  //delay(500);
  //in = 0;
  //Serial.println(analogRead(A1));
  //delay(200);
}

void alarme() {
 digitalWrite(PinoLed,!digitalRead(PinoLed));
 Serial.println("Alarme");
}
void set_ldr(){ //Função ISR
  Serial.println("Set_ldr");
  if (armado){
  armado=false;
  //Timer1.detachInterrupt(); 
  digitalWrite(PinoLed,LOW);
//;
}else{  
  //interrupts();
  Serial.println("Set_ldr: armado=true");
  armado=true;
  //Timer1.initialize(1000000);
  //Timer1.attachInterrupt(alarme);
  //digitalWrite(PinoLed,HIGH);
}
}
  
 */