ferrybig

Arduino PWM ATX 4pin fan

Sep 3rd, 2020
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.28 KB | None | 0 0
  1. /*
  2.   Fade
  3.  
  4.   This example shows how to fade an LED on pin 9 using the analogWrite()
  5.   function.
  6.  
  7.   The analogWrite() function uses PWM, so if you want to change the pin you're
  8.   using, be sure to use another PWM capable pin. On most Arduino, the PWM pins
  9.   are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
  10.  
  11.   This example code is in the public domain.
  12.  
  13.   http://www.arduino.cc/en/Tutorial/Fade
  14. */
  15.  
  16. #include <PWM.h>
  17.  
  18. //use pin 11 on the Mega instead, otherwise there is a frequency cap at 31 Hz
  19. int led = 3;                // the pin that the LED is attached to
  20.         // how many points to fade the LED by
  21. int32_t frequency = 25000; //frequency (in Hz)
  22.  
  23. const int sensePin = 2;
  24.  
  25.  
  26. void setup()
  27. {
  28.     Serial.begin(9600);
  29.   //initialize all timers except for 0, to save time keeping functions
  30.   InitTimersSafe();
  31.  
  32.   //sets the frequency for the specified pin
  33.   bool success = SetPinFrequencySafe(led, frequency);
  34.  
  35.   //if the pin frequency was set successfully, pin 13 turn on
  36.   if(success) {
  37.     pinMode(13, OUTPUT);
  38.     digitalWrite(13, HIGH);  
  39.   }
  40.     pinMode(sensePin, INPUT_PULLUP);
  41.   attachInterrupt(digitalPinToInterrupt(sensePin), sense, RISING);
  42. }
  43.  
  44. int brightness = 5;    // how bright the LED is
  45. int fadeAmount = 5;    // how many points to fade the LED by
  46. unsigned int skipAdjust = 0;
  47.  
  48. unsigned long lastPulse = 0;
  49. volatile unsigned long pulsus = 0;
  50.  
  51. void sense() {
  52.     pulsus++;
  53. }
  54.  
  55. // the loop routine runs over and over again forever:
  56. void loop() {
  57.   // set the brightness of pin 9:
  58.   pwmWrite(led, brightness);
  59.  
  60.   // change the brightness for next time through the loop:
  61.   if(skipAdjust != 0) {
  62.     skipAdjust--;
  63.   } else {
  64.       brightness = brightness + fadeAmount;
  65.    
  66.       // reverse the direction of the fading at the ends of the fade:
  67.       if (brightness <= 5 || brightness >= 255) {
  68.         fadeAmount = -fadeAmount;
  69.         skipAdjust = 10;
  70.       }
  71.   }
  72.  
  73.   unsigned long currentTime = millis();
  74.   unsigned long pulses = pulsus;
  75.   unsigned long freq = currentTime == lastPulse ? 0 : ( pulses * 1000 / (currentTime - lastPulse));
  76.   pulsus -= pulses;
  77.   lastPulse = currentTime;
  78.   Serial.print(brightness);
  79.   Serial.print(' ');
  80.   Serial.print(freq);
  81.   Serial.println();
  82.   // wait for 50 milliseconds to see the dimming effect
  83.   delay(1000);
  84.  
  85. }
Add Comment
Please, Sign In to add comment