Advertisement
honey_the_codewitch

fan RPM computer

Jan 3rd, 2023
818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <Arduino.h>
  2.  
  3. #define PWM_PIN 23
  4. #define TACH_PIN 22
  5.  
  6. volatile int ticks;
  7. const int ticks_per_rev = 2;
  8. volatile uint32_t old_tick_ts;
  9. volatile uint32_t tick_ts;
  10. static uint32_t ts = 0;
  11.  
  12. static void pwm_set(uint8_t value, void *state)
  13. {
  14.   // input is 8-bit
  15.   // write a 4-bit duty
  16.   ledcWrite(0, value >> 4);
  17. }
  18.  
  19. static void update_ticks() {
  20.   if((ticks++)==(ticks_per_rev-1)) {
  21.     old_tick_ts = tick_ts;
  22.     tick_ts = millis();
  23.     ticks = 0;
  24.   }
  25. }
  26. void setup()
  27. {
  28.   ticks = 0;
  29.   tick_ts = 0;
  30.   old_tick_ts = 0;
  31.   Serial.begin(115200);
  32.   ledcAttachPin(PWM_PIN, 0);
  33.   ledcSetup(0, 25 * 1000, 4);
  34.   attachInterrupt(TACH_PIN,update_ticks,RISING);
  35.   Serial.println("Booted");
  36.   pwm_set(255,nullptr);
  37. }
  38.  
  39. void loop()
  40. {
  41.   double rpm = NAN;
  42.   if(tick_ts>old_tick_ts && old_tick_ts!=0) {
  43.     rpm = (60*1000.0)/(tick_ts-old_tick_ts);
  44.   }
  45.   if(millis()>ts+250) {
  46.     ts=millis();
  47.     Serial.print(rpm);
  48.     Serial.println(" RPM");
  49.   }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement