#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x70,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
int potVal;
int potPin = A2;
int fanVal;
const byte OC1A_PIN = 9;
const byte OC1B_PIN = 10;
const word PWM_FREQ_HZ = 25000; //Adjust this value to adjust the frequency
const word TCNT1_TOP = 16000000 / (2 * PWM_FREQ_HZ);
int NbTopsFan; int Calc;
int hallsensor = 2; typedef struct{
char fantype;
unsigned int fandiv;
}fanspec;
fanspec fanspace[3]={{0,1},{1,2},{2,8}}; char fan = 1;
void rpm (){
NbTopsFan++;
}
void setPwmDuty(byte duty) {
OCR1A = (word)(duty * TCNT1_TOP) / 100;
}
void setup() {
lcd.init();
lcd.backlight();
pinMode(OC1A_PIN, OUTPUT);
pinMode(hallsensor, INPUT);
attachInterrupt(0, rpm, RISING);
// Clear Timer1 control and count registers
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
TCCR1A |= (1 << COM1A1) | (1 << WGM11);
TCCR1B |= (1 << WGM13) | (1 << CS10);
ICR1 = TCNT1_TOP;
}
void loop() {
potVal = analogRead(potPin);
fanVal = map(potVal, 0, 1023, 0, 100);
setPwmDuty(fanVal);
NbTopsFan = 0;
sei();
delay (100);
cli();
Calc = ((NbTopsFan * 600)/fanspace[fan].fandiv);
lcd.setCursor(1,0);
lcd.print(Calc,DEC);
lcd.print(" rpm");
}