Advertisement
Guest User

Untitled

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