Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* This code sample is associated with the following question on Stack Exchange:
- * http://arduino.stackexchange.com/questions/20919/arduino-nano-pwm-output-acting-strange-after-running-for-a-day-or-so
- */
- #include <Time.h>
- #define _analogWrite(a, b) analogWrite(a, 255-(b))
- #define clamp(X, minVal, maxVal) min(max(X, minVal), maxVal)
- const PROGMEM int pwmPin = 3;
- time_t lastUpdate = 0;
- inline void flushSerialBuffer() {
- while (Serial.available()) Serial.read();
- }
- void setup() {
- Serial.begin(9600);
- Serial.setTimeout(500);
- pinMode(pwmPin, OUTPUT);
- _analogWrite(pwmPin, 0);
- }
- void loop() {
- time_t currentTime = now();
- if (Serial.available()) {
- delay(500); // Just to be super safe
- int pwmValue = Serial.parseInt();
- flushSerialBuffer();
- if (pwmValue < 0 || pwmValue > 255) pwmValue = 0;
- _analogWrite(pwmPin, pwmValue);
- lastUpdate = currentTime;
- }
- if (currentTime - lastUpdate > 30) _analogWrite(pwmPin, 0);
- delay(250);
- }
Advertisement
Add Comment
Please, Sign In to add comment