Advertisement
Guest User

Untitled

a guest
Apr 17th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 31.41 KB | None | 0 0
  1.  
  2. #define FASTLED_INTERRUPT_RETRY_COUNT 0
  3. #include <ArduinoJson.h>
  4. #include <ESP8266WiFi.h>
  5. #include <PubSubClient.h>
  6. #include "FastLED.h"
  7. #include <ESP8266mDNS.h>
  8. #include <WiFiUdp.h>
  9. #include <ArduinoOTA.h>
  10.  
  11.  
  12.  
  13. /************ WIFI and MQTT Information (CHANGE THESE FOR YOUR SETUP) ******************/
  14. const char* ssid = "xxxx"; //type your WIFI information inside the quotes
  15. const char* password = "xxxxxx";
  16. const char* mqtt_server = "192.168.8.21";
  17. const char* mqtt_username = "homeassistant";
  18. const char* mqtt_password = "xxxxxxx";
  19. const int mqtt_port = 1883;
  20.  
  21.  
  22.  
  23. /**************************** FOR OTA **************************************************/
  24. #define SENSORNAME "desk" //change this to whatever you want to call your device
  25. #define OTApassword "xxxxxx" //the password you will need to enter to upload remotely via the ArduinoIDE
  26. int OTAport = 8266;
  27.  
  28.  
  29.  
  30. /************* MQTT TOPICS (change these topics as you wish)  **************************/
  31. const char* light_state_topic = "led/desk";
  32. const char* light_set_topic = "led/desk/set";
  33.  
  34. const char* on_cmd = "ON";
  35. const char* off_cmd = "OFF";
  36. const char* effect = "solid";
  37. String effectString = "solid";
  38. String oldeffectString = "solid";
  39.  
  40.  
  41.  
  42. /****************************************FOR JSON***************************************/
  43. const int BUFFER_SIZE = JSON_OBJECT_SIZE(10);
  44. #define MQTT_MAX_PACKET_SIZE 512
  45.  
  46.  
  47.  
  48. /*********************************** FastLED Defintions ********************************/
  49. #define NUM_LEDS    44
  50. #define DATA_PIN    15
  51. //#define CLOCK_PIN 5
  52. #define CHIPSET     WS2812B
  53. #define COLOR_ORDER BRG
  54.  
  55. byte realRed = 0;
  56. byte realGreen = 0;
  57. byte realBlue = 0;
  58.  
  59. byte red = 255;
  60. byte green = 255;
  61. byte blue = 255;
  62. byte brightness = 255;
  63.  
  64.  
  65.  
  66. /******************************** GLOBALS for fade/flash *******************************/
  67. bool stateOn = false;
  68. bool startFade = false;
  69. bool onbeforeflash = false;
  70. unsigned long lastLoop = 0;
  71. int transitionTime = 0;
  72. int effectSpeed = 0;
  73. bool inFade = false;
  74. int loopCount = 0;
  75. int stepR, stepG, stepB;
  76. int redVal, grnVal, bluVal;
  77.  
  78. bool flash = false;
  79. bool startFlash = false;
  80. int flashLength = 0;
  81. unsigned long flashStartTime = 0;
  82. byte flashRed = red;
  83. byte flashGreen = green;
  84. byte flashBlue = blue;
  85. byte flashBrightness = brightness;
  86.  
  87.  
  88.  
  89. /********************************** GLOBALS for EFFECTS ******************************/
  90. //RAINBOW
  91. uint8_t thishue = 0;                                          // Starting hue value.
  92. uint8_t deltahue = 10;
  93.  
  94. //CANDYCANE
  95. CRGBPalette16 currentPalettestriped; //for Candy Cane
  96. CRGBPalette16 gPal; //for fire
  97.  
  98. //NOISE
  99. static uint16_t dist;         // A random number for our noise generator.
  100. uint16_t scale = 30;          // Wouldn't recommend changing this on the fly, or the animation will be really blocky.
  101. uint8_t maxChanges = 48;      // Value for blending between palettes.
  102. CRGBPalette16 targetPalette(OceanColors_p);
  103. CRGBPalette16 currentPalette(CRGB::Black);
  104.  
  105. //TWINKLE
  106. #define DENSITY     80
  107. int twinklecounter = 0;
  108.  
  109. //RIPPLE
  110. uint8_t colour;                                               // Ripple colour is randomized.
  111. int center = 0;                                               // Center of the current ripple.
  112. int step = -1;                                                // -1 is the initializing step.
  113. uint8_t myfade = 255;                                         // Starting brightness.
  114. #define maxsteps 16                                           // Case statement wouldn't allow a variable.
  115. uint8_t bgcol = 0;                                            // Background colour rotates.
  116. int thisdelay = 20;                                           // Standard delay value.
  117.  
  118. //DOTS
  119. uint8_t   count =   0;                                        // Count up to 255 and then reverts to 0
  120. uint8_t fadeval = 224;                                        // Trail behind the LED's. Lower => faster fade.
  121. uint8_t bpm = 30;
  122.  
  123. //LIGHTNING
  124. uint8_t frequency = 50;                                       // controls the interval between strikes
  125. uint8_t flashes = 8;                                          //the upper limit of flashes per strike
  126. unsigned int dimmer = 1;
  127. uint8_t ledstart;                                             // Starting location of a flash
  128. uint8_t ledlen;
  129. int lightningcounter = 0;
  130.  
  131. //FUNKBOX
  132. int idex = 0;                //-LED INDEX (0 to NUM_LEDS-1
  133. int TOP_INDEX = int(NUM_LEDS / 2);
  134. int thissat = 255;           //-FX LOOPS DELAY VAR
  135. uint8_t thishuepolice = 0;
  136. int antipodal_index(int i) {
  137.   int iN = i + TOP_INDEX;
  138.   if (i >= TOP_INDEX) {
  139.     iN = ( i + TOP_INDEX ) % NUM_LEDS;
  140.   }
  141.   return iN;
  142. }
  143.  
  144. //FIRE
  145. #define COOLING  55
  146. #define SPARKING 120
  147. bool gReverseDirection = false;
  148.  
  149. //BPM
  150. uint8_t gHue = 0;
  151.  
  152.  
  153. WiFiClient espClient;
  154. PubSubClient client(espClient);
  155. struct CRGB leds[NUM_LEDS];
  156.  
  157.  
  158.  
  159. /********************************** START SETUP*****************************************/
  160. void setup() {
  161.   Serial.begin(115200);
  162.   FastLED.addLeds<CHIPSET, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  163.  
  164.   setupStripedPalette( CRGB::Red, CRGB::Red, CRGB::White, CRGB::White); //for CANDY CANE
  165.   gPal = HeatColors_p; //for FIRE
  166.  
  167.   setup_wifi();
  168.   client.setServer(mqtt_server, mqtt_port);
  169.   client.setCallback(callback);
  170.  
  171.   //OTA SETUP
  172.   ArduinoOTA.setPort(OTAport);
  173.   // Hostname defaults to esp8266-[ChipID]
  174.   ArduinoOTA.setHostname(SENSORNAME);
  175.  
  176.   // No authentication by default
  177.   ArduinoOTA.setPassword((const char *)OTApassword);
  178.  
  179.   ArduinoOTA.onStart([]() {
  180.     Serial.println("Starting");
  181.   });
  182.   ArduinoOTA.onEnd([]() {
  183.     Serial.println("\nEnd");
  184.   });
  185.   ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  186.     Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  187.   });
  188.   ArduinoOTA.onError([](ota_error_t error) {
  189.     Serial.printf("Error[%u]: ", error);
  190.     if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
  191.     else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
  192.     else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
  193.     else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
  194.     else if (error == OTA_END_ERROR) Serial.println("End Failed");
  195.   });
  196.   ArduinoOTA.begin();
  197.  
  198.   Serial.println("Ready");
  199.   Serial.print("IP Address: ");
  200.   Serial.println(WiFi.localIP());
  201.  
  202. }
  203.  
  204.  
  205.  
  206.  
  207. /********************************** START SETUP WIFI*****************************************/
  208. void setup_wifi() {
  209.  
  210.   delay(10);
  211.   // We start by connecting to a WiFi network
  212.   Serial.println();
  213.   Serial.print("Connecting to ");
  214.   Serial.println(ssid);
  215.  
  216.   WiFi.mode(WIFI_STA);
  217.   WiFi.begin(ssid, password);
  218.  
  219.   while (WiFi.status() != WL_CONNECTED) {
  220.     delay(500);
  221.     Serial.print(".");
  222.   }
  223.  
  224.   Serial.println("");
  225.   Serial.println("WiFi connected");
  226.   Serial.println("IP address: ");
  227.   Serial.println(WiFi.localIP());
  228. }
  229.  
  230. /*
  231.   SAMPLE PAYLOAD:
  232.   {
  233.     "brightness": 120,
  234.     "color": {
  235.       "r": 255,
  236.       "g": 100,
  237.       "b": 100
  238.     },
  239.     "flash": 2,
  240.     "transition": 5,
  241.     "state": "ON"
  242.   }
  243. */
  244.  
  245.  
  246.  
  247. /********************************** START CALLBACK*****************************************/
  248. void callback(char* topic, byte* payload, unsigned int length) {
  249.   Serial.print("Message arrived [");
  250.   Serial.print(topic);
  251.   Serial.print("] ");
  252.  
  253.   char message[length + 1];
  254.   for (int i = 0; i < length; i++) {
  255.     message[i] = (char)payload[i];
  256.   }
  257.   message[length] = '\0';
  258.   Serial.println(message);
  259.  
  260.   if (!processJson(message)) {
  261.     return;
  262.   }
  263.  
  264.   if (stateOn) {
  265.  
  266.     realRed = map(red, 0, 255, 0, brightness);
  267.     realGreen = map(green, 0, 255, 0, brightness);
  268.     realBlue = map(blue, 0, 255, 0, brightness);
  269.   }
  270.   else {
  271.  
  272.     realRed = 0;
  273.     realGreen = 0;
  274.     realBlue = 0;
  275.   }
  276.  
  277.   Serial.println(effect);
  278.  
  279.   startFade = true;
  280.   inFade = false; // Kill the current fade
  281.  
  282.   sendState();
  283. }
  284.  
  285.  
  286.  
  287. /********************************** START PROCESS JSON*****************************************/
  288. bool processJson(char* message) {
  289.   StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
  290.  
  291.   JsonObject& root = jsonBuffer.parseObject(message);
  292.  
  293.   if (!root.success()) {
  294.     Serial.println("parseObject() failed");
  295.     return false;
  296.   }
  297.  
  298.   if (root.containsKey("state")) {
  299.     if (strcmp(root["state"], on_cmd) == 0) {
  300.       stateOn = true;
  301.     }
  302.     else if (strcmp(root["state"], off_cmd) == 0) {
  303.       stateOn = false;
  304.       onbeforeflash = false;
  305.     }
  306.   }
  307.  
  308.   // If "flash" is included, treat RGB and brightness differently
  309.   if (root.containsKey("flash")) {
  310.     flashLength = (int)root["flash"] * 1000;
  311.  
  312.     oldeffectString = effectString;
  313.  
  314.     if (root.containsKey("brightness")) {
  315.       flashBrightness = root["brightness"];
  316.     }
  317.     else {
  318.       flashBrightness = brightness;
  319.     }
  320.  
  321.     if (root.containsKey("color")) {
  322.       flashRed = root["color"]["r"];
  323.       flashGreen = root["color"]["g"];
  324.       flashBlue = root["color"]["b"];
  325.     }
  326.     else {
  327.       flashRed = red;
  328.       flashGreen = green;
  329.       flashBlue = blue;
  330.     }
  331.  
  332.     if (root.containsKey("effect")) {
  333.       effect = root["effect"];
  334.       effectString = effect;
  335.       twinklecounter = 0; //manage twinklecounter
  336.     }
  337.  
  338.     if (root.containsKey("transition")) {
  339.       transitionTime = root["transition"];
  340.     }
  341.     else if ( effectString == "solid") {
  342.       transitionTime = 0;
  343.     }
  344.  
  345.     flashRed = map(flashRed, 0, 255, 0, flashBrightness);
  346.     flashGreen = map(flashGreen, 0, 255, 0, flashBrightness);
  347.     flashBlue = map(flashBlue, 0, 255, 0, flashBrightness);
  348.  
  349.     flash = true;
  350.     startFlash = true;
  351.   }
  352.   else { // Not flashing
  353.     flash = false;
  354.  
  355.     if (stateOn) {   //if the light is turned on and the light isn't flashing
  356.       onbeforeflash = true;
  357.     }
  358.  
  359.     if (root.containsKey("color")) {
  360.       red = root["color"]["r"];
  361.       green = root["color"]["g"];
  362.       blue = root["color"]["b"];
  363.     }
  364.    
  365.     if (root.containsKey("color_temp")) {
  366.       //temp comes in as mireds, need to convert to kelvin then to RGB
  367.       int color_temp = root["color_temp"];
  368.       unsigned int kelvin  = 1000000 / color_temp;
  369.      
  370.       temp2rgb(kelvin);
  371.      
  372.     }
  373.  
  374.     if (root.containsKey("brightness")) {
  375.       brightness = root["brightness"];
  376.     }
  377.  
  378.     if (root.containsKey("effect")) {
  379.       effect = root["effect"];
  380.       effectString = effect;
  381.       twinklecounter = 0; //manage twinklecounter
  382.     }
  383.  
  384.     if (root.containsKey("transition")) {
  385.       transitionTime = root["transition"];
  386.     }
  387.     else if ( effectString == "solid") {
  388.       transitionTime = 0;
  389.     }
  390.  
  391.   }
  392.  
  393.   return true;
  394. }
  395.  
  396.  
  397.  
  398. /********************************** START SEND STATE*****************************************/
  399. void sendState() {
  400.   StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
  401.  
  402.   JsonObject& root = jsonBuffer.createObject();
  403.  
  404.   root["state"] = (stateOn) ? on_cmd : off_cmd;
  405.   JsonObject& color = root.createNestedObject("color");
  406.   color["r"] = red;
  407.   color["g"] = green;
  408.   color["b"] = blue;
  409.  
  410.   root["brightness"] = brightness;
  411.   root["effect"] = effectString.c_str();
  412.  
  413.  
  414.   char buffer[root.measureLength() + 1];
  415.   root.printTo(buffer, sizeof(buffer));
  416.  
  417.   client.publish(light_state_topic, buffer, true);
  418. }
  419.  
  420.  
  421.  
  422. /********************************** START RECONNECT*****************************************/
  423. void reconnect() {
  424.   // Loop until we're reconnected
  425.   while (!client.connected()) {
  426.     Serial.print("Attempting MQTT connection...");
  427.     // Attempt to connect
  428.     if (client.connect(SENSORNAME, mqtt_username, mqtt_password)) {
  429.       Serial.println("connected");
  430.       client.subscribe(light_set_topic);
  431.       setColor(0, 0, 0);
  432.       sendState();
  433.     } else {
  434.       Serial.print("failed, rc=");
  435.       Serial.print(client.state());
  436.       Serial.println(" try again in 5 seconds");
  437.       // Wait 5 seconds before retrying
  438.       delay(5000);
  439.     }
  440.   }
  441. }
  442.  
  443.  
  444.  
  445. /********************************** START Set Color*****************************************/
  446. void setColor(int inR, int inG, int inB) {
  447.   for (int i = 0; i < NUM_LEDS; i++) {
  448.     leds[i].red   = inR;
  449.     leds[i].green = inG;
  450.     leds[i].blue  = inB;
  451.   }
  452.  
  453.   FastLED.show();
  454.  
  455.   Serial.println("Setting LEDs:");
  456.   Serial.print("r: ");
  457.   Serial.print(inR);
  458.   Serial.print(", g: ");
  459.   Serial.print(inG);
  460.   Serial.print(", b: ");
  461.   Serial.println(inB);
  462. }
  463.  
  464.  
  465.  
  466. /********************************** START MAIN LOOP*****************************************/
  467. void loop() {
  468.  
  469.   if (!client.connected()) {
  470.     reconnect();
  471.   }
  472.  
  473.   if (WiFi.status() != WL_CONNECTED) {
  474.     delay(1);
  475.     Serial.print("WIFI Disconnected. Attempting reconnection.");
  476.     setup_wifi();
  477.     return;
  478.   }
  479.  
  480.  
  481.  
  482.   client.loop();
  483.  
  484.   ArduinoOTA.handle();
  485.  
  486.  
  487.   //EFFECT BPM
  488.   if (effectString == "bpm") {
  489.     uint8_t BeatsPerMinute = 62;
  490.     CRGBPalette16 palette = PartyColors_p;
  491.     uint8_t beat = beatsin8( BeatsPerMinute, 64, 255);
  492.     for ( int i = 0; i < NUM_LEDS; i++) { //9948
  493.       leds[i] = ColorFromPalette(palette, gHue + (i * 2), beat - gHue + (i * 10));
  494.     }
  495.     if (transitionTime == 0 or transitionTime == NULL) {
  496.       transitionTime = 30;
  497.     }
  498.     showleds();
  499.   }
  500.  
  501.  
  502.   //EFFECT Candy Cane
  503.   if (effectString == "candy cane") {
  504.     static uint8_t startIndex = 0;
  505.     startIndex = startIndex + 1; /* higher = faster motion */
  506.     fill_palette( leds, NUM_LEDS,
  507.                   startIndex, 16, /* higher = narrower stripes */
  508.                   currentPalettestriped, 255, LINEARBLEND);
  509.     if (transitionTime == 0 or transitionTime == NULL) {
  510.       transitionTime = 0;
  511.     }
  512.     showleds();
  513.   }
  514.  
  515.  
  516.   //EFFECT CONFETTI
  517.   if (effectString == "confetti" ) {
  518.     fadeToBlackBy( leds, NUM_LEDS, 25);
  519.     int pos = random16(NUM_LEDS);
  520.     leds[pos] += CRGB(realRed + random8(64), realGreen, realBlue);
  521.     if (transitionTime == 0 or transitionTime == NULL) {
  522.       transitionTime = 30;
  523.     }
  524.     showleds();
  525.   }
  526.  
  527.  
  528.   //EFFECT CYCLON RAINBOW
  529.   if (effectString == "cyclon rainbow") {                    //Single Dot Down
  530.     static uint8_t hue = 0;
  531.     // First slide the led in one direction
  532.     for (int i = 0; i < NUM_LEDS; i++) {
  533.       // Set the i'th led to red
  534.       leds[i] = CHSV(hue++, 255, 255);
  535.       // Show the leds
  536.       showleds();
  537.       // now that we've shown the leds, reset the i'th led to black
  538.       // leds[i] = CRGB::Black;
  539.       fadeall();
  540.       // Wait a little bit before we loop around and do it again
  541.       delay(10);
  542.     }
  543.     for (int i = (NUM_LEDS) - 1; i >= 0; i--) {
  544.       // Set the i'th led to red
  545.       leds[i] = CHSV(hue++, 255, 255);
  546.       // Show the leds
  547.       showleds();
  548.       // now that we've shown the leds, reset the i'th led to black
  549.       // leds[i] = CRGB::Black;
  550.       fadeall();
  551.       // Wait a little bit before we loop around and do it again
  552.       delay(10);
  553.     }
  554.   }
  555.  
  556.  
  557.   //EFFECT DOTS
  558.   if (effectString == "dots") {
  559.     uint8_t inner = beatsin8(bpm, NUM_LEDS / 4, NUM_LEDS / 4 * 3);
  560.     uint8_t outer = beatsin8(bpm, 0, NUM_LEDS - 1);
  561.     uint8_t middle = beatsin8(bpm, NUM_LEDS / 3, NUM_LEDS / 3 * 2);
  562.     leds[middle] = CRGB::Purple;
  563.     leds[inner] = CRGB::Blue;
  564.     leds[outer] = CRGB::Aqua;
  565.     nscale8(leds, NUM_LEDS, fadeval);
  566.  
  567.     if (transitionTime == 0 or transitionTime == NULL) {
  568.       transitionTime = 30;
  569.     }
  570.     showleds();
  571.   }
  572.  
  573.  
  574.   //EFFECT FIRE
  575.   if (effectString == "fire") {
  576.     Fire2012WithPalette();
  577.     if (transitionTime == 0 or transitionTime == NULL) {
  578.       transitionTime = 150;
  579.     }
  580.     showleds();
  581.   }
  582.  
  583.   random16_add_entropy( random8());
  584.  
  585.  
  586.   //EFFECT Glitter
  587.   if (effectString == "glitter") {
  588.     fadeToBlackBy( leds, NUM_LEDS, 20);
  589.     addGlitterColor(80, realRed, realGreen, realBlue);
  590.     if (transitionTime == 0 or transitionTime == NULL) {
  591.       transitionTime = 30;
  592.     }
  593.     showleds();
  594.   }
  595.  
  596.  
  597.   //EFFECT JUGGLE
  598.   if (effectString == "juggle" ) {                           // eight colored dots, weaving in and out of sync with each other
  599.     fadeToBlackBy(leds, NUM_LEDS, 20);
  600.     for (int i = 0; i < 8; i++) {
  601.       leds[beatsin16(i + 7, 0, NUM_LEDS - 1  )] |= CRGB(realRed, realGreen, realBlue);
  602.     }
  603.     if (transitionTime == 0 or transitionTime == NULL) {
  604.       transitionTime = 130;
  605.     }
  606.     showleds();
  607.   }
  608.  
  609.  
  610.   //EFFECT LIGHTNING
  611.   if (effectString == "lightning") {
  612.     twinklecounter = twinklecounter + 1;                     //Resets strip if previous animation was running
  613.     if (twinklecounter < 2) {
  614.       FastLED.clear();
  615.       FastLED.show();
  616.     }
  617.     ledstart = random8(NUM_LEDS);           // Determine starting location of flash
  618.     ledlen = random8(NUM_LEDS - ledstart);  // Determine length of flash (not to go beyond NUM_LEDS-1)
  619.     for (int flashCounter = 0; flashCounter < random8(3, flashes); flashCounter++) {
  620.       if (flashCounter == 0) dimmer = 5;    // the brightness of the leader is scaled down by a factor of 5
  621.       else dimmer = random8(1, 3);          // return strokes are brighter than the leader
  622.       fill_solid(leds + ledstart, ledlen, CHSV(255, 0, 255 / dimmer));
  623.       showleds();    // Show a section of LED's
  624.       delay(random8(4, 10));                // each flash only lasts 4-10 milliseconds
  625.       fill_solid(leds + ledstart, ledlen, CHSV(255, 0, 0)); // Clear the section of LED's
  626.       showleds();
  627.       if (flashCounter == 0) delay (130);   // longer delay until next flash after the leader
  628.       delay(50 + random8(100));             // shorter delay between strokes
  629.     }
  630.     delay(random8(frequency) * 100);        // delay between strikes
  631.     if (transitionTime == 0 or transitionTime == NULL) {
  632.       transitionTime = 0;
  633.     }
  634.     showleds();
  635.   }
  636.  
  637.  
  638.   //EFFECT POLICE ALL
  639.   if (effectString == "police all") {                 //POLICE LIGHTS (TWO COLOR SOLID)
  640.     idex++;
  641.     if (idex >= NUM_LEDS) {
  642.       idex = 0;
  643.     }
  644.     int idexR = idex;
  645.     int idexB = antipodal_index(idexR);
  646.     int thathue = (thishuepolice + 160) % 255;
  647.     leds[idexR] = CHSV(thishuepolice, thissat, 255);
  648.     leds[idexB] = CHSV(thathue, thissat, 255);
  649.     if (transitionTime == 0 or transitionTime == NULL) {
  650.       transitionTime = 30;
  651.     }
  652.     showleds();
  653.   }
  654.  
  655.   //EFFECT POLICE ONE
  656.   if (effectString == "police one") {
  657.     idex++;
  658.     if (idex >= NUM_LEDS) {
  659.       idex = 0;
  660.     }
  661.     int idexR = idex;
  662.     int idexB = antipodal_index(idexR);
  663.     int thathue = (thishuepolice + 160) % 255;
  664.     for (int i = 0; i < NUM_LEDS; i++ ) {
  665.       if (i == idexR) {
  666.         leds[i] = CHSV(thishuepolice, thissat, 255);
  667.       }
  668.       else if (i == idexB) {
  669.         leds[i] = CHSV(thathue, thissat, 255);
  670.       }
  671.       else {
  672.         leds[i] = CHSV(0, 0, 0);
  673.       }
  674.     }
  675.     if (transitionTime == 0 or transitionTime == NULL) {
  676.       transitionTime = 30;
  677.     }
  678.     showleds();
  679.   }
  680.  
  681.  
  682.   //EFFECT RAINBOW
  683.   if (effectString == "rainbow") {
  684.     // FastLED's built-in rainbow generator
  685.     static uint8_t starthue = 0;    thishue++;
  686.     fill_rainbow(leds, NUM_LEDS, thishue, deltahue);
  687.     if (transitionTime == 0 or transitionTime == NULL) {
  688.       transitionTime = 130;
  689.     }
  690.     showleds();
  691.   }
  692.  
  693.  
  694.   //EFFECT RAINBOW WITH GLITTER
  695.   if (effectString == "rainbow with glitter") {               // FastLED's built-in rainbow generator with Glitter
  696.     static uint8_t starthue = 0;
  697.     thishue++;
  698.     fill_rainbow(leds, NUM_LEDS, thishue, deltahue);
  699.     addGlitter(80);
  700.     if (transitionTime == 0 or transitionTime == NULL) {
  701.       transitionTime = 130;
  702.     }
  703.     showleds();
  704.   }
  705.  
  706.  
  707.   //EFFECT SIENLON
  708.   if (effectString == "sinelon") {
  709.     fadeToBlackBy( leds, NUM_LEDS, 20);
  710.     int pos = beatsin16(13, 0, NUM_LEDS - 1);
  711.     leds[pos] += CRGB(realRed, realGreen, realBlue);
  712.     if (transitionTime == 0 or transitionTime == NULL) {
  713.       transitionTime = 150;
  714.     }
  715.     showleds();
  716.   }
  717.  
  718.  
  719.   //EFFECT TWINKLE
  720.   if (effectString == "twinkle") {
  721.     twinklecounter = twinklecounter + 1;
  722.     if (twinklecounter < 2) {                               //Resets strip if previous animation was running
  723.       FastLED.clear();
  724.       FastLED.show();
  725.     }
  726.     const CRGB lightcolor(8, 7, 1);
  727.     for ( int i = 0; i < NUM_LEDS; i++) {
  728.       if ( !leds[i]) continue; // skip black pixels
  729.       if ( leds[i].r & 1) { // is red odd?
  730.         leds[i] -= lightcolor; // darken if red is odd
  731.       } else {
  732.         leds[i] += lightcolor; // brighten if red is even
  733.       }
  734.     }
  735.     if ( random8() < DENSITY) {
  736.       int j = random16(NUM_LEDS);
  737.       if ( !leds[j] ) leds[j] = lightcolor;
  738.     }
  739.  
  740.     if (transitionTime == 0 or transitionTime == NULL) {
  741.       transitionTime = 0;
  742.     }
  743.     showleds();
  744.   }
  745.  
  746.  
  747.   EVERY_N_MILLISECONDS(10) {
  748.  
  749.     nblendPaletteTowardPalette(currentPalette, targetPalette, maxChanges);  // FOR NOISE ANIMATIon
  750.     {
  751.       gHue++;
  752.     }
  753.  
  754.     //EFFECT NOISE
  755.     if (effectString == "noise") {
  756.       for (int i = 0; i < NUM_LEDS; i++) {                                     // Just onE loop to fill up the LED array as all of the pixels change.
  757.         uint8_t index = inoise8(i * scale, dist + i * scale) % 255;            // Get a value from the noise function. I'm using both x and y axis.
  758.         leds[i] = ColorFromPalette(currentPalette, index, 255, LINEARBLEND);   // With that value, look up the 8 bit colour palette value and assign it to the current LED.
  759.       }
  760.       dist += beatsin8(10, 1, 4);                                              // Moving along the distance (that random number we started out with). Vary it a bit with a sine wave.
  761.       // In some sketches, I've used millis() instead of an incremented counter. Works a treat.
  762.       if (transitionTime == 0 or transitionTime == NULL) {
  763.         transitionTime = 0;
  764.       }
  765.       showleds();
  766.     }
  767.  
  768.     //EFFECT RIPPLE
  769.     if (effectString == "ripple") {
  770.       for (int i = 0; i < NUM_LEDS; i++) leds[i] = CHSV(bgcol++, 255, 15);  // Rotate background colour.
  771.       switch (step) {
  772.         case -1:                                                          // Initialize ripple variables.
  773.           center = random(NUM_LEDS);
  774.           colour = random8();
  775.           step = 0;
  776.           break;
  777.         case 0:
  778.           leds[center] = CHSV(colour, 255, 255);                          // Display the first pixel of the ripple.
  779.           step ++;
  780.           break;
  781.         case maxsteps:                                                    // At the end of the ripples.
  782.           step = -1;
  783.           break;
  784.         default:                                                             // Middle of the ripples.
  785.           leds[(center + step + NUM_LEDS) % NUM_LEDS] += CHSV(colour, 255, myfade / step * 2);   // Simple wrap from Marc Miller
  786.           leds[(center - step + NUM_LEDS) % NUM_LEDS] += CHSV(colour, 255, myfade / step * 2);
  787.           step ++;                                                         // Next step.
  788.           break;
  789.       }
  790.       if (transitionTime == 0 or transitionTime == NULL) {
  791.         transitionTime = 30;
  792.       }
  793.       showleds();
  794.     }
  795.  
  796.   }
  797.  
  798.  
  799.   EVERY_N_SECONDS(5) {
  800.     targetPalette = CRGBPalette16(CHSV(random8(), 255, random8(128, 255)), CHSV(random8(), 255, random8(128, 255)), CHSV(random8(), 192, random8(128, 255)), CHSV(random8(), 255, random8(128, 255)));
  801.   }
  802.  
  803.   //FLASH AND FADE SUPPORT
  804.   if (flash) {
  805.     if (startFlash) {
  806.       startFlash = false;
  807.       flashStartTime = millis();
  808.     }
  809.  
  810.     if ((millis() - flashStartTime) <= flashLength) {
  811.       if ((millis() - flashStartTime) % 1000 <= 500) {
  812.         setColor(flashRed, flashGreen, flashBlue);
  813.       }
  814.       else {
  815.         setColor(0, 0, 0);
  816.         // If you'd prefer the flashing to happen "on top of"
  817.         // the current color, uncomment the next line.
  818.         // setColor(realRed, realGreen, realBlue);
  819.       }
  820.     }
  821.     else {
  822.       flash = false;
  823.       effectString = oldeffectString;
  824.       if (onbeforeflash) { //keeps light off after flash if light was originally off
  825.         setColor(realRed, realGreen, realBlue);
  826.       }
  827.       else {
  828.         stateOn = false;
  829.         setColor(0, 0, 0);
  830.         sendState();
  831.       }
  832.     }
  833.   }
  834.  
  835.   if (startFade && effectString == "solid") {
  836.     // If we don't want to fade, skip it.
  837.     if (transitionTime == 0) {
  838.       setColor(realRed, realGreen, realBlue);
  839.  
  840.       redVal = realRed;
  841.       grnVal = realGreen;
  842.       bluVal = realBlue;
  843.  
  844.       startFade = false;
  845.     }
  846.     else {
  847.       loopCount = 0;
  848.       stepR = calculateStep(redVal, realRed);
  849.       stepG = calculateStep(grnVal, realGreen);
  850.       stepB = calculateStep(bluVal, realBlue);
  851.  
  852.       inFade = true;
  853.     }
  854.   }
  855.  
  856.   if (inFade) {
  857.     startFade = false;
  858.     unsigned long now = millis();
  859.     if (now - lastLoop > transitionTime) {
  860.       if (loopCount <= 1020) {
  861.         lastLoop = now;
  862.  
  863.         redVal = calculateVal(stepR, redVal, loopCount);
  864.         grnVal = calculateVal(stepG, grnVal, loopCount);
  865.         bluVal = calculateVal(stepB, bluVal, loopCount);
  866.  
  867.         if (effectString == "solid") {
  868.           setColor(redVal, grnVal, bluVal); // Write current values to LED pins
  869.         }
  870.         loopCount++;
  871.       }
  872.       else {
  873.         inFade = false;
  874.       }
  875.     }
  876.   }
  877. }
  878.  
  879.  
  880. /**************************** START TRANSITION FADER *****************************************/
  881. // From https://www.arduino.cc/en/Tutorial/ColorCrossfader
  882. /* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS
  883.   The program works like this:
  884.   Imagine a crossfade that moves the red LED from 0-10,
  885.     the green from 0-5, and the blue from 10 to 7, in
  886.     ten steps.
  887.     We'd want to count the 10 steps and increase or
  888.     decrease color values in evenly stepped increments.
  889.     Imagine a + indicates raising a value by 1, and a -
  890.     equals lowering it. Our 10 step fade would look like:
  891.     1 2 3 4 5 6 7 8 9 10
  892.   R + + + + + + + + + +
  893.   G   +   +   +   +   +
  894.   B     -     -     -
  895.   The red rises from 0 to 10 in ten steps, the green from
  896.   0-5 in 5 steps, and the blue falls from 10 to 7 in three steps.
  897.   In the real program, the color percentages are converted to
  898.   0-255 values, and there are 1020 steps (255*4).
  899.   To figure out how big a step there should be between one up- or
  900.   down-tick of one of the LED values, we call calculateStep(),
  901.   which calculates the absolute gap between the start and end values,
  902.   and then divides that gap by 1020 to determine the size of the step
  903.   between adjustments in the value.
  904. */
  905. int calculateStep(int prevValue, int endValue) {
  906.   int step = endValue - prevValue; // What's the overall gap?
  907.   if (step) {                      // If its non-zero,
  908.     step = 1020 / step;          //   divide by 1020
  909.   }
  910.  
  911.   return step;
  912. }
  913. /* The next function is calculateVal. When the loop value, i,
  914.    reaches the step size appropriate for one of the
  915.    colors, it increases or decreases the value of that color by 1.
  916.    (R, G, and B are each calculated separately.)
  917. */
  918. int calculateVal(int step, int val, int i) {
  919.   if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
  920.     if (step > 0) {              //   increment the value if step is positive...
  921.       val += 1;
  922.     }
  923.     else if (step < 0) {         //   ...or decrement it if step is negative
  924.       val -= 1;
  925.     }
  926.   }
  927.  
  928.   // Defensive driving: make sure val stays in the range 0-255
  929.   if (val > 255) {
  930.     val = 255;
  931.   }
  932.   else if (val < 0) {
  933.     val = 0;
  934.   }
  935.  
  936.   return val;
  937. }
  938.  
  939.  
  940.  
  941. /**************************** START STRIPLED PALETTE *****************************************/
  942. void setupStripedPalette( CRGB A, CRGB AB, CRGB B, CRGB BA) {
  943.   currentPalettestriped = CRGBPalette16(
  944.                             A, A, A, A, A, A, A, A, B, B, B, B, B, B, B, B
  945.                             //    A, A, A, A, A, A, A, A, B, B, B, B, B, B, B, B
  946.                           );
  947. }
  948.  
  949.  
  950.  
  951. /********************************** START FADE************************************************/
  952. void fadeall() {
  953.   for (int i = 0; i < NUM_LEDS; i++) {
  954.     leds[i].nscale8(250);  //for CYCLon
  955.   }
  956. }
  957.  
  958.  
  959.  
  960. /********************************** START FIRE **********************************************/
  961. void Fire2012WithPalette()
  962. {
  963.   // Array of temperature readings at each simulation cell
  964.   static byte heat[NUM_LEDS];
  965.  
  966.   // Step 1.  Cool down every cell a little
  967.   for ( int i = 0; i < NUM_LEDS; i++) {
  968.     heat[i] = qsub8( heat[i],  random8(0, ((COOLING * 10) / NUM_LEDS) + 2));
  969.   }
  970.  
  971.   // Step 2.  Heat from each cell drifts 'up' and diffuses a little
  972.   for ( int k = NUM_LEDS - 1; k >= 2; k--) {
  973.     heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
  974.   }
  975.  
  976.   // Step 3.  Randomly ignite new 'sparks' of heat near the bottom
  977.   if ( random8() < SPARKING ) {
  978.     int y = random8(7);
  979.     heat[y] = qadd8( heat[y], random8(160, 255) );
  980.   }
  981.  
  982.   // Step 4.  Map from heat cells to LED colors
  983.   for ( int j = 0; j < NUM_LEDS; j++) {
  984.     // Scale the heat value from 0-255 down to 0-240
  985.     // for best results with color palettes.
  986.     byte colorindex = scale8( heat[j], 240);
  987.     CRGB color = ColorFromPalette( gPal, colorindex);
  988.     int pixelnumber;
  989.     if ( gReverseDirection ) {
  990.       pixelnumber = (NUM_LEDS - 1) - j;
  991.     } else {
  992.       pixelnumber = j;
  993.     }
  994.     leds[pixelnumber] = color;
  995.   }
  996. }
  997.  
  998.  
  999.  
  1000. /********************************** START ADD GLITTER *********************************************/
  1001. void addGlitter( fract8 chanceOfGlitter)
  1002. {
  1003.   if ( random8() < chanceOfGlitter) {
  1004.     leds[ random16(NUM_LEDS) ] += CRGB::White;
  1005.   }
  1006. }
  1007.  
  1008.  
  1009.  
  1010. /********************************** START ADD GLITTER COLOR ****************************************/
  1011. void addGlitterColor( fract8 chanceOfGlitter, int red, int green, int blue)
  1012. {
  1013.   if ( random8() < chanceOfGlitter) {
  1014.     leds[ random16(NUM_LEDS) ] += CRGB(red, green, blue);
  1015.   }
  1016. }
  1017.  
  1018.  
  1019.  
  1020. /********************************** START SHOW LEDS ***********************************************/
  1021. void showleds() {
  1022.  
  1023.   delay(1);
  1024.  
  1025.   if (stateOn) {
  1026.     FastLED.setBrightness(brightness);  //EXECUTE EFFECT COLOR
  1027.     FastLED.show();
  1028.     if (transitionTime > 0 && transitionTime < 130) {  //Sets animation speed based on receieved value
  1029.       FastLED.delay(1000 / transitionTime);
  1030.       //delay(10*transitionTime);
  1031.     }
  1032.   }
  1033.   else if (startFade) {
  1034.     setColor(0, 0, 0);
  1035.     startFade = false;
  1036.   }
  1037. }
  1038. void temp2rgb(unsigned int kelvin) {
  1039.     int tmp_internal = kelvin / 100.0;
  1040.    
  1041.     // red
  1042.     if (tmp_internal <= 66) {
  1043.         red = 255;
  1044.     } else {
  1045.         float tmp_red = 329.698727446 * pow(tmp_internal - 60, -0.1332047592);
  1046.         if (tmp_red < 0) {
  1047.             red = 0;
  1048.         } else if (tmp_red > 255) {
  1049.             red = 255;
  1050.         } else {
  1051.             red = tmp_red;
  1052.         }
  1053.     }
  1054.    
  1055.     // green
  1056.     if (tmp_internal <=66){
  1057.         float tmp_green = 99.4708025861 * log(tmp_internal) - 161.1195681661;
  1058.         if (tmp_green < 0) {
  1059.             green = 0;
  1060.         } else if (tmp_green > 255) {
  1061.             green = 255;
  1062.         } else {
  1063.             green = tmp_green;
  1064.         }
  1065.     } else {
  1066.         float tmp_green = 288.1221695283 * pow(tmp_internal - 60, -0.0755148492);
  1067.         if (tmp_green < 0) {
  1068.             green = 0;
  1069.         } else if (tmp_green > 255) {
  1070.             green = 255;
  1071.         } else {
  1072.             green = tmp_green;
  1073.         }
  1074.     }
  1075.    
  1076.     // blue
  1077.     if (tmp_internal >=66) {
  1078.         blue = 255;
  1079.     } else if (tmp_internal <= 19) {
  1080.         blue = 0;
  1081.     } else {
  1082.         float tmp_blue = 138.5177312231 * log(tmp_internal - 10) - 305.0447927307;
  1083.         if (tmp_blue < 0) {
  1084.             blue = 0;
  1085.         } else if (tmp_blue > 255) {
  1086.             blue = 255;
  1087.         } else {
  1088.             blue = tmp_blue;
  1089.         }
  1090.     }
  1091. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement