/*
Este sketch serve para controlar um ventilador/motor AC em modo PSM (Pulse Skip Modulation)
Deve ser usado com um modulo Dimmer AC, como por exemplo este; https://pt.aliexpress.com/item/1005001965951718.html
O pino de interrupção (D2) deve ser ligado ao pino Z-C do modulo
O pino de saída (D12) deve ser ligado ao pino PSM do modulo
A entrada analógica (A0) pode ser ligada a um potenciometro ou a uma saída analogica de outro microcontrolador
This sketch is used to control an AC fan/motor in PSM mode (Pulse Skip Modulation)
Should be used with an AC Dimmer module, such as this one; https://pt.aliexpress.com/item/1005001965951718.html
The interrupt pin (D2) must be connected to the Z-C pin of the module
The output pin (D12) must be connected to the PSM pin of the module
The analog input (A0) can be connected to a potentiometer or to an analog output of another microcontroller
*/
#define led 13
#define fan 12 // Ventilador (Fan)
#define pot A0 // Potenciometro (Potentiometer)
int potValue = 0;
int mapedPotValue = 0;
int fanOnTime = 0;
int fanOffTime = 0;
int freq_Hz = 50; // Frequencia da rede AC (AC mains frequency)
// In some regions you will have to switch to 60 Hz
void fanUpdate(){
static int countOn = 0;
static int countOff = 0;
if(fanOnTime > countOn){
digitalWrite(fan,1); // Liga o Ventilador (Fan ON)
digitalWrite(led,1);
countOn++;
}
else if(fanOnTime <= countOn && fanOffTime > countOff){
digitalWrite(fan,0); // Desliga o Ventilador (Fan OFF)
digitalWrite(led,0);
countOff++ ;
}
else{
countOn = 0;
countOff = 0;
}
}
void fanSetVal(int percentg, int freq, int* pr_fanOnTime, int* pr_fanOffTime){
int zeroCrossPuls = freq*2;
int percentgVal = (zeroCrossPuls*percentg)/100;
*pr_fanOnTime = percentgVal;
*pr_fanOffTime = zeroCrossPuls - percentgVal;
}
void setup() {
// put your setup code here, to run once:
//analogReference(EXTERNAL); // descomentar se quiser utilizar uma voltagem de referencia diferente, por ex. saida analogica de 3,3v de outro microcontrolador
// uncomment if you want to use a different reference voltage, e.g. 3.3v analog output from another microcontroller
attachInterrupt(digitalPinToInterrupt(2),fanUpdate,RISING );
}
void loop() {
// put your main code here, to run repeatedly:
potValue = analogRead(pot);
mapedPotValue = map(potValue,0,1023,0,100); // Transforma o valor analogico em percentagem (Transforms the analog value into a percentage)
fanSetVal(mapedPotValue, freq_Hz, &fanOnTime, &fanOffTime);
}