Back to Parent

// This #include statement was automatically added by the Particle IDE.
#include <neopixel.h>

#include "neopixel.h"

// IMPORTANT: Set pixel COUNT, PIN and TYPE
#define PIXEL_PIN D2
#define PIXEL_COUNT 16
#define PIXEL_TYPE WS2812

Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, PIXEL_TYPE);

long timerStartAt = -1;
int status = 0; // 0 for default white, 1 for fading to red, 2 for fading to white
std::array<int, 3> red = {255, 0, 0};
std::array<int, 3> white = {255, 255, 255};
long fadeDuration = 1000 * 15 * 60 ;

void setup() {
    Serial.begin( 9600 ); 
    strip.begin();
    strip.show(); // Initialize all pixels to 'off'
    Particle.function("changeStatus", handleStatue);
    Particle.variable("status", status);
}

uint32_t getCurrentRGB(int fadeDuration, int timeElapsed, std::array<int, 3>  prevColor, std::array<int, 3>  targetColor) {
    int prev_r = prevColor[0];
    int prev_g = prevColor[1];
    int prev_b = prevColor[2];

    int target_r = targetColor[0];
    int target_g = targetColor[1];
    int target_b = targetColor[2];

    int r, g, b;  // Declare variables outside the loop
    
    Serial.println(timeElapsed);    

    if (fadeDuration != 0) {
        r = map(timeElapsed, 0, fadeDuration, prev_r, target_r);
        g = map(timeElapsed, 0, fadeDuration, prev_g, target_g);
        b = map(timeElapsed, 0, fadeDuration, prev_b, target_b);
        Serial.println(r);    
        Serial.println(g);        
        Serial.println(b);   
    }


    return strip.Color(r, g, b);
}

int handleStatue(String new_status){
    int new_status_int;
    if (new_status == "0") {
        new_status_int = 0;
    }
    
    if (new_status == "1") {
        new_status_int = 1;
    }
    
    if (new_status == "2") {
        new_status_int = 2;
    }
    
    status = new_status_int;
    return 1;
}

void loop() {
    uint32_t c = strip.Color(255, 255, 255);
    long timeNow = millis();
    long timeElapsed = timeNow - timerStartAt;
    Serial.print( "timeElapsed"); 
    Serial.println( timeElapsed); 
    
    if (status == 0) {
         c = strip.Color(255, 255, 255);
         timerStartAt = timeNow;
    }else if (status == 1) {
        if (timeElapsed < fadeDuration) {
            c = getCurrentRGB(fadeDuration, timeElapsed, white, red);
        } else {
            timerStartAt = timeNow;
            status = 2;
            return;
        }
    } else if (status == 2) {
        if (timeElapsed < fadeDuration) {
            c = getCurrentRGB(fadeDuration, timeElapsed, red, white);
        } else {
            timerStartAt = timeNow;
            status = 0;
            return;
        }
    } else {
        Particle.publish("error status");
    }

    for(int i=0; i< strip.numPixels(); i++) {
        strip.setPixelColor(i, c);
		strip.show();
    }
	
}
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0