Advertisement
Guest User

OG code

a guest
Feb 26th, 2016
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1.     #include <Time.h>
  2.    
  3.     // Simple macro for inverted pwm output (since my circuit will turn the lamp OFF whenever the output is HIGH)
  4.     #define _analogWrite(a, b) analogWrite(a, 255-(b))
  5.    
  6.     // Globals
  7.     const PROGMEM int pwmPin = 3;
  8.     time_t lastUpdate = 0;
  9.     int pwmValue = 0;
  10.    
  11.     void setup() {
  12.         Serial.begin(9600);
  13.         Serial.setTimeout(250);
  14.         pinMode(pwmPin, OUTPUT);
  15.         _analogWrite(pwmPin, pwmValue);
  16.     }
  17.    
  18.     void loop() {
  19.         // Get current time
  20.         time_t currentTime = now();
  21.    
  22.         // If there's data available, process it
  23.         if (Serial.available()) {
  24.             // Read all the incoming data
  25.             String str = Serial.readString();
  26.             // Extract only the numbers from it
  27.             String str2 = "";
  28.             for (int i=0; i<str.length(); i++) {
  29.                 if (str[i] >= '0' && str[i] <= '9') str2 += str[i];
  30.             }
  31.             // Convert it to an int, and store it
  32.             pwmValue = str2.toInt();
  33.             // Save the current time
  34.             lastUpdate = currentTime;
  35.         }
  36.        
  37.         // Safety mechanism (if we haven't received anything in the last 30 seconds, set the output to 0)
  38.         if (currentTime - lastUpdate > 30) pwmValue = 0;
  39.    
  40.         // Write the value we have to the output
  41.         _analogWrite(pwmPin, pwmValue);
  42.        
  43.         delay(100);
  44.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement