Advertisement
Guest User

Untitled

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