Guest User

Arduino code sample

a guest
Feb 21st, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. /* This code sample is associated with the following question on Stack Exchange:
  2.  * http://arduino.stackexchange.com/questions/20919/arduino-nano-pwm-output-acting-strange-after-running-for-a-day-or-so
  3.  */
  4.  
  5. #include <Time.h>
  6.  
  7. #define _analogWrite(a, b) analogWrite(a, 255-(b))
  8. #define clamp(X, minVal, maxVal) min(max(X, minVal), maxVal)
  9.  
  10. const PROGMEM int pwmPin = 3;
  11. time_t lastUpdate = 0;
  12.  
  13. inline void flushSerialBuffer() {
  14.     while (Serial.available()) Serial.read();
  15. }
  16.  
  17. void setup() {
  18.     Serial.begin(9600);
  19.     Serial.setTimeout(500);
  20.     pinMode(pwmPin, OUTPUT);
  21.     _analogWrite(pwmPin, 0);
  22. }
  23.  
  24. void loop() {
  25.     time_t currentTime = now();
  26.    
  27.     if (Serial.available()) {
  28.         delay(500); // Just to be super safe
  29.         int pwmValue = Serial.parseInt();
  30.         flushSerialBuffer();
  31.         if (pwmValue < 0 || pwmValue > 255) pwmValue = 0;
  32.         _analogWrite(pwmPin, pwmValue);
  33.         lastUpdate = currentTime;
  34.     }
  35.    
  36.     if (currentTime - lastUpdate > 30) _analogWrite(pwmPin, 0);
  37.    
  38.     delay(250);
  39. }
Advertisement
Add Comment
Please, Sign In to add comment