Guest User

Untitled

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