Not_satoshinakamoto

Untitled

Nov 14th, 2023
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 30.12 KB | Help | 0 0
  1. #include <SPI.h>
  2. #include <MFRC522.h>
  3.  
  4. #define SS_PIN    15  // ESP32 pin GPIO5
  5. #define RST_PIN   16 // ESP32 pin GPIO27
  6.  
  7. MFRC522 rfid(SS_PIN, RST_PIN);
  8.  
  9. byte authorizedUID1[4] = {0x19, 0x3B, 0x21, 0xD9};
  10. byte authorizedUID2[4] = {0x46, 0x27, 0x35, 0x42};
  11. byte authorizedUID3[4] = {0x16, 0xE4, 0x31, 0x42};
  12.  
  13. //#define FASTLED_ALLOW_INTERRUPTS 1
  14. //#define INTERRUPT_THRESHOLD 1
  15. #define FASTLED_INTERRUPT_RETRY_COUNT 0
  16.  
  17. #include <FastLED.h>
  18. FASTLED_USING_NAMESPACE
  19.  
  20. extern "C" {
  21. #include "user_interface.h"
  22. }
  23.  
  24. #include <ESP8266WiFi.h>
  25. //#include <ESP8266mDNS.h>
  26. #include <ESP8266WebServer.h>
  27. #include <ESP8266HTTPUpdateServer.h>
  28. //#include <WebSocketsServer.h>
  29. #include <FS.h>
  30. #include <EEPROM.h>
  31. //#include <IRremoteESP8266.h>
  32. #include "GradientPalettes.h"
  33. #include <WiFiClient.h>
  34.  
  35. #define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
  36.  
  37. #include "Field.h"
  38.  
  39. //#define RECV_PIN D4
  40. //IRrecv irReceiver(RECV_PIN);
  41.  
  42. //#include "Commands.h"
  43.  
  44. ESP8266WebServer webServer(80);
  45. //WebSocketsServer webSocketsServer = WebSocketsServer(81);
  46. ESP8266HTTPUpdateServer httpUpdateServer;
  47.  
  48.  
  49. #include "FSBrowser.h"
  50.  
  51. #define DATA_PIN      2
  52. #define LED_TYPE      WS2811
  53. #define COLOR_ORDER   RGB
  54. #define NUM_LEDS      5
  55.  
  56. #define MILLI_AMPS         2000 // IMPORTANT: set the max milli-Amps of your power supply (4A = 4000mA)
  57. #define FRAMES_PER_SECOND  120  // here you can control the speed. With the Access Point / Web Server the animations run a bit slower.
  58.  
  59. const bool apMode = true;
  60.  
  61. #include "Secrets.h" // this file is intentionally not included in the sketch, so nobody accidentally commits their secret information.
  62. // create a Secrets.h file with the following:
  63.  
  64.  
  65. CRGB leds[NUM_LEDS];
  66.  
  67. const uint8_t brightnessCount = 5;
  68. uint8_t brightnessMap[brightnessCount] = { 16, 32, 64, 128, 255 };
  69. uint8_t brightnessIndex = 0;
  70.  
  71. // ten seconds per color palette makes a good demo
  72. // 20-120 is better for deployment
  73. uint8_t secondsPerPalette = 10;
  74.  
  75. // COOLING: How much does the air cool as it rises?
  76. // Less cooling = taller flames.  More cooling = shorter flames.
  77. // Default 50, suggested range 20-100
  78. uint8_t cooling = 49;
  79.  
  80. // SPARKING: What chance (out of 255) is there that a new spark will be lit?
  81. // Higher chance = more roaring fire.  Lower chance = more flickery fire.
  82. // Default 120, suggested range 50-200.
  83. uint8_t sparking = 60;
  84.  
  85. uint8_t speed = 30;
  86.  
  87. ///////////////////////////////////////////////////////////////////////
  88.  
  89. // Forward declarations of an array of cpt-city gradient palettes, and
  90. // a count of how many there are.  The actual color palette definitions
  91. // are at the bottom of this file.
  92. extern const TProgmemRGBGradientPalettePtr gGradientPalettes[];
  93.  
  94. uint8_t gCurrentPaletteNumber = 0;
  95.  
  96. CRGBPalette16 gCurrentPalette( CRGB::Black);
  97. CRGBPalette16 gTargetPalette( gGradientPalettes[0] );
  98.  
  99. CRGBPalette16 IceColors_p = CRGBPalette16(CRGB::Black, CRGB::Blue, CRGB::Aqua, CRGB::White);
  100.  
  101. uint8_t currentPatternIndex = 0; // Index number of which pattern is current
  102. uint8_t autoplay = 0;
  103.  
  104. uint8_t autoplayDuration = 10;
  105. unsigned long autoPlayTimeout = 0;
  106.  
  107. uint8_t currentPaletteIndex = 0;
  108.  
  109. uint8_t gHue = 0; // rotating "base color" used by many of the patterns
  110.  
  111. CRGB solidColor = CRGB::Blue;
  112.  
  113. // scale the brightness of all pixels down
  114. void dimAll(byte value)
  115. {
  116.   for (int i = 0; i < NUM_LEDS; i++) {
  117.     leds[i].nscale8(value);
  118.   }
  119. }
  120.  
  121. typedef void (*Pattern)();
  122. typedef Pattern PatternList[];
  123. typedef struct {
  124.   Pattern pattern;
  125.   String name;
  126. } PatternAndName;
  127. typedef PatternAndName PatternAndNameList[];
  128.  
  129. #include "Twinkles.h"
  130. #include "TwinkleFOX.h"
  131.  
  132. // List of patterns to cycle through.  Each is defined as a separate function below.
  133.  
  134. PatternAndNameList patterns = {
  135.   { pride,                  "Pride" },
  136.   { colorWaves,             "Color Waves" },
  137.  
  138.   // twinkle patterns
  139.   { rainbowTwinkles,        "Rainbow Twinkles" },
  140.   { snowTwinkles,           "Snow Twinkles" },
  141.   { cloudTwinkles,          "Cloud Twinkles" },
  142.   { incandescentTwinkles,   "Incandescent Twinkles" },
  143.  
  144.   // TwinkleFOX patterns
  145.   { retroC9Twinkles,        "Retro C9 Twinkles" },
  146.   { redWhiteTwinkles,       "Red & White Twinkles" },
  147.   { blueWhiteTwinkles,      "Blue & White Twinkles" },
  148.   { redGreenWhiteTwinkles,  "Red, Green & White Twinkles" },
  149.   { fairyLightTwinkles,     "Fairy Light Twinkles" },
  150.   { snow2Twinkles,          "Snow 2 Twinkles" },
  151.   { hollyTwinkles,          "Holly Twinkles" },
  152.   { iceTwinkles,            "Ice Twinkles" },
  153.   { partyTwinkles,          "Party Twinkles" },
  154.   { forestTwinkles,         "Forest Twinkles" },
  155.   { lavaTwinkles,           "Lava Twinkles" },
  156.   { fireTwinkles,           "Fire Twinkles" },
  157.   { cloud2Twinkles,         "Cloud 2 Twinkles" },
  158.   { oceanTwinkles,          "Ocean Twinkles" },
  159.  
  160.   { rainbow,                "Rainbow" },
  161.   { rainbowWithGlitter,     "Rainbow With Glitter" },
  162.   { rainbowSolid,           "Solid Rainbow" },
  163.   { confetti,               "Confetti" },
  164.   { sinelon,                "Sinelon" },
  165.   { bpm,                    "Beat" },
  166.   { juggle,                 "Juggle" },
  167.   { fire,                   "Fire" },
  168.   { water,                  "Water" },
  169.  
  170.   { showSolidColor,         "Solid Color" }
  171. };
  172.  
  173. const uint8_t patternCount = ARRAY_SIZE(patterns);
  174.  
  175. typedef struct {
  176.   CRGBPalette16 palette;
  177.   String name;
  178. } PaletteAndName;
  179. typedef PaletteAndName PaletteAndNameList[];
  180.  
  181. const CRGBPalette16 palettes[] = {
  182.   RainbowColors_p,
  183.   RainbowStripeColors_p,
  184.   CloudColors_p,
  185.   LavaColors_p,
  186.   OceanColors_p,
  187.   ForestColors_p,
  188.   PartyColors_p,
  189.   HeatColors_p
  190. };
  191.  
  192. const uint8_t paletteCount = ARRAY_SIZE(palettes);
  193.  
  194. const String paletteNames[paletteCount] = {
  195.   "Rainbow",
  196.   "Rainbow Stripe",
  197.   "Cloud",
  198.   "Lava",
  199.   "Ocean",
  200.   "Forest",
  201.   "Party",
  202.   "Heat",
  203. };
  204.  
  205. #include "Fields.h"
  206.  
  207.  
  208. void setup() {
  209.   WiFi.setSleepMode(WIFI_NONE_SLEEP);
  210.  
  211.   Serial.begin(9600);
  212.   delay(100);
  213.   Serial.setDebugOutput(true);
  214.  
  215.   SPI.begin(); // init SPI bus
  216.   rfid.PCD_Init(); // init MFRC522
  217.  
  218.   FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);         // for WS2812 (Neopixel)
  219.   //FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS); // for APA102 (Dotstar)
  220.   FastLED.setDither(false);
  221.   FastLED.setCorrection(TypicalLEDStrip);
  222.   FastLED.setBrightness(brightness);
  223.   FastLED.setMaxPowerInVoltsAndMilliamps(5, MILLI_AMPS);
  224.   fill_solid(leds, NUM_LEDS, CRGB::Black);
  225.   FastLED.show();
  226.  
  227.   EEPROM.begin(512);
  228.   loadSettings();
  229.  
  230.   FastLED.setBrightness(brightness);
  231.  
  232.   //  irReceiver.enableIRIn(); // Start the receiver
  233.  
  234.   Serial.println();
  235.   Serial.print( F("Heap: ") ); Serial.println(system_get_free_heap_size());
  236.   Serial.print( F("Boot Vers: ") ); Serial.println(system_get_boot_version());
  237.   Serial.print( F("CPU: ") ); Serial.println(system_get_cpu_freq());
  238.   Serial.print( F("SDK: ") ); Serial.println(system_get_sdk_version());
  239.   Serial.print( F("Chip ID: ") ); Serial.println(system_get_chip_id());
  240.   Serial.print( F("Flash ID: ") ); Serial.println(spi_flash_get_id());
  241.   Serial.print( F("Flash Size: ") ); Serial.println(ESP.getFlashChipRealSize());
  242.   Serial.print( F("Vcc: ") ); Serial.println(ESP.getVcc());
  243.   Serial.println();
  244.  
  245.   SPIFFS.begin();
  246.   {
  247.     Serial.println("SPIFFS contents:");
  248.  
  249.     Dir dir = SPIFFS.openDir("/");
  250.     while (dir.next()) {
  251.       String fileName = dir.fileName();
  252.       size_t fileSize = dir.fileSize();
  253.       Serial.printf("FS File: %s, size: %s\n", fileName.c_str(), String(fileSize).c_str());
  254.     }
  255.     Serial.printf("\n");
  256.   }
  257.  
  258.   //disabled due to https://github.com/jasoncoon/esp8266-fastled-webserver/issues/62
  259.   //initializeWiFi();
  260.  
  261.   if (apMode)
  262.   {
  263.     WiFi.mode(WIFI_AP);
  264.  
  265.     // Do a little work to get a unique-ish name. Append the
  266.     // last two bytes of the MAC (HEX'd) to "Thing-":
  267.     uint8_t mac[WL_MAC_ADDR_LENGTH];
  268.     WiFi.softAPmacAddress(mac);
  269.     String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) +
  270.                    String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
  271.     macID.toUpperCase();
  272.     String AP_NameString = "MaiasLights " + macID;
  273.  
  274.     char AP_NameChar[AP_NameString.length() + 1];
  275.     memset(AP_NameChar, 0, AP_NameString.length() + 1);
  276.  
  277.     for (int i = 0; i < AP_NameString.length(); i++)
  278.       AP_NameChar[i] = AP_NameString.charAt(i);
  279.  
  280.     WiFi.softAP(AP_NameChar, WiFiAPPSK);
  281.  
  282.     Serial.printf("Connect to Wi-Fi access point: %s\n", AP_NameChar);
  283.     Serial.println("and open http://192.168.4.1 in your browser");
  284.   }
  285.   else
  286.   {
  287.     Serial.printf("Connecting to %s\n", ssid);
  288.     if (String(WiFi.SSID()) != String(ssid)) {
  289.       WiFi.begin(ssid, password);
  290.       WiFi.disconnect();  //Prevent connecting to wifi based on previous configuration      WiFi.hostname(deviceName);      // DHCP Hostname (useful for finding device for static lease)
  291.       WiFi.begin(ssid, password);
  292.     WiFi.mode(WIFI_STA);
  293.     }
  294.   }
  295.  
  296.   httpUpdateServer.setup(&webServer);
  297.  
  298.   webServer.on("/all", HTTP_GET, []() {
  299.     String json = getFieldsJson(fields, fieldCount);
  300.     webServer.send(200, "text/json", json);
  301.   });
  302.  
  303.   webServer.on("/fieldValue", HTTP_GET, []() {
  304.     String name = webServer.arg("name");
  305.     String value = getFieldValue(name, fields, fieldCount);
  306.     webServer.send(200, "text/json", value);
  307.   });
  308.  
  309.   webServer.on("/fieldValue", HTTP_POST, []() {
  310.     String name = webServer.arg("name");
  311.     String value = webServer.arg("value");
  312.     String newValue = setFieldValue(name, value, fields, fieldCount);
  313.     webServer.send(200, "text/json", newValue);
  314.   });
  315.  
  316.   webServer.on("/power", HTTP_POST, []() {
  317.     String value = webServer.arg("value");
  318.     setPower(value.toInt());
  319.     sendInt(power);
  320.   });
  321.  
  322.   webServer.on("/cooling", HTTP_POST, []() {
  323.     String value = webServer.arg("value");
  324.     cooling = value.toInt();
  325.     broadcastInt("cooling", cooling);
  326.     sendInt(cooling);
  327.   });
  328.  
  329.   webServer.on("/sparking", HTTP_POST, []() {
  330.     String value = webServer.arg("value");
  331.     sparking = value.toInt();
  332.     broadcastInt("sparking", sparking);
  333.     sendInt(sparking);
  334.   });
  335.  
  336.   webServer.on("/speed", HTTP_POST, []() {
  337.     String value = webServer.arg("value");
  338.     speed = value.toInt();
  339.     broadcastInt("speed", speed);
  340.     sendInt(speed);
  341.   });
  342.  
  343.   webServer.on("/twinkleSpeed", HTTP_POST, []() {
  344.     String value = webServer.arg("value");
  345.     twinkleSpeed = value.toInt();
  346.     if (twinkleSpeed < 0) twinkleSpeed = 0;
  347.     else if (twinkleSpeed > 8) twinkleSpeed = 8;
  348.     broadcastInt("twinkleSpeed", twinkleSpeed);
  349.     sendInt(twinkleSpeed);
  350.   });
  351.  
  352.   webServer.on("/twinkleDensity", HTTP_POST, []() {
  353.     String value = webServer.arg("value");
  354.     twinkleDensity = value.toInt();
  355.     if (twinkleDensity < 0) twinkleDensity = 0;
  356.     else if (twinkleDensity > 8) twinkleDensity = 8;
  357.     broadcastInt("twinkleDensity", twinkleDensity);
  358.     sendInt(twinkleDensity);
  359.   });
  360.  
  361.   webServer.on("/solidColor", HTTP_POST, []() {
  362.     String r = webServer.arg("r");
  363.     String g = webServer.arg("g");
  364.     String b = webServer.arg("b");
  365.     setSolidColor(r.toInt(), g.toInt(), b.toInt());
  366.     sendString(String(solidColor.r) + "," + String(solidColor.g) + "," + String(solidColor.b));
  367.   });
  368.  
  369.   webServer.on("/pattern", HTTP_POST, []() {
  370.     String value = webServer.arg("value");
  371.     setPattern(value.toInt());
  372.     sendInt(currentPatternIndex);
  373.   });
  374.  
  375.   webServer.on("/patternName", HTTP_POST, []() {
  376.     String value = webServer.arg("value");
  377.     setPatternName(value);
  378.     sendInt(currentPatternIndex);
  379.   });
  380.  
  381.   webServer.on("/palette", HTTP_POST, []() {
  382.     String value = webServer.arg("value");
  383.     setPalette(value.toInt());
  384.     sendInt(currentPaletteIndex);
  385.   });
  386.  
  387.   webServer.on("/paletteName", HTTP_POST, []() {
  388.     String value = webServer.arg("value");
  389.     setPaletteName(value);
  390.     sendInt(currentPaletteIndex);
  391.   });
  392.  
  393.   webServer.on("/brightness", HTTP_POST, []() {
  394.     String value = webServer.arg("value");
  395.     setBrightness(value.toInt());
  396.     sendInt(brightness);
  397.   });
  398.  
  399.   webServer.on("/autoplay", HTTP_POST, []() {
  400.     String value = webServer.arg("value");
  401.     setAutoplay(value.toInt());
  402.     sendInt(autoplay);
  403.   });
  404.  
  405.   webServer.on("/autoplayDuration", HTTP_POST, []() {
  406.     String value = webServer.arg("value");
  407.     setAutoplayDuration(value.toInt());
  408.     sendInt(autoplayDuration);
  409.   });
  410.  
  411.   //list directory
  412.   webServer.on("/list", HTTP_GET, handleFileList);
  413.   //load editor
  414.   webServer.on("/edit", HTTP_GET, []() {
  415.     if (!handleFileRead("/edit.htm")) webServer.send(404, "text/plain", "FileNotFound");
  416.   });
  417.   //create file
  418.   webServer.on("/edit", HTTP_PUT, handleFileCreate);
  419.   //delete file
  420.   webServer.on("/edit", HTTP_DELETE, handleFileDelete);
  421.   //first callback is called after the request has ended with all parsed arguments
  422.   //second callback handles file uploads at that location
  423.   webServer.on("/edit", HTTP_POST, []() {
  424.     webServer.send(200, "text/plain", "");
  425.   }, handleFileUpload);
  426.  
  427.   webServer.serveStatic("/", SPIFFS, "/", "max-age=86400");
  428.  
  429.   webServer.begin();
  430.   Serial.println("HTTP web server started");
  431.  
  432.   //  webSocketsServer.begin();
  433.   //  webSocketsServer.onEvent(webSocketEvent);
  434.   //  Serial.println("Web socket server started");
  435.  
  436.   autoPlayTimeout = millis() + (autoplayDuration * 1000);
  437. }
  438.  
  439. void sendInt(uint8_t value)
  440. {
  441.   sendString(String(value));
  442. }
  443.  
  444. void sendString(String value)
  445. {
  446.   webServer.send(200, "text/plain", value);
  447. }
  448.  
  449. void broadcastInt(String name, uint8_t value)
  450. {
  451.   String json = "{\"name\":\"" + name + "\",\"value\":" + String(value) + "}";
  452.   //  webSocketsServer.broadcastTXT(json);
  453. }
  454.  
  455. void broadcastString(String name, String value)
  456. {
  457.   String json = "{\"name\":\"" + name + "\",\"value\":\"" + String(value) + "\"}";
  458.   //  webSocketsServer.broadcastTXT(json);
  459. }
  460.  
  461. void loop() {
  462.   if (rfid.PICC_IsNewCardPresent()) { // new tag is available
  463.     if (rfid.PICC_ReadCardSerial()) { // NUID has been readed
  464.       MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  465.  
  466.       if (rfid.uid.uidByte[0] == authorizedUID1[0] &&
  467.           rfid.uid.uidByte[1] == authorizedUID1[1] &&
  468.           rfid.uid.uidByte[2] == authorizedUID1[2] &&
  469.           rfid.uid.uidByte[3] == authorizedUID1[3] ) {
  470.         Serial.println("Authorized Tag 1");
  471.         webServer.sendHeader("Location", "/power?value=1");
  472.         webServer.send(200);
  473.       }
  474.       else
  475.       if (rfid.uid.uidByte[0] == authorizedUID3[0] &&
  476.           rfid.uid.uidByte[1] == authorizedUID3[1] &&
  477.           rfid.uid.uidByte[2] == authorizedUID3[2] &&
  478.           rfid.uid.uidByte[3] == authorizedUID3[3] ) {
  479.         Serial.println("LIGHTS");
  480.       }
  481.       else
  482.       {
  483.         Serial.print("Unauthorized Tag with UID:");
  484.         for (int i = 0; i < rfid.uid.size; i++) {
  485.           Serial.print(rfid.uid.uidByte[i] < 0x10 ? " 0" : " ");
  486.           Serial.print(rfid.uid.uidByte[i], HEX);
  487.         }
  488.         Serial.println();
  489.       }
  490.  
  491.       rfid.PICC_HaltA(); // halt PICC
  492.       rfid.PCD_StopCrypto1(); // stop encryption on PCD
  493.     }
  494.   }
  495.  
  496.   // Add entropy to random number generator; we use a lot of it.
  497.   random16_add_entropy(random(65535));
  498.  
  499.   //  dnsServer.processNextRequest();
  500.   //  webSocketsServer.loop();
  501.   webServer.handleClient();
  502.  
  503.   //  handleIrInput();
  504.  
  505.   if (power == 0) {
  506.     fill_solid(leds, NUM_LEDS, CRGB::Black);
  507.     FastLED.show();
  508.     // FastLED.delay(15);
  509.     return;
  510.   }
  511.  
  512.   static bool hasConnected = false;
  513.   EVERY_N_SECONDS(1) {
  514.     if (WiFi.status() != WL_CONNECTED) {
  515.       //      Serial.printf("Connecting to %s\n", ssid);
  516.       hasConnected = false;
  517.     }
  518.     else if (!hasConnected) {
  519.       hasConnected = true;
  520.       Serial.print("Connected! Open http://");
  521.       Serial.print(WiFi.localIP());
  522.       Serial.println(" in your browser");
  523.     }
  524.   }
  525.  
  526.   // EVERY_N_SECONDS(10) {
  527.   //   Serial.print( F("Heap: ") ); Serial.println(system_get_free_heap_size());
  528.   // }
  529.  
  530.   // change to a new cpt-city gradient palette
  531.   EVERY_N_SECONDS( secondsPerPalette ) {
  532.     gCurrentPaletteNumber = addmod8( gCurrentPaletteNumber, 1, gGradientPaletteCount);
  533.     gTargetPalette = gGradientPalettes[ gCurrentPaletteNumber ];
  534.   }
  535.  
  536.   EVERY_N_MILLISECONDS(40) {
  537.     // slowly blend the current palette to the next
  538.     nblendPaletteTowardPalette( gCurrentPalette, gTargetPalette, 8);
  539.     gHue++;  // slowly cycle the "base color" through the rainbow
  540.   }
  541.  
  542.   if (autoplay && (millis() > autoPlayTimeout)) {
  543.     adjustPattern(true);
  544.     autoPlayTimeout = millis() + (autoplayDuration * 1000);
  545.   }
  546.  
  547.   // Call the current pattern function once, updating the 'leds' array
  548.   patterns[currentPatternIndex].pattern();
  549.  
  550.   FastLED.show();
  551.  
  552.   // insert a delay to keep the framerate modest
  553.   FastLED.delay(1000 / FRAMES_PER_SECOND);
  554. }
  555.  
  556. void loadSettings()
  557. {
  558.   brightness = EEPROM.read(0);
  559.  
  560.   currentPatternIndex = EEPROM.read(1);
  561.   if (currentPatternIndex < 0)
  562.     currentPatternIndex = 0;
  563.   else if (currentPatternIndex >= patternCount)
  564.     currentPatternIndex = patternCount - 1;
  565.  
  566.   byte r = EEPROM.read(2);
  567.   byte g = EEPROM.read(3);
  568.   byte b = EEPROM.read(4);
  569.  
  570.   if (r == 0 && g == 0 && b == 0)
  571.   {
  572.   }
  573.   else
  574.   {
  575.     solidColor = CRGB(r, g, b);
  576.   }
  577.  
  578.   power = EEPROM.read(5);
  579.  
  580.   autoplay = EEPROM.read(6);
  581.   autoplayDuration = EEPROM.read(7);
  582.  
  583.   currentPaletteIndex = EEPROM.read(8);
  584.   if (currentPaletteIndex < 0)
  585.     currentPaletteIndex = 0;
  586.   else if (currentPaletteIndex >= paletteCount)
  587.     currentPaletteIndex = paletteCount - 1;
  588. }
  589.  
  590. void setPower(uint8_t value)
  591. {
  592.   power = value == 0 ? 0 : 1;
  593.  
  594.   EEPROM.write(5, power);
  595.   EEPROM.commit();
  596.  
  597.   broadcastInt("power", power);
  598. }
  599.  
  600. void setAutoplay(uint8_t value)
  601. {
  602.   autoplay = value == 0 ? 0 : 1;
  603.  
  604.   EEPROM.write(6, autoplay);
  605.   EEPROM.commit();
  606.  
  607.   broadcastInt("autoplay", autoplay);
  608. }
  609.  
  610. void setAutoplayDuration(uint8_t value)
  611. {
  612.   autoplayDuration = value;
  613.  
  614.   EEPROM.write(7, autoplayDuration);
  615.   EEPROM.commit();
  616.  
  617.   autoPlayTimeout = millis() + (autoplayDuration * 1000);
  618.  
  619.   broadcastInt("autoplayDuration", autoplayDuration);
  620. }
  621.  
  622. void setSolidColor(CRGB color)
  623. {
  624.   setSolidColor(color.r, color.g, color.b);
  625. }
  626.  
  627. void setSolidColor(uint8_t r, uint8_t g, uint8_t b)
  628. {
  629.   solidColor = CRGB(r, g, b);
  630.  
  631.   EEPROM.write(2, r);
  632.   EEPROM.write(3, g);
  633.   EEPROM.write(4, b);
  634.   EEPROM.commit();
  635.  
  636.   setPattern(patternCount - 1);
  637.  
  638.   broadcastString("color", String(solidColor.r) + "," + String(solidColor.g) + "," + String(solidColor.b));
  639. }
  640.  
  641. // increase or decrease the current pattern number, and wrap around at the ends
  642. void adjustPattern(bool up)
  643. {
  644.   if (up)
  645.     currentPatternIndex++;
  646.   else
  647.     currentPatternIndex--;
  648.  
  649.   // wrap around at the ends
  650.   if (currentPatternIndex < 0)
  651.     currentPatternIndex = patternCount - 1;
  652.   if (currentPatternIndex >= patternCount)
  653.     currentPatternIndex = 0;
  654.  
  655.   if (autoplay == 0) {
  656.     EEPROM.write(1, currentPatternIndex);
  657.     EEPROM.commit();
  658.   }
  659.  
  660.   broadcastInt("pattern", currentPatternIndex);
  661. }
  662.  
  663. void setPattern(uint8_t value)
  664. {
  665.   if (value >= patternCount)
  666.     value = patternCount - 1;
  667.  
  668.   currentPatternIndex = value;
  669.  
  670.   if (autoplay == 0) {
  671.     EEPROM.write(1, currentPatternIndex);
  672.     EEPROM.commit();
  673.   }
  674.  
  675.   broadcastInt("pattern", currentPatternIndex);
  676. }
  677.  
  678. void setPatternName(String name)
  679. {
  680.   for (uint8_t i = 0; i < patternCount; i++) {
  681.     if (patterns[i].name == name) {
  682.       setPattern(i);
  683.       break;
  684.     }
  685.   }
  686. }
  687.  
  688. void setPalette(uint8_t value)
  689. {
  690.   if (value >= paletteCount)
  691.     value = paletteCount - 1;
  692.  
  693.   currentPaletteIndex = value;
  694.  
  695.   EEPROM.write(8, currentPaletteIndex);
  696.   EEPROM.commit();
  697.  
  698.   broadcastInt("palette", currentPaletteIndex);
  699. }
  700.  
  701. void setPaletteName(String name)
  702. {
  703.   for (uint8_t i = 0; i < paletteCount; i++) {
  704.     if (paletteNames[i] == name) {
  705.       setPalette(i);
  706.       break;
  707.     }
  708.   }
  709. }
  710.  
  711. void adjustBrightness(bool up)
  712. {
  713.   if (up && brightnessIndex < brightnessCount - 1)
  714.     brightnessIndex++;
  715.   else if (!up && brightnessIndex > 0)
  716.     brightnessIndex--;
  717.  
  718.   brightness = brightnessMap[brightnessIndex];
  719.  
  720.   FastLED.setBrightness(brightness);
  721.  
  722.   EEPROM.write(0, brightness);
  723.   EEPROM.commit();
  724.  
  725.   broadcastInt("brightness", brightness);
  726. }
  727.  
  728. void setBrightness(uint8_t value)
  729. {
  730.   if (value > 255)
  731.     value = 255;
  732.   else if (value < 0) value = 0;
  733.  
  734.   brightness = value;
  735.  
  736.   FastLED.setBrightness(brightness);
  737.  
  738.   EEPROM.write(0, brightness);
  739.   EEPROM.commit();
  740.  
  741.   broadcastInt("brightness", brightness);
  742. }
  743.  
  744. void strandTest()
  745. {
  746.   static uint8_t i = 0;
  747.  
  748.   EVERY_N_SECONDS(1)
  749.   {
  750.     i++;
  751.     if (i >= NUM_LEDS)
  752.       i = 0;
  753.   }
  754.  
  755.   fill_solid(leds, NUM_LEDS, CRGB::Black);
  756.  
  757.   leds[i] = solidColor;
  758. }
  759.  
  760. void showSolidColor()
  761. {
  762.   fill_solid(leds, NUM_LEDS, solidColor);
  763. }
  764.  
  765. // Patterns from FastLED example DemoReel100: https://github.com/FastLED/FastLED/blob/master/examples/DemoReel100/DemoReel100.ino
  766.  
  767. void rainbow()
  768. {
  769.   // FastLED's built-in rainbow generator
  770.   fill_rainbow( leds, NUM_LEDS, gHue, 255 / NUM_LEDS);
  771. }
  772.  
  773. void rainbowWithGlitter()
  774. {
  775.   // built-in FastLED rainbow, plus some random sparkly glitter
  776.   rainbow();
  777.   addGlitter(80);
  778. }
  779.  
  780. void rainbowSolid()
  781. {
  782.   fill_solid(leds, NUM_LEDS, CHSV(gHue, 255, 255));
  783. }
  784.  
  785. void confetti()
  786. {
  787.   // random colored speckles that blink in and fade smoothly
  788.   fadeToBlackBy( leds, NUM_LEDS, 10);
  789.   int pos = random16(NUM_LEDS);
  790.   // leds[pos] += CHSV( gHue + random8(64), 200, 255);
  791.   leds[pos] += ColorFromPalette(palettes[currentPaletteIndex], gHue + random8(64));
  792. }
  793.  
  794. void sinelon()
  795. {
  796.   // a colored dot sweeping back and forth, with fading trails
  797.   fadeToBlackBy( leds, NUM_LEDS, 20);
  798.   int pos = beatsin16(speed, 0, NUM_LEDS);
  799.   static int prevpos = 0;
  800.   CRGB color = ColorFromPalette(palettes[currentPaletteIndex], gHue, 255);
  801.   if ( pos < prevpos ) {
  802.     fill_solid( leds + pos, (prevpos - pos) + 1, color);
  803.   } else {
  804.     fill_solid( leds + prevpos, (pos - prevpos) + 1, color);
  805.   }
  806.   prevpos = pos;
  807. }
  808.  
  809. void bpm()
  810. {
  811.   // colored stripes pulsing at a defined Beats-Per-Minute (BPM)
  812.   uint8_t beat = beatsin8( speed, 64, 255);
  813.   CRGBPalette16 palette = palettes[currentPaletteIndex];
  814.   for ( int i = 0; i < NUM_LEDS; i++) {
  815.     leds[i] = ColorFromPalette(palette, gHue + (i * 2), beat - gHue + (i * 10));
  816.   }
  817. }
  818.  
  819. void juggle()
  820. {
  821.   static uint8_t    numdots =   4; // Number of dots in use.
  822.   static uint8_t   faderate =   2; // How long should the trails be. Very low value = longer trails.
  823.   static uint8_t     hueinc =  255 / numdots - 1; // Incremental change in hue between each dot.
  824.   static uint8_t    thishue =   0; // Starting hue.
  825.   static uint8_t     curhue =   0; // The current hue
  826.   static uint8_t    thissat = 255; // Saturation of the colour.
  827.   static uint8_t thisbright = 255; // How bright should the LED/display be.
  828.   static uint8_t   basebeat =   5; // Higher = faster movement.
  829.  
  830.   static uint8_t lastSecond =  99;  // Static variable, means it's only defined once. This is our 'debounce' variable.
  831.   uint8_t secondHand = (millis() / 1000) % 30; // IMPORTANT!!! Change '30' to a different value to change duration of the loop.
  832.  
  833.   if (lastSecond != secondHand) { // Debounce to make sure we're not repeating an assignment.
  834.     lastSecond = secondHand;
  835.     switch (secondHand) {
  836.       case  0: numdots = 1; basebeat = 20; hueinc = 16; faderate = 2; thishue = 0; break; // You can change values here, one at a time , or altogether.
  837.       case 10: numdots = 4; basebeat = 10; hueinc = 16; faderate = 8; thishue = 128; break;
  838.       case 20: numdots = 8; basebeat =  3; hueinc =  0; faderate = 8; thishue = random8(); break; // Only gets called once, and not continuously for the next several seconds. Therefore, no rainbows.
  839.       case 30: break;
  840.     }
  841.   }
  842.  
  843.   // Several colored dots, weaving in and out of sync with each other
  844.   curhue = thishue; // Reset the hue values.
  845.   fadeToBlackBy(leds, NUM_LEDS, faderate);
  846.   for ( int i = 0; i < numdots; i++) {
  847.     //beat16 is a FastLED 3.1 function
  848.     leds[beatsin16(basebeat + i + numdots, 0, NUM_LEDS)] += CHSV(gHue + curhue, thissat, thisbright);
  849.     curhue += hueinc;
  850.   }
  851. }
  852.  
  853. void fire()
  854. {
  855.   heatMap(HeatColors_p, true);
  856. }
  857.  
  858. void water()
  859. {
  860.   heatMap(IceColors_p, false);
  861. }
  862.  
  863. // Pride2015 by Mark Kriegsman: https://gist.github.com/kriegsman/964de772d64c502760e5
  864. // This function draws rainbows with an ever-changing,
  865. // widely-varying set of parameters.
  866. void pride()
  867. {
  868.   static uint16_t sPseudotime = 0;
  869.   static uint16_t sLastMillis = 0;
  870.   static uint16_t sHue16 = 0;
  871.  
  872.   uint8_t sat8 = beatsin88( 87, 220, 250);
  873.   uint8_t brightdepth = beatsin88( 341, 96, 224);
  874.   uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256));
  875.   uint8_t msmultiplier = beatsin88(147, 23, 60);
  876.  
  877.   uint16_t hue16 = sHue16;//gHue * 256;
  878.   uint16_t hueinc16 = beatsin88(113, 1, 3000);
  879.  
  880.   uint16_t ms = millis();
  881.   uint16_t deltams = ms - sLastMillis ;
  882.   sLastMillis  = ms;
  883.   sPseudotime += deltams * msmultiplier;
  884.   sHue16 += deltams * beatsin88( 400, 5, 9);
  885.   uint16_t brightnesstheta16 = sPseudotime;
  886.  
  887.   for ( uint16_t i = 0 ; i < NUM_LEDS; i++) {
  888.     hue16 += hueinc16;
  889.     uint8_t hue8 = hue16 / 256;
  890.  
  891.     brightnesstheta16  += brightnessthetainc16;
  892.     uint16_t b16 = sin16( brightnesstheta16  ) + 32768;
  893.  
  894.     uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
  895.     uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
  896.     bri8 += (255 - brightdepth);
  897.  
  898.     CRGB newcolor = CHSV( hue8, sat8, bri8);
  899.  
  900.     uint16_t pixelnumber = i;
  901.     pixelnumber = (NUM_LEDS - 1) - pixelnumber;
  902.  
  903.     nblend( leds[pixelnumber], newcolor, 64);
  904.   }
  905. }
  906.  
  907. void radialPaletteShift()
  908. {
  909.   for (uint16_t i = 0; i < NUM_LEDS; i++) {
  910.     // leds[i] = ColorFromPalette( gCurrentPalette, gHue + sin8(i*16), brightness);
  911.     leds[i] = ColorFromPalette(gCurrentPalette, i + gHue, 255, LINEARBLEND);
  912.   }
  913. }
  914.  
  915. // based on FastLED example Fire2012WithPalette: https://github.com/FastLED/FastLED/blob/master/examples/Fire2012WithPalette/Fire2012WithPalette.ino
  916. void heatMap(CRGBPalette16 palette, bool up)
  917. {
  918.   fill_solid(leds, NUM_LEDS, CRGB::Black);
  919.  
  920.   // Add entropy to random number generator; we use a lot of it.
  921.   random16_add_entropy(random(256));
  922.  
  923.   // Array of temperature readings at each simulation cell
  924.   static byte heat[NUM_LEDS];
  925.  
  926.   byte colorindex;
  927.  
  928.   // Step 1.  Cool down every cell a little
  929.   for ( uint16_t i = 0; i < NUM_LEDS; i++) {
  930.     heat[i] = qsub8( heat[i],  random8(0, ((cooling * 10) / NUM_LEDS) + 2));
  931.   }
  932.  
  933.   // Step 2.  Heat from each cell drifts 'up' and diffuses a little
  934.   for ( uint16_t k = NUM_LEDS - 1; k >= 2; k--) {
  935.     heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
  936.   }
  937.  
  938.   // Step 3.  Randomly ignite new 'sparks' of heat near the bottom
  939.   if ( random8() < sparking ) {
  940.     int y = random8(7);
  941.     heat[y] = qadd8( heat[y], random8(160, 255) );
  942.   }
  943.  
  944.   // Step 4.  Map from heat cells to LED colors
  945.   for ( uint16_t j = 0; j < NUM_LEDS; j++) {
  946.     // Scale the heat value from 0-255 down to 0-240
  947.     // for best results with color palettes.
  948.     colorindex = scale8(heat[j], 190);
  949.  
  950.     CRGB color = ColorFromPalette(palette, colorindex);
  951.  
  952.     if (up) {
  953.       leds[j] = color;
  954.     }
  955.     else {
  956.       leds[(NUM_LEDS - 1) - j] = color;
  957.     }
  958.   }
  959. }
  960.  
  961. void addGlitter( uint8_t chanceOfGlitter)
  962. {
  963.   if ( random8() < chanceOfGlitter) {
  964.     leds[ random16(NUM_LEDS) ] += CRGB::White;
  965.   }
  966. }
  967.  
  968. ///////////////////////////////////////////////////////////////////////
  969.  
  970. // Forward declarations of an array of cpt-city gradient palettes, and
  971. // a count of how many there are.  The actual color palette definitions
  972. // are at the bottom of this file.
  973. extern const TProgmemRGBGradientPalettePtr gGradientPalettes[];
  974. extern const uint8_t gGradientPaletteCount;
  975.  
  976. uint8_t beatsaw8( accum88 beats_per_minute, uint8_t lowest = 0, uint8_t highest = 255,
  977.                   uint32_t timebase = 0, uint8_t phase_offset = 0)
  978. {
  979.   uint8_t beat = beat8( beats_per_minute, timebase);
  980.   uint8_t beatsaw = beat + phase_offset;
  981.   uint8_t rangewidth = highest - lowest;
  982.   uint8_t scaledbeat = scale8( beatsaw, rangewidth);
  983.   uint8_t result = lowest + scaledbeat;
  984.   return result;
  985. }
  986.  
  987. void colorWaves()
  988. {
  989.   colorwaves( leds, NUM_LEDS, gCurrentPalette);
  990. }
  991.  
  992. // ColorWavesWithPalettes by Mark Kriegsman: https://gist.github.com/kriegsman/8281905786e8b2632aeb
  993. // This function draws color waves with an ever-changing,
  994. // widely-varying set of parameters, using a color palette.
  995. void colorwaves( CRGB* ledarray, uint16_t numleds, CRGBPalette16& palette)
  996. {
  997.   static uint16_t sPseudotime = 0;
  998.   static uint16_t sLastMillis = 0;
  999.   static uint16_t sHue16 = 0;
  1000.  
  1001.   // uint8_t sat8 = beatsin88( 87, 220, 250);
  1002.   uint8_t brightdepth = beatsin88( 341, 96, 224);
  1003.   uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256));
  1004.   uint8_t msmultiplier = beatsin88(147, 23, 60);
  1005.  
  1006.   uint16_t hue16 = sHue16;//gHue * 256;
  1007.   uint16_t hueinc16 = beatsin88(113, 300, 1500);
  1008.  
  1009.   uint16_t ms = millis();
  1010.   uint16_t deltams = ms - sLastMillis ;
  1011.   sLastMillis  = ms;
  1012.   sPseudotime += deltams * msmultiplier;
  1013.   sHue16 += deltams * beatsin88( 400, 5, 9);
  1014.   uint16_t brightnesstheta16 = sPseudotime;
  1015.  
  1016.   for ( uint16_t i = 0 ; i < numleds; i++) {
  1017.     hue16 += hueinc16;
  1018.     uint8_t hue8 = hue16 / 256;
  1019.     uint16_t h16_128 = hue16 >> 7;
  1020.     if ( h16_128 & 0x100) {
  1021.       hue8 = 255 - (h16_128 >> 1);
  1022.     } else {
  1023.       hue8 = h16_128 >> 1;
  1024.     }
  1025.  
  1026.     brightnesstheta16  += brightnessthetainc16;
  1027.     uint16_t b16 = sin16( brightnesstheta16  ) + 32768;
  1028.  
  1029.     uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
  1030.     uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
  1031.     bri8 += (255 - brightdepth);
  1032.  
  1033.     uint8_t index = hue8;
  1034.     //index = triwave8( index);
  1035.     index = scale8( index, 240);
  1036.  
  1037.     CRGB newcolor = ColorFromPalette( palette, index, bri8);
  1038.  
  1039.     uint16_t pixelnumber = i;
  1040.     pixelnumber = (numleds - 1) - pixelnumber;
  1041.  
  1042.     nblend( ledarray[pixelnumber], newcolor, 128);
  1043.   }
  1044. }
  1045.  
  1046. // Alternate rendering function just scrolls the current palette
  1047. // across the defined LED strip.
  1048. void palettetest( CRGB* ledarray, uint16_t numleds, const CRGBPalette16& gCurrentPalette)
  1049. {
  1050.   static uint8_t startindex = 0;
  1051.   startindex--;
  1052.   fill_palette( ledarray, numleds, startindex, (256 / NUM_LEDS) + 1, gCurrentPalette, 255, LINEARBLEND);
  1053. }
Advertisement
Add Comment
Please, Sign In to add comment