Advertisement
Guest User

Untitled

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