diff --git a/boards/esp32s2.json b/boards/esp32s2.json new file mode 100644 index 000000000..7aff095fc --- /dev/null +++ b/boards/esp32s2.json @@ -0,0 +1,31 @@ +{ + "build": { + "arduino":{ + "ldscript": "esp32s2_out.ld" + }, + "core": "esp32", + "mcu": "esp32s2", + "extra_flags": "-Desp32S2_dev_module", + "f_cpu": "240000000L", + "f_flash": "80000000L", + "flash_mode": "qio", + "mcu": "esp32s2", + "variant": "esp32s2" + }, + "connectivity": [ + "wifi" + ], + "frameworks": [ + "arduino" + ], + "name": "ESP32S2 Dev Module", + "upload": { + "flash_size": "4MB", + "maximum_ram_size": 327680, + "maximum_size": 4194304, + "require_upload_port": true, + "speed": 460800 + }, + "url": "https://espressif.com", + "vendor": "espressif" + } \ No newline at end of file diff --git a/docs/source/Controller/C013.rst b/docs/source/Controller/C013.rst index 2aefa7b95..b0dc29d5f 100644 --- a/docs/source/Controller/C013.rst +++ b/docs/source/Controller/C013.rst @@ -228,8 +228,11 @@ Extended Sysinfo message (13 + 28 = 41 bytes): The node type is defined as: * 1 = "ESP Easy" +* 5 = "Rpi Easy" * 17 = "ESP Easy Mega" * 33 = "ESP Easy 32" +* 34 = "ESP Easy 32-S2" +* 35 = "ESP Easy 32-C3" * 65 = "Arduino Easy" * 81 = "Nano Easy" diff --git a/docs/source/ESPEasy/ESPchips.rst b/docs/source/ESPEasy/ESPchips.rst new file mode 100644 index 000000000..5914759d8 --- /dev/null +++ b/docs/source/ESPEasy/ESPchips.rst @@ -0,0 +1,229 @@ +Supported ESP Chips +******************* + +ESPEasy does support a number of variants of the processors manufactured by Espressif. + +* ESP8266 The original ESP processor, with external flash. +* ESP8285 Mainly found in "Chinese" products. Has flash built in the processor. (almost always 1MByte flash) +* ESP32 The first successor of the ESP82xx, supporting 2 CPU cores, Bluetooth and more RAM and more GPIO pins. (and other new features) +* ESP32-S2 Has more GPIO pins than the ESP32, but only 1 CPU core. Initial support in ESPEasy added since 2021-09-19. +* ESP32-S3 Not yet available to buy. (as of September 2021) +* ESP32-C3 Support in ESPeasy will be added soon. + + +.. list-table:: Espressif platforms + :header-rows: 1 + :widths: 7 7 7 7 + :stub-columns: 1 + + * - + - ESP8266 + - ESP32 + - ESP32-S2 + * - release Year + - 2014 + - 2016 + - 2019 + * - Microcontroller + - Xtensa single-core 32-bit L106 + - Xtensa single/dual-core 32-bit LX6 + - Xtensa single-core 32-bit LX7 + * - Clock Frequency + - 80 MHz + - 160/240 MHz + - 240 MHz + * - Co-processor + - No + - ULP + - ULP (RISC-V) + * - SRAM + - 160 KB + - 520 KB + - 320 KB + * - ROM + - No + - 448 KB + - 128 KB + * - RTC Memory + - No + - 16 KB + - 16 KB + * - External SPIRAM + - No + - Up to 16MB + - Up to 128MB + * - External Flash + - Up to 16MB + - Up to 16MB + - Up to 1GB + * - Wi-Fi (802.11 b/g/n) + - HT20 + - HT20 + - HT20 + * - ESP-MESH + - Yes + - Yes + - Yes + * - Bluetooth + - No + - BT 4.2 BR/EDR & BLE + - No + * - Ethernet + - No + - 10/100 Mbps + - No + * - CAN + - No + - 2.0 + - No + * - Time of Flight + - No + - No + - Yes + * - GPIO (total) + - 16 + - 34 + - 43 + * - Touch Sensors + - No + - 10 + - 14 + * - SPI + - 2 + - 4 + - 4 (OSPI) + * - I2C + - 1 (soft) + - 2 + - 2 + * - I2S + - 2 + - 2 + - 1 + * - UART + - 2 (1 ½ actually) + - 3 + - 2 + * - ADC + - 1 (10-bit) + - 18 (12-bit) + - 20 (12-bit) + * - DAC + - No + - 2 (8-bit) + - 2 (8-bit) + * - PWM (soft) + - 8 + - 16 + - 8 + * - SDMMC + - No + - Yes + - No + * - RMT (remote control) + - No + - Yes + - Yes + * - USB OTG + - No + - No + - Yes + * - LCD Interface + - No + - No + - Yes + * - Camera Interface + - No + - No + - Yes + * - Temperature sensor + - No + - Yes + - Yes + * - Hall sensor + - No + - Yes + - No + * - Security + - No + - Secure boot Flash encryption 1024-bit OTP + - Secure boot Flash encryption 4096-bit OTP + * - Crypto + - No + - AES, SHA-2, RSA, ECC, RNG + - AES-128/192/256, SHA-2, RSA, RNG, HMAC, Digital Signature + * - Low Power Consumption + - 20uA + - 10uA deep sleep + - Automatic RF power management 5uA in idle mode 24uA at 1% duty cycle + + +`Table content source `_ + + +ESP8266/ESP8285 +=============== + +The ESP8266 was the "original" ESP platform and was found in the original Sonoff Basic modules. +The ESP8266 does need an external SPI flash module to store its progam data and configuration. + +Later a (probably) less expensive ESP8285 appeared, which does have the SPI flash integrated in the chip. +This means you cannot upgrade it by soldering a larger flash chip on it. +It does however free up 2 GPIO pins, which were previously unavailable as they were used to access the SPI flash. +For some products like the Sonoff 4ch modules this chip was a must-have. + +The small 1MB flash does impose some issues when trying to perform an "OTA" update of the firmware as there is not enough space to store the active firmware and the new version at the same time. +For 1MB modules (some ESP8266 modules were also sold with 1MB flash, like the ESP-01 modules) you need to take some extra steps to perform an OTA update. +Otherwise the only way to upgrade to a newer build is by flashing using the serial port. + + + + +ESP32 +===== + +The most important new features of the ESP32, compared to ESP82xx are: + +- Dual core CPU @ 240 MHz +- Upto 320 kByte of RAM +- 3 Hardware serial ports +- Bluetooth (not supported yet in ESPEasy) +- Extra GPIO pins +- Upto 18 GPIO pins can operate as ADC. +- Upto 10 touch pins +- Support for Ethernet + + + + + +ESP32-S2 +======== + +.. note:: Support for the ESP32-S2 is very preliminary, as in it is hardly tested (as of September 2021) + + +The ESP32-S2 is a bit strange when looking at its features and taking into account it was introduced about 3 years after the ESP32. + +The ESP32-S2 is missing quite a lot of useful features its predecessor had: + +- No Bluetooth +- Single core +- No support for Ethernet +- No support for CAN +- 2 Harware Serial ports. +- Less RAM + +The only advantages of the ESP32-S2 compared to its predecessor are: + +- More GPIO pins +- 2 extra ADC capable pins +- 4 extra touch capable pins +- USB OTG (not yet supported in ESPEasy) +- LCD interface (not yet supported in ESPEasy) +- Camera interface (not yet supported in ESPEasy) +- Extra hardware accelerated encryption functions (not yet supported in ESPEasy) +- Supposedly lower power consumption (not yet verified) +- Time of Flight (TOF) support that would (theoretically) allow indoor positioning + + diff --git a/docs/source/Reference/ExternalHostedStaticFiles.rst b/docs/source/Reference/ExternalHostedStaticFiles.rst index cf6805625..601f383b6 100644 --- a/docs/source/Reference/ExternalHostedStaticFiles.rst +++ b/docs/source/Reference/ExternalHostedStaticFiles.rst @@ -26,7 +26,7 @@ The files are located `here . - -------------------------------------------------------------------------*/ +/*! + * @file Adafruit_NeoPixel.cpp + * + * @mainpage Arduino Library for driving Adafruit NeoPixel addressable LEDs, + * FLORA RGB Smart Pixels and compatible devicess -- WS2811, WS2812, WS2812B, + * SK6812, etc. + * + * @section intro_sec Introduction + * + * This is the documentation for Adafruit's NeoPixel library for the + * Arduino platform, allowing a broad range of microcontroller boards + * (most AVR boards, many ARM devices, ESP8266 and ESP32, among others) + * to control Adafruit NeoPixels, FLORA RGB Smart Pixels and compatible + * devices -- WS2811, WS2812, WS2812B, SK6812, etc. + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing products + * from Adafruit! + * + * @section author Author + * + * Written by Phil "Paint Your Dragon" Burgess for Adafruit Industries, + * with contributions by PJRC, Michael Miller and other members of the + * open source community. + * + * @section license License + * + * This file is part of the Adafruit_NeoPixel library. + * + * Adafruit_NeoPixel is free software: you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * Adafruit_NeoPixel is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with NeoPixel. If not, see + * . + * + */ #include "Adafruit_NeoPixel.h" -// Constructor when length, pin and type are known at compile-time: -Adafruit_NeoPixel::Adafruit_NeoPixel(uint16_t n, uint8_t p, neoPixelType t) : - begun(false), brightness(0), pixels(NULL), endTime(0) -{ +#if defined(TARGET_LPC1768) + #include +#endif + +#if defined(NRF52) || defined(NRF52_SERIES) +#include "nrf.h" + +// Interrupt is only disabled if there is no PWM device available +// Note: Adafruit Bluefruit nrf52 does not use this option +//#define NRF52_DISABLE_INT +#endif + +#if defined(ARDUINO_ARCH_NRF52840) +#if defined __has_include +# if __has_include () +# include +# endif +#endif +#endif + +/*! + @brief NeoPixel constructor when length, pin and pixel type are known + at compile-time. + @param n Number of NeoPixels in strand. + @param p Arduino pin number which will drive the NeoPixel data in. + @param t Pixel type -- add together NEO_* constants defined in + Adafruit_NeoPixel.h, for example NEO_GRB+NEO_KHZ800 for + NeoPixels expecting an 800 KHz (vs 400 KHz) data stream + with color bytes expressed in green, red, blue order per + pixel. + @return Adafruit_NeoPixel object. Call the begin() function before use. +*/ +Adafruit_NeoPixel::Adafruit_NeoPixel(uint16_t n, int16_t p, neoPixelType t) : + begun(false), brightness(0), pixels(NULL), endTime(0) { updateType(t); updateLength(n); setPin(p); } -// via Michael Vogt/neophob: empty constructor is used when strand length -// isn't known at compile-time; situations where program config might be -// read from internal flash memory or an SD card, or arrive via serial -// command. If using this constructor, MUST follow up with updateType(), -// updateLength(), etc. to establish the strand type, length and pin number! +/*! + @brief "Empty" NeoPixel constructor when length, pin and/or pixel type + are not known at compile-time, and must be initialized later with + updateType(), updateLength() and setPin(). + @return Adafruit_NeoPixel object. Call the begin() function before use. + @note This function is deprecated, here only for old projects that + may still be calling it. New projects should instead use the + 'new' keyword with the first constructor syntax (length, pin, + type). +*/ Adafruit_NeoPixel::Adafruit_NeoPixel() : -#ifdef NEO_KHZ400 +#if defined(NEO_KHZ400) is800KHz(true), #endif begun(false), numLEDs(0), numBytes(0), pin(-1), brightness(0), pixels(NULL), - rOffset(1), gOffset(0), bOffset(2), wOffset(1), endTime(0) -{ + rOffset(1), gOffset(0), bOffset(2), wOffset(1), endTime(0) { } +/*! + @brief Deallocate Adafruit_NeoPixel object, set data pin back to INPUT. +*/ Adafruit_NeoPixel::~Adafruit_NeoPixel() { - if(pixels) free(pixels); + free(pixels); if(pin >= 0) pinMode(pin, INPUT); } +/*! + @brief Configure NeoPixel pin for output. +*/ void Adafruit_NeoPixel::begin(void) { if(pin >= 0) { pinMode(pin, OUTPUT); @@ -69,8 +121,18 @@ void Adafruit_NeoPixel::begin(void) { begun = true; } +/*! + @brief Change the length of a previously-declared Adafruit_NeoPixel + strip object. Old data is deallocated and new data is cleared. + Pin number and pixel format are unchanged. + @param n New length of strip, in pixels. + @note This function is deprecated, here only for old projects that + may still be calling it. New projects should instead use the + 'new' keyword with the first constructor syntax (length, pin, + type). +*/ void Adafruit_NeoPixel::updateLength(uint16_t n) { - if(pixels) free(pixels); // Free existing data (if any) + free(pixels); // Free existing data (if any) // Allocate new data -- note: ALL PIXELS ARE CLEARED numBytes = n * ((wOffset == rOffset) ? 3 : 4); @@ -82,63 +144,106 @@ void Adafruit_NeoPixel::updateLength(uint16_t n) { } } +/*! + @brief Change the pixel format of a previously-declared + Adafruit_NeoPixel strip object. If format changes from one of + the RGB variants to an RGBW variant (or RGBW to RGB), the old + data will be deallocated and new data is cleared. Otherwise, + the old data will remain in RAM and is not reordered to the + new format, so it's advisable to follow up with clear(). + @param t Pixel type -- add together NEO_* constants defined in + Adafruit_NeoPixel.h, for example NEO_GRB+NEO_KHZ800 for + NeoPixels expecting an 800 KHz (vs 400 KHz) data stream + with color bytes expressed in green, red, blue order per + pixel. + @note This function is deprecated, here only for old projects that + may still be calling it. New projects should instead use the + 'new' keyword with the first constructor syntax + (length, pin, type). +*/ void Adafruit_NeoPixel::updateType(neoPixelType t) { - boolean oldThreeBytesPerPixel = (wOffset == rOffset); // false if RGBW + bool oldThreeBytesPerPixel = (wOffset == rOffset); // false if RGBW wOffset = (t >> 6) & 0b11; // See notes in header file rOffset = (t >> 4) & 0b11; // regarding R/G/B/W offsets gOffset = (t >> 2) & 0b11; bOffset = t & 0b11; -#ifdef NEO_KHZ400 +#if defined(NEO_KHZ400) is800KHz = (t < 256); // 400 KHz flag is 1<<8 #endif // If bytes-per-pixel has changed (and pixel data was previously - // allocated), re-allocate to new size. Will clear any data. + // allocated), re-allocate to new size. Will clear any data. if(pixels) { - boolean newThreeBytesPerPixel = (wOffset == rOffset); + bool newThreeBytesPerPixel = (wOffset == rOffset); if(newThreeBytesPerPixel != oldThreeBytesPerPixel) updateLength(numLEDs); } } -#ifdef ESP8266 - #ifndef CORE_POST_3_0_0 - #define IRAM_ATTR ICACHE_RAM_ATTR - #endif +#if defined(ARDUINO_ARCH_RP2040) +extern "C" void rp2040Show( + uint16_t pin, uint8_t *pixels, uint32_t numBytes, uint8_t type); +#endif -// ESP8266 show() is external to enforce IRAM_ATTR execution -extern "C" void IRAM_ATTR espShow( - uint8_t pin, uint8_t *pixels, uint32_t numBytes, uint8_t type); +#if defined(ESP8266) +// ESP8266 show() is external to enforce ICACHE_RAM_ATTR execution +extern "C" IRAM_ATTR void espShow( + uint16_t pin, uint8_t *pixels, uint32_t numBytes, uint8_t type); +#elif defined(ESP32) +extern "C" void espShow( + uint16_t pin, uint8_t *pixels, uint32_t numBytes, uint8_t type); #endif // ESP8266 +#if defined(K210) +#define KENDRYTE_K210 1 +#endif + +#if defined(KENDRYTE_K210) +extern "C" void k210Show( + uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz); +#endif //KENDRYTE_K210 +/*! + @brief Transmit pixel data in RAM to NeoPixels. + @note On most architectures, interrupts are temporarily disabled in + order to achieve the correct NeoPixel signal timing. This means + that the Arduino millis() and micros() functions, which require + interrupts, will lose small intervals of time whenever this + function is called (about 30 microseconds per RGB pixel, 40 for + RGBW pixels). There's no easy fix for this, but a few + specialized alternative or companion libraries exist that use + very device-specific peripherals to work around it. +*/ void Adafruit_NeoPixel::show(void) { if(!pixels) return; - // Data latch = 50+ microsecond pause in the output stream. Rather than + // Data latch = 300+ microsecond pause in the output stream. Rather than // put a delay at the end of the function, the ending time is noted and // the function will simply hold off (if needed) on issuing the - // subsequent round of data until the latch time has elapsed. This + // subsequent round of data until the latch time has elapsed. This // allows the mainline code to start generating the next frame of data // rather than stalling for the latch. while(!canShow()); - // endTime is a private member (rather than global var) so that mutliple + // endTime is a private member (rather than global var) so that multiple // instances on different pins can be quickly issued in succession (each // instance doesn't delay the next). // In order to make this code runtime-configurable to work with any pin, // SBI/CBI instructions are eschewed in favor of full PORT writes via the - // OUT or ST instructions. It relies on two facts: that peripheral + // OUT or ST instructions. It relies on two facts: that peripheral // functions (such as PWM) take precedence on output pins, so our PORT- // wide writes won't interfere, and that interrupts are globally disabled // while data is being issued to the LEDs, so no other code will be - // accessing the PORT. The code takes an initial 'snapshot' of the PORT + // accessing the PORT. The code takes an initial 'snapshot' of the PORT // state, computes 'pin high' and 'pin low' values, and writes these back // to the PORT register as needed. + // NRF52 may use PWM + DMA (if available), may not need to disable interrupt +#if !( defined(NRF52) || defined(NRF52_SERIES) ) noInterrupts(); // Need 100% focus on instruction timing +#endif -#ifdef __AVR__ +#if defined(__AVR__) // AVR MCUs -- ATmega & ATtiny (no XMEGA) --------------------------------- volatile uint16_t @@ -150,13 +255,13 @@ void Adafruit_NeoPixel::show(void) { lo; // PORT w/output bit set low // Hand-tuned assembly code issues data to the LED drivers at a specific - // rate. There's separate code for different CPU speeds (8, 12, 16 MHz) - // for both the WS2811 (400 KHz) and WS2812 (800 KHz) drivers. The + // rate. There's separate code for different CPU speeds (8, 12, 16 MHz) + // for both the WS2811 (400 KHz) and WS2812 (800 KHz) drivers. The // datastream timing for the LED drivers allows a little wiggle room each // way (listed in the datasheets), so the conditions for compiling each // case are set up for a range of frequencies rather than just the exact // 8, 12 or 16 MHz values, permitting use with some close-but-not-spot-on - // devices (e.g. 16.5 MHz DigiSpark). The ranges were arrived at based + // devices (e.g. 16.5 MHz DigiSpark). The ranges were arrived at based // on the datasheet figures and have not been extensively tested outside // the canonical 8/12/16 MHz speeds; there's no guarantee these will work // close to the extremes (or possibly they could be pushed further). @@ -166,7 +271,7 @@ void Adafruit_NeoPixel::show(void) { // 8 MHz(ish) AVR --------------------------------------------------------- #if (F_CPU >= 7400000UL) && (F_CPU <= 9500000UL) -#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled if(is800KHz) { #endif @@ -192,7 +297,7 @@ void Adafruit_NeoPixel::show(void) { // Dirty trick: RJMPs proceeding to the next instruction are used // to delay two clock cycles in one instruction word (rather than - // using two NOPs). This was necessary in order to squeeze the + // using two NOPs). This was necessary in order to squeeze the // loop down to exactly 64 words -- the maximum possible for a // relative branch. @@ -553,11 +658,11 @@ void Adafruit_NeoPixel::show(void) { #endif // defined(PORTD/B/C) #endif // defined(PORTF) -#ifdef NEO_KHZ400 +#if defined(NEO_KHZ400) } else { // end 800 KHz, do 400 KHz // Timing is more relaxed; unrolling the inner loop for each bit is - // not necessary. Still using the peculiar RJMPs as 2X NOPs, not out + // not necessary. Still using the peculiar RJMPs as 2X NOPs, not out // of need but just to trim the code size down a little. // This 400-KHz-datastream-on-8-MHz-CPU code is not quite identical // to the 800-on-16 code later -- the hi/lo timing between WS2811 and @@ -609,7 +714,7 @@ void Adafruit_NeoPixel::show(void) { // 12 MHz(ish) AVR -------------------------------------------------------- #elif (F_CPU >= 11100000UL) && (F_CPU <= 14300000UL) -#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled if(is800KHz) { #endif @@ -874,7 +979,7 @@ void Adafruit_NeoPixel::show(void) { #endif // defined(PORTD/B/C) #endif // defined(PORTF) -#ifdef NEO_KHZ400 +#if defined(NEO_KHZ400) } else { // 400 KHz // 30 instruction clocks per bit: HHHHHHxxxxxxxxxLLLLLLLLLLLLLLL @@ -927,7 +1032,7 @@ void Adafruit_NeoPixel::show(void) { // 16 MHz(ish) AVR -------------------------------------------------------- #elif (F_CPU >= 15400000UL) && (F_CPU <= 19000000L) -#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled if(is800KHz) { #endif @@ -976,7 +1081,7 @@ void Adafruit_NeoPixel::show(void) { [hi] "r" (hi), [lo] "r" (lo)); -#ifdef NEO_KHZ400 +#if defined(NEO_KHZ400) } else { // 400 KHz // The 400 KHz clock on 16 MHz MCU is the most 'relaxed' version. @@ -1045,9 +1150,13 @@ void Adafruit_NeoPixel::show(void) { #elif defined(__arm__) -// ARM MCUs -- Teensy 3.0, 3.1, LC, Arduino Due --------------------------- +// ARM MCUs -- Teensy 3.0, 3.1, LC, Arduino Due, RP2040 ------------------- -#if defined(__MK20DX128__) || defined(__MK20DX256__) // Teensy 3.0 & 3.1 +#if defined(ARDUINO_ARCH_RP2040) + // Use PIO + rp2040Show(pin, pixels, numBytes, is800KHz); + +#elif defined(TEENSYDUINO) && defined(KINETISK) // Teensy 3.0, 3.1, 3.2, 3.5, 3.6 #define CYCLES_800_T0H (F_CPU / 4000000) #define CYCLES_800_T1H (F_CPU / 1250000) #define CYCLES_800 (F_CPU / 800000) @@ -1064,7 +1173,7 @@ void Adafruit_NeoPixel::show(void) { ARM_DEMCR |= ARM_DEMCR_TRCENA; ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA; -#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled if(is800KHz) { #endif cyc = ARM_DWT_CYCCNT + CYCLES_800; @@ -1083,7 +1192,7 @@ void Adafruit_NeoPixel::show(void) { } } while(ARM_DWT_CYCCNT - cyc < CYCLES_800); -#ifdef NEO_KHZ400 +#if defined(NEO_KHZ400) } else { // 400 kHz bitstream cyc = ARM_DWT_CYCCNT + CYCLES_400; while(p < end) { @@ -1104,96 +1213,452 @@ void Adafruit_NeoPixel::show(void) { } #endif // NEO_KHZ400 -#elif defined(__MKL26Z64__) // Teensy-LC +#elif defined(TEENSYDUINO) && (defined(__IMXRT1052__) || defined(__IMXRT1062__)) +#define CYCLES_800_T0H (F_CPU_ACTUAL / 4000000) +#define CYCLES_800_T1H (F_CPU_ACTUAL / 1250000) +#define CYCLES_800 (F_CPU_ACTUAL / 800000) +#define CYCLES_400_T0H (F_CPU_ACTUAL / 2000000) +#define CYCLES_400_T1H (F_CPU_ACTUAL / 833333) +#define CYCLES_400 (F_CPU_ACTUAL / 400000) + + uint8_t *p = pixels, + *end = p + numBytes, pix, mask; + volatile uint32_t *set = portSetRegister(pin), + *clr = portClearRegister(pin); + uint32_t cyc, + msk = digitalPinToBitMask(pin); + + ARM_DEMCR |= ARM_DEMCR_TRCENA; + ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA; + +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled + if(is800KHz) { +#endif + cyc = ARM_DWT_CYCCNT + CYCLES_800; + while(p < end) { + pix = *p++; + for(mask = 0x80; mask; mask >>= 1) { + while(ARM_DWT_CYCCNT - cyc < CYCLES_800); + cyc = ARM_DWT_CYCCNT; + *set = msk; + if(pix & mask) { + while(ARM_DWT_CYCCNT - cyc < CYCLES_800_T1H); + } else { + while(ARM_DWT_CYCCNT - cyc < CYCLES_800_T0H); + } + *clr = msk; + } + } + while(ARM_DWT_CYCCNT - cyc < CYCLES_800); +#if defined(NEO_KHZ400) + } else { // 400 kHz bitstream + cyc = ARM_DWT_CYCCNT + CYCLES_400; + while(p < end) { + pix = *p++; + for(mask = 0x80; mask; mask >>= 1) { + while(ARM_DWT_CYCCNT - cyc < CYCLES_400); + cyc = ARM_DWT_CYCCNT; + *set = msk; + if(pix & mask) { + while(ARM_DWT_CYCCNT - cyc < CYCLES_400_T1H); + } else { + while(ARM_DWT_CYCCNT - cyc < CYCLES_400_T0H); + } + *clr = msk; + } + } + while(ARM_DWT_CYCCNT - cyc < CYCLES_400); + } +#endif // NEO_KHZ400 + +#elif defined(TEENSYDUINO) && defined(__MKL26Z64__) // Teensy-LC #if F_CPU == 48000000 uint8_t *p = pixels, - pix, count, dly, - bitmask = digitalPinToBitMask(pin); + pix, count, dly, + bitmask = digitalPinToBitMask(pin); volatile uint8_t *reg = portSetRegister(pin); - uint32_t num = numBytes; + uint32_t num = numBytes; asm volatile( - "L%=_begin:" "\n\t" - "ldrb %[pix], [%[p], #0]" "\n\t" - "lsl %[pix], #24" "\n\t" - "movs %[count], #7" "\n\t" - "L%=_loop:" "\n\t" - "lsl %[pix], #1" "\n\t" - "bcs L%=_loop_one" "\n\t" - "L%=_loop_zero:" - "strb %[bitmask], [%[reg], #0]" "\n\t" - "movs %[dly], #4" "\n\t" - "L%=_loop_delay_T0H:" "\n\t" - "sub %[dly], #1" "\n\t" - "bne L%=_loop_delay_T0H" "\n\t" - "strb %[bitmask], [%[reg], #4]" "\n\t" - "movs %[dly], #13" "\n\t" - "L%=_loop_delay_T0L:" "\n\t" - "sub %[dly], #1" "\n\t" - "bne L%=_loop_delay_T0L" "\n\t" - "b L%=_next" "\n\t" - "L%=_loop_one:" - "strb %[bitmask], [%[reg], #0]" "\n\t" - "movs %[dly], #13" "\n\t" - "L%=_loop_delay_T1H:" "\n\t" - "sub %[dly], #1" "\n\t" - "bne L%=_loop_delay_T1H" "\n\t" - "strb %[bitmask], [%[reg], #4]" "\n\t" - "movs %[dly], #4" "\n\t" - "L%=_loop_delay_T1L:" "\n\t" - "sub %[dly], #1" "\n\t" - "bne L%=_loop_delay_T1L" "\n\t" - "nop" "\n\t" - "L%=_next:" "\n\t" - "sub %[count], #1" "\n\t" - "bne L%=_loop" "\n\t" - "lsl %[pix], #1" "\n\t" - "bcs L%=_last_one" "\n\t" - "L%=_last_zero:" - "strb %[bitmask], [%[reg], #0]" "\n\t" - "movs %[dly], #4" "\n\t" - "L%=_last_delay_T0H:" "\n\t" - "sub %[dly], #1" "\n\t" - "bne L%=_last_delay_T0H" "\n\t" - "strb %[bitmask], [%[reg], #4]" "\n\t" - "movs %[dly], #10" "\n\t" - "L%=_last_delay_T0L:" "\n\t" - "sub %[dly], #1" "\n\t" - "bne L%=_last_delay_T0L" "\n\t" - "b L%=_repeat" "\n\t" - "L%=_last_one:" - "strb %[bitmask], [%[reg], #0]" "\n\t" - "movs %[dly], #13" "\n\t" - "L%=_last_delay_T1H:" "\n\t" - "sub %[dly], #1" "\n\t" - "bne L%=_last_delay_T1H" "\n\t" - "strb %[bitmask], [%[reg], #4]" "\n\t" - "movs %[dly], #1" "\n\t" - "L%=_last_delay_T1L:" "\n\t" - "sub %[dly], #1" "\n\t" - "bne L%=_last_delay_T1L" "\n\t" - "nop" "\n\t" - "L%=_repeat:" "\n\t" - "add %[p], #1" "\n\t" - "sub %[num], #1" "\n\t" - "bne L%=_begin" "\n\t" - "L%=_done:" "\n\t" - : [p] "+r" (p), - [pix] "=&r" (pix), - [count] "=&r" (count), - [dly] "=&r" (dly), - [num] "+r" (num) - : [bitmask] "r" (bitmask), - [reg] "r" (reg) + "L%=_begin:" "\n\t" + "ldrb %[pix], [%[p], #0]" "\n\t" + "lsl %[pix], #24" "\n\t" + "movs %[count], #7" "\n\t" + "L%=_loop:" "\n\t" + "lsl %[pix], #1" "\n\t" + "bcs L%=_loop_one" "\n\t" + "L%=_loop_zero:" "\n\t" + "strb %[bitmask], [%[reg], #0]" "\n\t" + "movs %[dly], #4" "\n\t" + "L%=_loop_delay_T0H:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_loop_delay_T0H" "\n\t" + "strb %[bitmask], [%[reg], #4]" "\n\t" + "movs %[dly], #13" "\n\t" + "L%=_loop_delay_T0L:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_loop_delay_T0L" "\n\t" + "b L%=_next" "\n\t" + "L%=_loop_one:" "\n\t" + "strb %[bitmask], [%[reg], #0]" "\n\t" + "movs %[dly], #13" "\n\t" + "L%=_loop_delay_T1H:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_loop_delay_T1H" "\n\t" + "strb %[bitmask], [%[reg], #4]" "\n\t" + "movs %[dly], #4" "\n\t" + "L%=_loop_delay_T1L:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_loop_delay_T1L" "\n\t" + "nop" "\n\t" + "L%=_next:" "\n\t" + "sub %[count], #1" "\n\t" + "bne L%=_loop" "\n\t" + "lsl %[pix], #1" "\n\t" + "bcs L%=_last_one" "\n\t" + "L%=_last_zero:" "\n\t" + "strb %[bitmask], [%[reg], #0]" "\n\t" + "movs %[dly], #4" "\n\t" + "L%=_last_delay_T0H:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_last_delay_T0H" "\n\t" + "strb %[bitmask], [%[reg], #4]" "\n\t" + "movs %[dly], #10" "\n\t" + "L%=_last_delay_T0L:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_last_delay_T0L" "\n\t" + "b L%=_repeat" "\n\t" + "L%=_last_one:" "\n\t" + "strb %[bitmask], [%[reg], #0]" "\n\t" + "movs %[dly], #13" "\n\t" + "L%=_last_delay_T1H:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_last_delay_T1H" "\n\t" + "strb %[bitmask], [%[reg], #4]" "\n\t" + "movs %[dly], #1" "\n\t" + "L%=_last_delay_T1L:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_last_delay_T1L" "\n\t" + "nop" "\n\t" + "L%=_repeat:" "\n\t" + "add %[p], #1" "\n\t" + "sub %[num], #1" "\n\t" + "bne L%=_begin" "\n\t" + "L%=_done:" "\n\t" + : [p] "+r" (p), + [pix] "=&r" (pix), + [count] "=&r" (count), + [dly] "=&r" (dly), + [num] "+r" (num) + : [bitmask] "r" (bitmask), + [reg] "r" (reg) ); #else #error "Sorry, only 48 MHz is supported, please set Tools > CPU Speed to 48 MHz" #endif // F_CPU == 48000000 -#elif defined(__SAMD21G18A__) // Arduino Zero +// Begin of support for nRF52 based boards ------------------------- +#elif defined(NRF52) || defined(NRF52_SERIES) +// [[[Begin of the Neopixel NRF52 EasyDMA implementation +// by the Hackerspace San Salvador]]] +// This technique uses the PWM peripheral on the NRF52. The PWM uses the +// EasyDMA feature included on the chip. This technique loads the duty +// cycle configuration for each cycle when the PWM is enabled. For this +// to work we need to store a 16 bit configuration for each bit of the +// RGB(W) values in the pixel buffer. +// Comparator values for the PWM were hand picked and are guaranteed to +// be 100% organic to preserve freshness and high accuracy. Current +// parameters are: +// * PWM Clock: 16Mhz +// * Minimum step time: 62.5ns +// * Time for zero in high (T0H): 0.31ms +// * Time for one in high (T1H): 0.75ms +// * Cycle time: 1.25us +// * Frequency: 800Khz +// For 400Khz we just double the calculated times. +// ---------- BEGIN Constants for the EasyDMA implementation ----------- +// The PWM starts the duty cycle in LOW. To start with HIGH we +// need to set the 15th bit on each register. + +// WS2812 (rev A) timing is 0.35 and 0.7us +//#define MAGIC_T0H 5UL | (0x8000) // 0.3125us +//#define MAGIC_T1H 12UL | (0x8000) // 0.75us + +// WS2812B (rev B) timing is 0.4 and 0.8 us +#define MAGIC_T0H 6UL | (0x8000) // 0.375us +#define MAGIC_T1H 13UL | (0x8000) // 0.8125us + +// WS2811 (400 khz) timing is 0.5 and 1.2 +#define MAGIC_T0H_400KHz 8UL | (0x8000) // 0.5us +#define MAGIC_T1H_400KHz 19UL | (0x8000) // 1.1875us + +// For 400Khz, we double value of CTOPVAL +#define CTOPVAL 20UL // 1.25us +#define CTOPVAL_400KHz 40UL // 2.5us + +// ---------- END Constants for the EasyDMA implementation ------------- +// +// If there is no device available an alternative cycle-counter +// implementation is tried. +// The nRF52 runs with a fixed clock of 64Mhz. The alternative +// implementation is the same as the one used for the Teensy 3.0/1/2 but +// with the Nordic SDK HAL & registers syntax. +// The number of cycles was hand picked and is guaranteed to be 100% +// organic to preserve freshness and high accuracy. +// ---------- BEGIN Constants for cycle counter implementation --------- +#define CYCLES_800_T0H 18 // ~0.36 uS +#define CYCLES_800_T1H 41 // ~0.76 uS +#define CYCLES_800 71 // ~1.25 uS + +#define CYCLES_400_T0H 26 // ~0.50 uS +#define CYCLES_400_T1H 70 // ~1.26 uS +#define CYCLES_400 156 // ~2.50 uS +// ---------- END of Constants for cycle counter implementation -------- + + // To support both the SoftDevice + Neopixels we use the EasyDMA + // feature from the NRF25. However this technique implies to + // generate a pattern and store it on the memory. The actual + // memory used in bytes corresponds to the following formula: + // totalMem = numBytes*8*2+(2*2) + // The two additional bytes at the end are needed to reset the + // sequence. + // + // If there is not enough memory, we will fall back to cycle counter + // using DWT + uint32_t pattern_size = numBytes*8*sizeof(uint16_t)+2*sizeof(uint16_t); + uint16_t* pixels_pattern = NULL; + + NRF_PWM_Type* pwm = NULL; + + // Try to find a free PWM device, which is not enabled + // and has no connected pins + NRF_PWM_Type* PWM[] = { + NRF_PWM0, NRF_PWM1, NRF_PWM2 +#if defined(NRF_PWM3) + ,NRF_PWM3 +#endif + }; + + for(unsigned int device = 0; device < (sizeof(PWM)/sizeof(PWM[0])); device++) { + if( (PWM[device]->ENABLE == 0) && + (PWM[device]->PSEL.OUT[0] & PWM_PSEL_OUT_CONNECT_Msk) && + (PWM[device]->PSEL.OUT[1] & PWM_PSEL_OUT_CONNECT_Msk) && + (PWM[device]->PSEL.OUT[2] & PWM_PSEL_OUT_CONNECT_Msk) && + (PWM[device]->PSEL.OUT[3] & PWM_PSEL_OUT_CONNECT_Msk) + ) { + pwm = PWM[device]; + break; + } + } + + // only malloc if there is PWM device available + if ( pwm != NULL ) { + #if defined(ARDUINO_NRF52_ADAFRUIT) // use thread-safe malloc + pixels_pattern = (uint16_t *) rtos_malloc(pattern_size); + #else + pixels_pattern = (uint16_t *) malloc(pattern_size); + #endif + } + + // Use the identified device to choose the implementation + // If a PWM device is available use DMA + if( (pixels_pattern != NULL) && (pwm != NULL) ) { + uint16_t pos = 0; // bit position + + for(uint16_t n=0; n0; mask >>= 1) { + #if defined(NEO_KHZ400) + if( !is800KHz ) { + pixels_pattern[pos] = (pix & mask) ? MAGIC_T1H_400KHz : MAGIC_T0H_400KHz; + }else + #endif + { + pixels_pattern[pos] = (pix & mask) ? MAGIC_T1H : MAGIC_T0H; + } + + pos++; + } + } + + // Zero padding to indicate the end of que sequence + pixels_pattern[pos++] = 0 | (0x8000); // Seq end + pixels_pattern[pos++] = 0 | (0x8000); // Seq end + + // Set the wave mode to count UP + pwm->MODE = (PWM_MODE_UPDOWN_Up << PWM_MODE_UPDOWN_Pos); + + // Set the PWM to use the 16MHz clock + pwm->PRESCALER = (PWM_PRESCALER_PRESCALER_DIV_1 << PWM_PRESCALER_PRESCALER_Pos); + + // Setting of the maximum count + // but keeping it on 16Mhz allows for more granularity just + // in case someone wants to do more fine-tuning of the timing. +#if defined(NEO_KHZ400) + if( !is800KHz ) { + pwm->COUNTERTOP = (CTOPVAL_400KHz << PWM_COUNTERTOP_COUNTERTOP_Pos); + }else +#endif + { + pwm->COUNTERTOP = (CTOPVAL << PWM_COUNTERTOP_COUNTERTOP_Pos); + } + + // Disable loops, we want the sequence to repeat only once + pwm->LOOP = (PWM_LOOP_CNT_Disabled << PWM_LOOP_CNT_Pos); + + // On the "Common" setting the PWM uses the same pattern for the + // for supported sequences. The pattern is stored on half-word + // of 16bits + pwm->DECODER = (PWM_DECODER_LOAD_Common << PWM_DECODER_LOAD_Pos) | + (PWM_DECODER_MODE_RefreshCount << PWM_DECODER_MODE_Pos); + + // Pointer to the memory storing the patter + pwm->SEQ[0].PTR = (uint32_t)(pixels_pattern) << PWM_SEQ_PTR_PTR_Pos; + + // Calculation of the number of steps loaded from memory. + pwm->SEQ[0].CNT = (pattern_size/sizeof(uint16_t)) << PWM_SEQ_CNT_CNT_Pos; + + // The following settings are ignored with the current config. + pwm->SEQ[0].REFRESH = 0; + pwm->SEQ[0].ENDDELAY = 0; + + // The Neopixel implementation is a blocking algorithm. DMA + // allows for non-blocking operation. To "simulate" a blocking + // operation we enable the interruption for the end of sequence + // and block the execution thread until the event flag is set by + // the peripheral. +// pwm->INTEN |= (PWM_INTEN_SEQEND0_Enabled<PSEL.OUT[0] = g_APinDescription[pin].name; + #else + pwm->PSEL.OUT[0] = g_ADigitalPinMap[pin]; + #endif + + // Enable the PWM + pwm->ENABLE = 1; + + // After all of this and many hours of reading the documentation + // we are ready to start the sequence... + pwm->EVENTS_SEQEND[0] = 0; + pwm->TASKS_SEQSTART[0] = 1; + + // But we have to wait for the flag to be set. + while(!pwm->EVENTS_SEQEND[0]) + { + #if defined(ARDUINO_NRF52_ADAFRUIT) || defined(ARDUINO_ARCH_NRF52840) + yield(); + #endif + } + + // Before leave we clear the flag for the event. + pwm->EVENTS_SEQEND[0] = 0; + + // We need to disable the device and disconnect + // all the outputs before leave or the device will not + // be selected on the next call. + // TODO: Check if disabling the device causes performance issues. + pwm->ENABLE = 0; + + pwm->PSEL.OUT[0] = 0xFFFFFFFFUL; + + #if defined(ARDUINO_NRF52_ADAFRUIT) // use thread-safe free + rtos_free(pixels_pattern); + #else + free(pixels_pattern); + #endif + }// End of DMA implementation + // --------------------------------------------------------------------- + else{ +#ifndef ARDUINO_ARCH_NRF52840 + // Fall back to DWT + #if defined(ARDUINO_NRF52_ADAFRUIT) + // Bluefruit Feather 52 uses freeRTOS + // Critical Section is used since it does not block SoftDevice execution + taskENTER_CRITICAL(); + #elif defined(NRF52_DISABLE_INT) + // If you are using the Bluetooth SoftDevice we advise you to not disable + // the interrupts. Disabling the interrupts even for short periods of time + // causes the SoftDevice to stop working. + // Disable the interrupts only in cases where you need high performance for + // the LEDs and if you are not using the EasyDMA feature. + __disable_irq(); + #endif + + NRF_GPIO_Type* nrf_port = (NRF_GPIO_Type*) digitalPinToPort(pin); + uint32_t pinMask = digitalPinToBitMask(pin); + + uint32_t CYCLES_X00 = CYCLES_800; + uint32_t CYCLES_X00_T1H = CYCLES_800_T1H; + uint32_t CYCLES_X00_T0H = CYCLES_800_T0H; + +#if defined(NEO_KHZ400) + if( !is800KHz ) + { + CYCLES_X00 = CYCLES_400; + CYCLES_X00_T1H = CYCLES_400_T1H; + CYCLES_X00_T0H = CYCLES_400_T0H; + } +#endif + + // Enable DWT in debug core + CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; + DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; + + // Tries to re-send the frame if is interrupted by the SoftDevice. + while(1) { + uint8_t *p = pixels; + + uint32_t cycStart = DWT->CYCCNT; + uint32_t cyc = 0; + + for(uint16_t n=0; n>= 1) { + while(DWT->CYCCNT - cyc < CYCLES_X00); + cyc = DWT->CYCCNT; + + nrf_port->OUTSET |= pinMask; + + if(pix & mask) { + while(DWT->CYCCNT - cyc < CYCLES_X00_T1H); + } else { + while(DWT->CYCCNT - cyc < CYCLES_X00_T0H); + } + + nrf_port->OUTCLR |= pinMask; + } + } + while(DWT->CYCCNT - cyc < CYCLES_X00); + + + // If total time longer than 25%, resend the whole data. + // Since we are likely to be interrupted by SoftDevice + if ( (DWT->CYCCNT - cycStart) < ( 8*numBytes*((CYCLES_X00*5)/4) ) ) { + break; + } + + // re-send need 300us delay + delayMicroseconds(300); + } + + // Enable interrupts again + #if defined(ARDUINO_NRF52_ADAFRUIT) + taskEXIT_CRITICAL(); + #elif defined(NRF52_DISABLE_INT) + __enable_irq(); + #endif +#endif + } +// END of NRF52 implementation + +#elif defined (__SAMD21E17A__) || defined(__SAMD21G18A__) || defined(__SAMD21E18A__) || defined(__SAMD21J18A__) // Arduino Zero, Gemma/Trinket M0, SODAQ Autonomo and others // Tried this with a timer/counter, couldn't quite get adequate - // resolution. So yay, you get a load of goofball NOPs... + // resolution. So yay, you get a load of goofball NOPs... uint8_t *ptr, *end, p, bitMask, portNum; uint32_t pinMask; @@ -1208,7 +1673,7 @@ void Adafruit_NeoPixel::show(void) { volatile uint32_t *set = &(PORT->Group[portNum].OUTSET.reg), *clr = &(PORT->Group[portNum].OUTCLR.reg); -#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled if(is800KHz) { #endif for(;;) { @@ -1233,7 +1698,7 @@ void Adafruit_NeoPixel::show(void) { bitMask = 0x80; } } -#ifdef NEO_KHZ400 +#if defined(NEO_KHZ400) } else { // 400 KHz bitstream for(;;) { *set = pinMask; @@ -1266,10 +1731,78 @@ void Adafruit_NeoPixel::show(void) { } #endif +#elif defined (__SAMD51__) // M4 + + uint8_t *ptr, *end, p, bitMask, portNum, bit; + uint32_t pinMask; + + portNum = g_APinDescription[pin].ulPort; + pinMask = 1ul << g_APinDescription[pin].ulPin; + ptr = pixels; + end = ptr + numBytes; + p = *ptr++; + bitMask = 0x80; + + volatile uint32_t *set = &(PORT->Group[portNum].OUTSET.reg), + *clr = &(PORT->Group[portNum].OUTCLR.reg); + + // SAMD51 overclock-compatible timing is only a mild abomination. + // It uses SysTick for a consistent clock reference regardless of + // optimization / cache settings. That's the good news. The bad news, + // since SysTick->VAL is a volatile type it's slow to access...and then, + // with the SysTick interval that Arduino sets up (1 ms), this would + // require a subtract and MOD operation for gauging elapsed time, and + // all taken in combination that lacks adequate temporal resolution + // for NeoPixel timing. So a kind of horrible thing is done here... + // since interrupts are turned off anyway and it's generally accepted + // by now that we're gonna lose track of time in the NeoPixel lib, + // the SysTick timer is reconfigured for a period matching the NeoPixel + // bit timing (either 800 or 400 KHz) and we watch SysTick->VAL very + // closely (just a threshold, no subtract or MOD or anything) and that + // seems to work just well enough. When finished, the SysTick + // peripheral is set back to its original state. + + uint32_t t0, t1, top, ticks, + saveLoad = SysTick->LOAD, saveVal = SysTick->VAL; + +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled + if(is800KHz) { +#endif + top = (uint32_t)(F_CPU * 0.00000125); // Bit hi + lo = 1.25 uS + t0 = top - (uint32_t)(F_CPU * 0.00000040); // 0 = 0.4 uS hi + t1 = top - (uint32_t)(F_CPU * 0.00000080); // 1 = 0.8 uS hi +#if defined(NEO_KHZ400) + } else { // 400 KHz bitstream + top = (uint32_t)(F_CPU * 0.00000250); // Bit hi + lo = 2.5 uS + t0 = top - (uint32_t)(F_CPU * 0.00000050); // 0 = 0.5 uS hi + t1 = top - (uint32_t)(F_CPU * 0.00000120); // 1 = 1.2 uS hi + } +#endif + + SysTick->LOAD = top; // Config SysTick for NeoPixel bit freq + SysTick->VAL = top; // Set to start value (counts down) + (void)SysTick->VAL; // Dummy read helps sync up 1st bit + + for(;;) { + *set = pinMask; // Set output high + ticks = (p & bitMask) ? t1 : t0; // SysTick threshold, + while(SysTick->VAL > ticks); // wait for it + *clr = pinMask; // Set output low + if(!(bitMask >>= 1)) { // Next bit for this byte...done? + if(ptr >= end) break; // If last byte sent, exit loop + p = *ptr++; // Fetch next byte + bitMask = 0x80; // Reset bitmask + } + while(SysTick->VAL <= ticks); // Wait for rollover to 'top' + } + + SysTick->LOAD = saveLoad; // Restore SysTick rollover to 1 ms + SysTick->VAL = saveVal; // Restore SysTick value + #elif defined (ARDUINO_STM32_FEATHER) // FEATHER WICED (120MHz) // Tried this with a timer/counter, couldn't quite get adequate - // resolution. So yay, you get a load of goofball NOPs... + // resolution. So yay, you get a load of goofball NOPs... uint8_t *ptr, *end, p, bitMask; uint32_t pinMask; @@ -1283,7 +1816,7 @@ void Adafruit_NeoPixel::show(void) { volatile uint16_t *set = &(PIN_MAP[pin].gpio_device->regs->BSRRL); volatile uint16_t *clr = &(PIN_MAP[pin].gpio_device->regs->BSRRH); -#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled if(is800KHz) { #endif for(;;) { @@ -1342,13 +1875,184 @@ void Adafruit_NeoPixel::show(void) { bitMask = 0x80; } } -#ifdef NEO_KHZ400 +#if defined(NEO_KHZ400) } else { // 400 KHz bitstream // ToDo! } #endif -#else // Other ARM architecture -- Presumed Arduino Due +#elif defined(TARGET_LPC1768) + uint8_t *ptr, *end, p, bitMask; + ptr = pixels; + end = ptr + numBytes; + p = *ptr++; + bitMask = 0x80; + +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled + if(is800KHz) { +#endif + for(;;) { + if(p & bitMask) { + // data ONE high + // min: 550 typ: 700 max: 5,500 + gpio_set(pin); + time::delay_ns(550); + // min: 450 typ: 600 max: 5,000 + gpio_clear(pin); + time::delay_ns(450); + } else { + // data ZERO high + // min: 200 typ: 350 max: 500 + gpio_set(pin); + time::delay_ns(200); + // data low + // min: 450 typ: 600 max: 5,000 + gpio_clear(pin); + time::delay_ns(450); + } + if(bitMask >>= 1) { + // Move on to the next pixel + asm("nop;"); + } else { + if(ptr >= end) break; + p = *ptr++; + bitMask = 0x80; + } + } +#if defined(NEO_KHZ400) + } else { // 400 KHz bitstream + // ToDo! + } +#endif +#elif defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32) + uint8_t *p = pixels, *end = p + numBytes, + pix = *p++, mask = 0x80; + uint32_t cyc; + uint32_t saveLoad = SysTick->LOAD, saveVal = SysTick->VAL; +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled + if(is800KHz) { +#endif + uint32_t top = (F_CPU / 800000); // 1.25µs + uint32_t t0 = top - (F_CPU / 2500000); // 0.4µs + uint32_t t1 = top - (F_CPU / 1250000); // 0.8µs + SysTick->LOAD = top - 1; // Config SysTick for NeoPixel bit freq + SysTick->VAL = 0; // Set to start value + for(;;) { + LL_GPIO_SetOutputPin(gpioPort, gpioPin); + cyc = (pix & mask) ? t1 : t0; + while(SysTick->VAL > cyc); + LL_GPIO_ResetOutputPin(gpioPort, gpioPin); + if(!(mask >>= 1)) { + if(p >= end) break; + pix = *p++; + mask = 0x80; + } + while(SysTick->VAL <= cyc); + } +#if defined(NEO_KHZ400) + } else { // 400 kHz bitstream + uint32_t top = (F_CPU / 400000); // 2.5µs + uint32_t t0 = top - (F_CPU / 2000000); // 0.5µs + uint32_t t1 = top - (F_CPU / 833333); // 1.2µs + SysTick->LOAD = top - 1; // Config SysTick for NeoPixel bit freq + SysTick->VAL = 0; // Set to start value + for(;;) { + LL_GPIO_SetOutputPin(gpioPort, gpioPin); + cyc = (pix & mask) ? t1 : t0; + while(SysTick->VAL > cyc); + LL_GPIO_ResetOutputPin(gpioPort, gpioPin); + if(!(mask >>= 1)) { + if(p >= end) break; + pix = *p++; + mask = 0x80; + } + while(SysTick->VAL <= cyc); + } + } +#endif // NEO_KHZ400 + SysTick->LOAD = saveLoad; // Restore SysTick rollover to 1 ms + SysTick->VAL = saveVal; // Restore SysTick value +#elif defined (NRF51) + uint8_t *p = pixels, + pix, count, mask; + int32_t num = numBytes; + unsigned int bitmask = ( 1 << g_ADigitalPinMap[pin] ); +// https://github.com/sandeepmistry/arduino-nRF5/blob/dc53980c8bac27898fca90d8ecb268e11111edc1/variants/BBCmicrobit/variant.cpp + + volatile unsigned int *reg = (unsigned int *) (0x50000000UL + 0x508); + +// https://github.com/sandeepmistry/arduino-nRF5/blob/dc53980c8bac27898fca90d8ecb268e11111edc1/cores/nRF5/SDK/components/device/nrf51.h +// http://www.iot-programmer.com/index.php/books/27-micro-bit-iot-in-c/chapters-micro-bit-iot-in-c/47-micro-bit-iot-in-c-fast-memory-mapped-gpio?showall=1 +// https://github.com/Microsoft/pxt-neopixel/blob/master/sendbuffer.asm + + asm volatile( + // "cpsid i" ; disable irq + + // b .start + "b L%=_start" "\n\t" + // .nextbit: ; C0 + "L%=_nextbit:" "\n\t" //; C0 + // str r1, [r3, #0] ; pin := hi C2 + "strb %[bitmask], [%[reg], #0]" "\n\t" //; pin := hi C2 + // tst r6, r0 ; C3 + "tst %[mask], %[pix]" "\n\t"// ; C3 + // bne .islate ; C4 + "bne L%=_islate" "\n\t" //; C4 + // str r1, [r2, #0] ; pin := lo C6 + "strb %[bitmask], [%[reg], #4]" "\n\t" //; pin := lo C6 + // .islate: + "L%=_islate:" "\n\t" + // lsrs r6, r6, #1 ; r6 >>= 1 C7 + "lsr %[mask], %[mask], #1" "\n\t" //; r6 >>= 1 C7 + // bne .justbit ; C8 + "bne L%=_justbit" "\n\t" //; C8 + + // ; not just a bit - need new byte + // adds r4, #1 ; r4++ C9 + "add %[p], #1" "\n\t" //; r4++ C9 + // subs r5, #1 ; r5-- C10 + "sub %[num], #1" "\n\t" //; r5-- C10 + // bcc .stop ; if (r5<0) goto .stop C11 + "bcc L%=_stop" "\n\t" //; if (r5<0) goto .stop C11 + // .start: + "L%=_start:" + // movs r6, #0x80 ; reset mask C12 + "movs %[mask], #0x80" "\n\t" //; reset mask C12 + // nop ; C13 + "nop" "\n\t" //; C13 + + // .common: ; C13 + "L%=_common:" "\n\t" //; C13 + // str r1, [r2, #0] ; pin := lo C15 + "strb %[bitmask], [%[reg], #4]" "\n\t" //; pin := lo C15 + // ; always re-load byte - it just fits with the cycles better this way + // ldrb r0, [r4, #0] ; r0 := *r4 C17 + "ldrb %[pix], [%[p], #0]" "\n\t" //; r0 := *r4 C17 + // b .nextbit ; C20 + "b L%=_nextbit" "\n\t" //; C20 + + // .justbit: ; C10 + "L%=_justbit:" "\n\t" //; C10 + // ; no nops, branch taken is already 3 cycles + // b .common ; C13 + "b L%=_common" "\n\t" //; C13 + + // .stop: + "L%=_stop:" "\n\t" + // str r1, [r2, #0] ; pin := lo + "strb %[bitmask], [%[reg], #4]" "\n\t" //; pin := lo + // cpsie i ; enable irq + + : [p] "+r" (p), + [pix] "=&r" (pix), + [count] "=&r" (count), + [mask] "=&r" (mask), + [num] "+r" (num) + : [bitmask] "r" (bitmask), + [reg] "r" (reg) + ); + +#elif defined(__SAM3X8E__) // Arduino Due #define SCALE VARIANT_MCK / 2UL / 1000000UL #define INST (2UL * F_CPU / VARIANT_MCK) @@ -1371,7 +2075,7 @@ void Adafruit_NeoPixel::show(void) { TC_Start(TC1, 0); pinMask = g_APinDescription[pin].ulPin; // Don't 'optimize' these into - port = g_APinDescription[pin].pPort; // declarations above. Want to + port = g_APinDescription[pin].pPort; // declarations above. Want to portSet = &(port->PIO_SODR); // burn a few cycles after portClear = &(port->PIO_CODR); // starting timer to minimize timeValue = &(TC1->TC_CHANNEL[0].TC_CV); // the initial 'while'. @@ -1381,13 +2085,13 @@ void Adafruit_NeoPixel::show(void) { pix = *p++; mask = 0x80; -#ifdef NEO_KHZ400 // 800 KHz check needed only if 400 KHz support enabled +#if defined(NEO_KHZ400) // 800 KHz check needed only if 400 KHz support enabled if(is800KHz) { #endif time0 = TIME_800_0; time1 = TIME_800_1; period = PERIOD_800; -#ifdef NEO_KHZ400 +#if defined(NEO_KHZ400) } else { // 400 KHz bitstream time0 = TIME_400_0; time1 = TIME_400_1; @@ -1397,10 +2101,10 @@ void Adafruit_NeoPixel::show(void) { for(t = time0;; t = time0) { if(pix & mask) t = time1; - while(*timeValue < period); + while(*timeValue < (unsigned)period); *portSet = pinMask; *timeReset = TC_CCR_CLKEN | TC_CCR_SWTRG; - while(*timeValue < t); + while(*timeValue < (unsigned)t); *portClear = pinMask; if(!(mask >>= 1)) { // This 'inside-out' loop logic utilizes if(p >= end) break; // idle time to minimize inter-byte delays. @@ -1408,7 +2112,7 @@ void Adafruit_NeoPixel::show(void) { mask = 0x80; } } - while(*timeValue < period); // Wait for last bit + while(*timeValue < (unsigned)period); // Wait for last bit TC_Stop(TC1, 0); #endif // end Due @@ -1416,13 +2120,17 @@ void Adafruit_NeoPixel::show(void) { // END ARM ---------------------------------------------------------------- -#elif defined(ESP8266) +#elif defined(ESP8266) || defined(ESP32) // ESP8266 ---------------------------------------------------------------- // ESP8266 show() is external to enforce IRAM_ATTR execution espShow(pin, pixels, numBytes, is800KHz); +#elif defined(KENDRYTE_K210) + + k210Show(pin, pixels, numBytes, is800KHz); + #elif defined(__ARDUINO_ARC__) // Arduino 101 ----------------------------------------------------------- @@ -1517,31 +2225,50 @@ void Adafruit_NeoPixel::show(void) { } } +#else +#error Architecture not supported #endif // END ARCHITECTURE SELECT ------------------------------------------------ - +#if !( defined(NRF52) || defined(NRF52_SERIES) ) interrupts(); +#endif + endTime = micros(); // Save EOD time for latch on next call } -// Set the output pin number -void Adafruit_NeoPixel::setPin(uint8_t p) { - if(begun && (pin >= 0)) pinMode(pin, INPUT); - pin = p; - if(begun) { - pinMode(p, OUTPUT); - digitalWrite(p, LOW); - } -#ifdef __AVR__ - port = portOutputRegister(digitalPinToPort(p)); - pinMask = digitalPinToBitMask(p); +/*! + @brief Set/change the NeoPixel output pin number. Previous pin, + if any, is set to INPUT and the new pin is set to OUTPUT. + @param p Arduino pin number (-1 = no pin). +*/ +void Adafruit_NeoPixel::setPin(int16_t p) { + if(begun && (pin >= 0)) pinMode(pin, INPUT); // Disable existing out pin + pin = p; + if(begun) { + pinMode(p, OUTPUT); + digitalWrite(p, LOW); + } +#if defined(__AVR__) + port = portOutputRegister(digitalPinToPort(p)); + pinMask = digitalPinToBitMask(p); +#endif +#if defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32) + gpioPort = digitalPinToPort(p); + gpioPin = STM_LL_GPIO_PIN(digitalPinToPinName(p)); #endif } -// Set pixel color from separate R,G,B components: +/*! + @brief Set a pixel's color using separate red, green and blue + components. If using RGBW pixels, white will be set to 0. + @param n Pixel index, starting from 0. + @param r Red brightness, 0 = minimum (off), 255 = maximum. + @param g Green brightness, 0 = minimum (off), 255 = maximum. + @param b Blue brightness, 0 = minimum (off), 255 = maximum. +*/ void Adafruit_NeoPixel::setPixelColor( uint16_t n, uint8_t r, uint8_t g, uint8_t b) { @@ -1564,6 +2291,16 @@ void Adafruit_NeoPixel::setPixelColor( } } +/*! + @brief Set a pixel's color using separate red, green, blue and white + components (for RGBW NeoPixels only). + @param n Pixel index, starting from 0. + @param r Red brightness, 0 = minimum (off), 255 = maximum. + @param g Green brightness, 0 = minimum (off), 255 = maximum. + @param b Blue brightness, 0 = minimum (off), 255 = maximum. + @param w White brightness, 0 = minimum (off), 255 = maximum, ignored + if using RGB pixels. +*/ void Adafruit_NeoPixel::setPixelColor( uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t w) { @@ -1587,7 +2324,13 @@ void Adafruit_NeoPixel::setPixelColor( } } -// Set pixel color from 'packed' 32-bit RGB color: +/*! + @brief Set a pixel's color using a 32-bit 'packed' RGB or RGBW value. + @param n Pixel index, starting from 0. + @param c 32-bit color value. Most significant byte is white (for RGBW + pixels) or ignored (for RGB pixels), next is red, then green, + and least significant byte is blue. +*/ void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint32_t c) { if(n < numLEDs) { uint8_t *p, @@ -1612,19 +2355,149 @@ void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint32_t c) { } } -// Convert separate R,G,B into packed 32-bit RGB color. -// Packed format is always RGB, regardless of LED strand color order. -uint32_t Adafruit_NeoPixel::Color(uint8_t r, uint8_t g, uint8_t b) { - return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; +/*! + @brief Fill all or part of the NeoPixel strip with a color. + @param c 32-bit color value. Most significant byte is white (for + RGBW pixels) or ignored (for RGB pixels), next is red, + then green, and least significant byte is blue. If all + arguments are unspecified, this will be 0 (off). + @param first Index of first pixel to fill, starting from 0. Must be + in-bounds, no clipping is performed. 0 if unspecified. + @param count Number of pixels to fill, as a positive value. Passing + 0 or leaving unspecified will fill to end of strip. +*/ +void Adafruit_NeoPixel::fill(uint32_t c, uint16_t first, uint16_t count) { + uint16_t i, end; + + if(first >= numLEDs) { + return; // If first LED is past end of strip, nothing to do + } + + // Calculate the index ONE AFTER the last pixel to fill + if(count == 0) { + // Fill to end of strip + end = numLEDs; + } else { + // Ensure that the loop won't go past the last pixel + end = first + count; + if(end > numLEDs) end = numLEDs; + } + + for(i = first; i < end; i++) { + this->setPixelColor(i, c); + } } -// Convert separate R,G,B,W into packed 32-bit WRGB color. -// Packed format is always WRGB, regardless of LED strand color order. -uint32_t Adafruit_NeoPixel::Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w) { - return ((uint32_t)w << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; +/*! + @brief Convert hue, saturation and value into a packed 32-bit RGB color + that can be passed to setPixelColor() or other RGB-compatible + functions. + @param hue An unsigned 16-bit value, 0 to 65535, representing one full + loop of the color wheel, which allows 16-bit hues to "roll + over" while still doing the expected thing (and allowing + more precision than the wheel() function that was common to + prior NeoPixel examples). + @param sat Saturation, 8-bit value, 0 (min or pure grayscale) to 255 + (max or pure hue). Default of 255 if unspecified. + @param val Value (brightness), 8-bit value, 0 (min / black / off) to + 255 (max or full brightness). Default of 255 if unspecified. + @return Packed 32-bit RGB with the most significant byte set to 0 -- the + white element of WRGB pixels is NOT utilized. Result is linearly + but not perceptually correct, so you may want to pass the result + through the gamma32() function (or your own gamma-correction + operation) else colors may appear washed out. This is not done + automatically by this function because coders may desire a more + refined gamma-correction function than the simplified + one-size-fits-all operation of gamma32(). Diffusing the LEDs also + really seems to help when using low-saturation colors. +*/ +uint32_t Adafruit_NeoPixel::ColorHSV(uint16_t hue, uint8_t sat, uint8_t val) { + + uint8_t r, g, b; + + // Remap 0-65535 to 0-1529. Pure red is CENTERED on the 64K rollover; + // 0 is not the start of pure red, but the midpoint...a few values above + // zero and a few below 65536 all yield pure red (similarly, 32768 is the + // midpoint, not start, of pure cyan). The 8-bit RGB hexcone (256 values + // each for red, green, blue) really only allows for 1530 distinct hues + // (not 1536, more on that below), but the full unsigned 16-bit type was + // chosen for hue so that one's code can easily handle a contiguous color + // wheel by allowing hue to roll over in either direction. + hue = (hue * 1530L + 32768) / 65536; + // Because red is centered on the rollover point (the +32768 above, + // essentially a fixed-point +0.5), the above actually yields 0 to 1530, + // where 0 and 1530 would yield the same thing. Rather than apply a + // costly modulo operator, 1530 is handled as a special case below. + + // So you'd think that the color "hexcone" (the thing that ramps from + // pure red, to pure yellow, to pure green and so forth back to red, + // yielding six slices), and with each color component having 256 + // possible values (0-255), might have 1536 possible items (6*256), + // but in reality there's 1530. This is because the last element in + // each 256-element slice is equal to the first element of the next + // slice, and keeping those in there this would create small + // discontinuities in the color wheel. So the last element of each + // slice is dropped...we regard only elements 0-254, with item 255 + // being picked up as element 0 of the next slice. Like this: + // Red to not-quite-pure-yellow is: 255, 0, 0 to 255, 254, 0 + // Pure yellow to not-quite-pure-green is: 255, 255, 0 to 1, 255, 0 + // Pure green to not-quite-pure-cyan is: 0, 255, 0 to 0, 255, 254 + // and so forth. Hence, 1530 distinct hues (0 to 1529), and hence why + // the constants below are not the multiples of 256 you might expect. + + // Convert hue to R,G,B (nested ifs faster than divide+mod+switch): + if(hue < 510) { // Red to Green-1 + b = 0; + if(hue < 255) { // Red to Yellow-1 + r = 255; + g = hue; // g = 0 to 254 + } else { // Yellow to Green-1 + r = 510 - hue; // r = 255 to 1 + g = 255; + } + } else if(hue < 1020) { // Green to Blue-1 + r = 0; + if(hue < 765) { // Green to Cyan-1 + g = 255; + b = hue - 510; // b = 0 to 254 + } else { // Cyan to Blue-1 + g = 1020 - hue; // g = 255 to 1 + b = 255; + } + } else if(hue < 1530) { // Blue to Red-1 + g = 0; + if(hue < 1275) { // Blue to Magenta-1 + r = hue - 1020; // r = 0 to 254 + b = 255; + } else { // Magenta to Red-1 + r = 255; + b = 1530 - hue; // b = 255 to 1 + } + } else { // Last 0.5 Red (quicker than % operator) + r = 255; + g = b = 0; + } + + // Apply saturation and value to R,G,B, pack into 32-bit result: + uint32_t v1 = 1 + val; // 1 to 256; allows >>8 instead of /255 + uint16_t s1 = 1 + sat; // 1 to 256; same reason + uint8_t s2 = 255 - sat; // 255 to 0 + return ((((((r * s1) >> 8) + s2) * v1) & 0xff00) << 8) | + (((((g * s1) >> 8) + s2) * v1) & 0xff00) | + ( ((((b * s1) >> 8) + s2) * v1) >> 8); } -// Query color from previously-set pixel (returns packed 32-bit RGB value) +/*! + @brief Query the color of a previously-set pixel. + @param n Index of pixel to read (0 = first). + @return 'Packed' 32-bit RGB or WRGB value. Most significant byte is white + (for RGBW pixels) or 0 (for RGB pixels), next is red, then green, + and least significant byte is blue. + @note If the strip brightness has been changed from the default value + of 255, the color read from a pixel may not exactly match what + was previously written with one of the setPixelColor() functions. + This gets more pronounced at lower brightness levels. +*/ uint32_t Adafruit_NeoPixel::getPixelColor(uint16_t n) const { if(n >= numLEDs) return 0; // Out of bounds, return no color. @@ -1633,10 +2506,10 @@ uint32_t Adafruit_NeoPixel::getPixelColor(uint16_t n) const { if(wOffset == rOffset) { // Is RGB-type device p = &pixels[n * 3]; if(brightness) { - // Stored color was decimated by setBrightness(). Returned value + // Stored color was decimated by setBrightness(). Returned value // attempts to scale back to an approximation of the original 24-bit // value used when setting the pixel color, but there will always be - // some error -- those bits are simply gone. Issue is most + // some error -- those bits are simply gone. Issue is most // pronounced at low brightness levels. return (((uint32_t)(p[rOffset] << 8) / brightness) << 16) | (((uint32_t)(p[gOffset] << 8) / brightness) << 8) | @@ -1663,39 +2536,41 @@ uint32_t Adafruit_NeoPixel::getPixelColor(uint16_t n) const { } } -// Returns pointer to pixels[] array. Pixel data is stored in device- -// native format and is not translated here. Application will need to be -// aware of specific pixel data format and handle colors appropriately. -uint8_t *Adafruit_NeoPixel::getPixels(void) const { - return pixels; -} -uint16_t Adafruit_NeoPixel::numPixels(void) const { - return numLEDs; -} - -// Adjust output brightness; 0=darkest (off), 255=brightest. This does -// NOT immediately affect what's currently displayed on the LEDs. The -// next call to show() will refresh the LEDs at this level. However, -// this process is potentially "lossy," especially when increasing -// brightness. The tight timing in the WS2811/WS2812 code means there -// aren't enough free cycles to perform this scaling on the fly as data -// is issued. So we make a pass through the existing color data in RAM -// and scale it (subsequent graphics commands also work at this -// brightness level). If there's a significant step up in brightness, -// the limited number of steps (quantization) in the old data will be -// quite visible in the re-scaled version. For a non-destructive -// change, you'll need to re-render the full strip data. C'est la vie. +/*! + @brief Adjust output brightness. Does not immediately affect what's + currently displayed on the LEDs. The next call to show() will + refresh the LEDs at this level. + @param b Brightness setting, 0=minimum (off), 255=brightest. + @note This was intended for one-time use in one's setup() function, + not as an animation effect in itself. Because of the way this + library "pre-multiplies" LED colors in RAM, changing the + brightness is often a "lossy" operation -- what you write to + pixels isn't necessary the same as what you'll read back. + Repeated brightness changes using this function exacerbate the + problem. Smart programs therefore treat the strip as a + write-only resource, maintaining their own state to render each + frame of an animation, not relying on read-modify-write. +*/ void Adafruit_NeoPixel::setBrightness(uint8_t b) { // Stored brightness value is different than what's passed. // This simplifies the actual scaling math later, allowing a fast - // 8x8-bit multiply and taking the MSB. 'brightness' is a uint8_t, + // 8x8-bit multiply and taking the MSB. 'brightness' is a uint8_t, // adding 1 here may (intentionally) roll over...so 0 = max brightness // (color values are interpreted literally; no scaling), 1 = min // brightness (off), 255 = just below max brightness. uint8_t newBrightness = b + 1; if(newBrightness != brightness) { // Compare against prior value - // Brightness has changed -- re-scale existing data in RAM + // Brightness has changed -- re-scale existing data in RAM, + // This process is potentially "lossy," especially when increasing + // brightness. The tight timing in the WS2811/WS2812 code means there + // aren't enough free cycles to perform this scaling on the fly as data + // is issued. So we make a pass through the existing color data in RAM + // and scale it (subsequent graphics commands also work at this + // brightness level). If there's a significant step up in brightness, + // the limited number of steps (quantization) in the old data will be + // quite visible in the re-scaled version. For a non-destructive + // change, you'll need to re-render the full strip data. C'est la vie. uint8_t c, *ptr = pixels, oldBrightness = brightness - 1; // De-wrap old brightness value @@ -1711,24 +2586,33 @@ void Adafruit_NeoPixel::setBrightness(uint8_t b) { } } -//Return the brightness value +/*! + @brief Retrieve the last-set brightness value for the strip. + @return Brightness value: 0 = minimum (off), 255 = maximum. +*/ uint8_t Adafruit_NeoPixel::getBrightness(void) const { return brightness - 1; } -void Adafruit_NeoPixel::clear() { +/*! + @brief Fill the whole NeoPixel strip with 0 / black / off. +*/ +void Adafruit_NeoPixel::clear(void) { memset(pixels, 0, numBytes); } - - - - - - - - - - - - +// A 32-bit variant of gamma8() that applies the same function +// to all components of a packed RGB or WRGB value. +uint32_t Adafruit_NeoPixel::gamma32(uint32_t x) { + uint8_t *y = (uint8_t *)&x; + // All four bytes of a 32-bit value are filtered even if RGB (not WRGB), + // to avoid a bunch of shifting and masking that would be necessary for + // properly handling different endianisms (and each byte is a fairly + // trivial operation, so it might not even be wasting cycles vs a check + // and branch for the RGB case). In theory this might cause trouble *if* + // someone's storing information in the unused most significant byte + // of an RGB value, but this seems exceedingly rare and if it's + // encountered in reality they can mask values going in or coming out. + for(uint8_t i=0; i<4; i++) y[i] = gamma8(y[i]); + return x; // Packed 32-bit return +} diff --git a/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.h b/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.h index b051d7d17..68c2fbd54 100644 --- a/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.h +++ b/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.h @@ -1,105 +1,129 @@ -/*-------------------------------------------------------------------- - This file is part of the Adafruit NeoPixel library. - - NeoPixel is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as - published by the Free Software Foundation, either version 3 of - the License, or (at your option) any later version. - - NeoPixel is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with NeoPixel. If not, see - . - --------------------------------------------------------------------*/ +/*! + * @file Adafruit_NeoPixel.h + * + * This is part of Adafruit's NeoPixel library for the Arduino platform, + * allowing a broad range of microcontroller boards (most AVR boards, + * many ARM devices, ESP8266 and ESP32, among others) to control Adafruit + * NeoPixels, FLORA RGB Smart Pixels and compatible devices -- WS2811, + * WS2812, WS2812B, SK6812, etc. + * + * Adafruit invests time and resources providing this open source code, + * please support Adafruit and open-source hardware by purchasing products + * from Adafruit! + * + * Written by Phil "Paint Your Dragon" Burgess for Adafruit Industries, + * with contributions by PJRC, Michael Miller and other members of the + * open source community. + * + * This file is part of the Adafruit_NeoPixel library. + * + * Adafruit_NeoPixel is free software: you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * Adafruit_NeoPixel is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with NeoPixel. If not, see + * . + * + */ #ifndef ADAFRUIT_NEOPIXEL_H #define ADAFRUIT_NEOPIXEL_H -#if (ARDUINO >= 100) - #include -#else - #include - #include +#ifdef ARDUINO + #if (ARDUINO >= 100) + #include + #else + #include + #include + #endif #endif -// The order of primary colors in the NeoPixel data stream can vary -// among device types, manufacturers and even different revisions of -// the same item. The third parameter to the Adafruit_NeoPixel -// constructor encodes the per-pixel byte offsets of the red, green -// and blue primaries (plus white, if present) in the data stream -- -// the following #defines provide an easier-to-use named version for -// each permutation. e.g. NEO_GRB indicates a NeoPixel-compatible -// device expecting three bytes per pixel, with the first byte -// containing the green value, second containing red and third -// containing blue. The in-memory representation of a chain of -// NeoPixels is the same as the data-stream order; no re-ordering of -// bytes is required when issuing data to the chain. +#ifdef TARGET_LPC1768 + #include +#endif -// Bits 5,4 of this value are the offset (0-3) from the first byte of -// a pixel to the location of the red color byte. Bits 3,2 are the -// green offset and 1,0 are the blue offset. If it is an RGBW-type -// device (supporting a white primary in addition to R,G,B), bits 7,6 -// are the offset to the white byte...otherwise, bits 7,6 are set to -// the same value as 5,4 (red) to indicate an RGB (not RGBW) device. +// The order of primary colors in the NeoPixel data stream can vary among +// device types, manufacturers and even different revisions of the same +// item. The third parameter to the Adafruit_NeoPixel constructor encodes +// the per-pixel byte offsets of the red, green and blue primaries (plus +// white, if present) in the data stream -- the following #defines provide +// an easier-to-use named version for each permutation. e.g. NEO_GRB +// indicates a NeoPixel-compatible device expecting three bytes per pixel, +// with the first byte transmitted containing the green value, second +// containing red and third containing blue. The in-memory representation +// of a chain of NeoPixels is the same as the data-stream order; no +// re-ordering of bytes is required when issuing data to the chain. +// Most of these values won't exist in real-world devices, but it's done +// this way so we're ready for it (also, if using the WS2811 driver IC, +// one might have their pixels set up in any weird permutation). + +// Bits 5,4 of this value are the offset (0-3) from the first byte of a +// pixel to the location of the red color byte. Bits 3,2 are the green +// offset and 1,0 are the blue offset. If it is an RGBW-type device +// (supporting a white primary in addition to R,G,B), bits 7,6 are the +// offset to the white byte...otherwise, bits 7,6 are set to the same value +// as 5,4 (red) to indicate an RGB (not RGBW) device. // i.e. binary representation: // 0bWWRRGGBB for RGBW devices // 0bRRRRGGBB for RGB // RGB NeoPixel permutations; white and red offsets are always same -// Offset: W R G B -#define NEO_RGB ((0 << 6) | (0 << 4) | (1 << 2) | (2)) -#define NEO_RBG ((0 << 6) | (0 << 4) | (2 << 2) | (1)) -#define NEO_GRB ((1 << 6) | (1 << 4) | (0 << 2) | (2)) -#define NEO_GBR ((2 << 6) | (2 << 4) | (0 << 2) | (1)) -#define NEO_BRG ((1 << 6) | (1 << 4) | (2 << 2) | (0)) -#define NEO_BGR ((2 << 6) | (2 << 4) | (1 << 2) | (0)) +// Offset: W R G B +#define NEO_RGB ((0<<6) | (0<<4) | (1<<2) | (2)) ///< Transmit as R,G,B +#define NEO_RBG ((0<<6) | (0<<4) | (2<<2) | (1)) ///< Transmit as R,B,G +#define NEO_GRB ((1<<6) | (1<<4) | (0<<2) | (2)) ///< Transmit as G,R,B +#define NEO_GBR ((2<<6) | (2<<4) | (0<<2) | (1)) ///< Transmit as G,B,R +#define NEO_BRG ((1<<6) | (1<<4) | (2<<2) | (0)) ///< Transmit as B,R,G +#define NEO_BGR ((2<<6) | (2<<4) | (1<<2) | (0)) ///< Transmit as B,G,R // RGBW NeoPixel permutations; all 4 offsets are distinct // Offset: W R G B -#define NEO_WRGB ((0 << 6) | (1 << 4) | (2 << 2) | (3)) -#define NEO_WRBG ((0 << 6) | (1 << 4) | (3 << 2) | (2)) -#define NEO_WGRB ((0 << 6) | (2 << 4) | (1 << 2) | (3)) -#define NEO_WGBR ((0 << 6) | (3 << 4) | (1 << 2) | (2)) -#define NEO_WBRG ((0 << 6) | (2 << 4) | (3 << 2) | (1)) -#define NEO_WBGR ((0 << 6) | (3 << 4) | (2 << 2) | (1)) +#define NEO_WRGB ((0<<6) | (1<<4) | (2<<2) | (3)) ///< Transmit as W,R,G,B +#define NEO_WRBG ((0<<6) | (1<<4) | (3<<2) | (2)) ///< Transmit as W,R,B,G +#define NEO_WGRB ((0<<6) | (2<<4) | (1<<2) | (3)) ///< Transmit as W,G,R,B +#define NEO_WGBR ((0<<6) | (3<<4) | (1<<2) | (2)) ///< Transmit as W,G,B,R +#define NEO_WBRG ((0<<6) | (2<<4) | (3<<2) | (1)) ///< Transmit as W,B,R,G +#define NEO_WBGR ((0<<6) | (3<<4) | (2<<2) | (1)) ///< Transmit as W,B,G,R -#define NEO_RWGB ((1 << 6) | (0 << 4) | (2 << 2) | (3)) -#define NEO_RWBG ((1 << 6) | (0 << 4) | (3 << 2) | (2)) -#define NEO_RGWB ((2 << 6) | (0 << 4) | (1 << 2) | (3)) -#define NEO_RGBW ((3 << 6) | (0 << 4) | (1 << 2) | (2)) -#define NEO_RBWG ((2 << 6) | (0 << 4) | (3 << 2) | (1)) -#define NEO_RBGW ((3 << 6) | (0 << 4) | (2 << 2) | (1)) +#define NEO_RWGB ((1<<6) | (0<<4) | (2<<2) | (3)) ///< Transmit as R,W,G,B +#define NEO_RWBG ((1<<6) | (0<<4) | (3<<2) | (2)) ///< Transmit as R,W,B,G +#define NEO_RGWB ((2<<6) | (0<<4) | (1<<2) | (3)) ///< Transmit as R,G,W,B +#define NEO_RGBW ((3<<6) | (0<<4) | (1<<2) | (2)) ///< Transmit as R,G,B,W +#define NEO_RBWG ((2<<6) | (0<<4) | (3<<2) | (1)) ///< Transmit as R,B,W,G +#define NEO_RBGW ((3<<6) | (0<<4) | (2<<2) | (1)) ///< Transmit as R,B,G,W -#define NEO_GWRB ((1 << 6) | (2 << 4) | (0 << 2) | (3)) -#define NEO_GWBR ((1 << 6) | (3 << 4) | (0 << 2) | (2)) -#define NEO_GRWB ((2 << 6) | (1 << 4) | (0 << 2) | (3)) -#define NEO_GRBW ((3 << 6) | (1 << 4) | (0 << 2) | (2)) -#define NEO_GBWR ((2 << 6) | (3 << 4) | (0 << 2) | (1)) -#define NEO_GBRW ((3 << 6) | (2 << 4) | (0 << 2) | (1)) +#define NEO_GWRB ((1<<6) | (2<<4) | (0<<2) | (3)) ///< Transmit as G,W,R,B +#define NEO_GWBR ((1<<6) | (3<<4) | (0<<2) | (2)) ///< Transmit as G,W,B,R +#define NEO_GRWB ((2<<6) | (1<<4) | (0<<2) | (3)) ///< Transmit as G,R,W,B +#define NEO_GRBW ((3<<6) | (1<<4) | (0<<2) | (2)) ///< Transmit as G,R,B,W +#define NEO_GBWR ((2<<6) | (3<<4) | (0<<2) | (1)) ///< Transmit as G,B,W,R +#define NEO_GBRW ((3<<6) | (2<<4) | (0<<2) | (1)) ///< Transmit as G,B,R,W -#define NEO_BWRG ((1 << 6) | (2 << 4) | (3 << 2) | (0)) -#define NEO_BWGR ((1 << 6) | (3 << 4) | (2 << 2) | (0)) -#define NEO_BRWG ((2 << 6) | (1 << 4) | (3 << 2) | (0)) -#define NEO_BRGW ((3 << 6) | (1 << 4) | (2 << 2) | (0)) -#define NEO_BGWR ((2 << 6) | (3 << 4) | (1 << 2) | (0)) -#define NEO_BGRW ((3 << 6) | (2 << 4) | (1 << 2) | (0)) +#define NEO_BWRG ((1<<6) | (2<<4) | (3<<2) | (0)) ///< Transmit as B,W,R,G +#define NEO_BWGR ((1<<6) | (3<<4) | (2<<2) | (0)) ///< Transmit as B,W,G,R +#define NEO_BRWG ((2<<6) | (1<<4) | (3<<2) | (0)) ///< Transmit as B,R,W,G +#define NEO_BRGW ((3<<6) | (1<<4) | (2<<2) | (0)) ///< Transmit as B,R,G,W +#define NEO_BGWR ((2<<6) | (3<<4) | (1<<2) | (0)) ///< Transmit as B,G,W,R +#define NEO_BGRW ((3<<6) | (2<<4) | (1<<2) | (0)) ///< Transmit as B,G,R,W -// Add NEO_KHZ400 to the color order value to indicate a 400 KHz -// device. All but the earliest v1 NeoPixels expect an 800 KHz data -// stream, this is the default if unspecified. Because flash space -// is very limited on ATtiny devices (e.g. Trinket, Gemma), v1 -// NeoPixels aren't handled by default on those chips, though it can -// be enabled by removing the ifndef/endif below -- but code will be -// bigger. Conversely, can disable the NEO_KHZ400 line on other MCUs -// to remove v1 support and save a little space. +// Add NEO_KHZ400 to the color order value to indicate a 400 KHz device. +// All but the earliest v1 NeoPixels expect an 800 KHz data stream, this is +// the default if unspecified. Because flash space is very limited on ATtiny +// devices (e.g. Trinket, Gemma), v1 NeoPixels aren't handled by default on +// those chips, though it can be enabled by removing the ifndef/endif below, +// but code will be bigger. Conversely, can disable the NEO_KHZ400 line on +// other MCUs to remove v1 support and save a little space. -#define NEO_KHZ800 0x0000 // 800 KHz datastream +#define NEO_KHZ800 0x0000 ///< 800 KHz data transmission #ifndef __AVR_ATtiny85__ -#define NEO_KHZ400 0x0100 // 400 KHz datastream +#define NEO_KHZ400 0x0100 ///< 400 KHz data transmission #endif // If 400 KHz support is enabled, the third parameter to the constructor @@ -108,74 +132,251 @@ // is sufficient to encode pixel color order, saving some space. #ifdef NEO_KHZ400 -typedef uint16_t neoPixelType; +typedef uint16_t neoPixelType; ///< 3rd arg to Adafruit_NeoPixel constructor #else -typedef uint8_t neoPixelType; +typedef uint8_t neoPixelType; ///< 3rd arg to Adafruit_NeoPixel constructor #endif +// These two tables are declared outside the Adafruit_NeoPixel class +// because some boards may require oldschool compilers that don't +// handle the C++11 constexpr keyword. + +/* A PROGMEM (flash mem) table containing 8-bit unsigned sine wave (0-255). + Copy & paste this snippet into a Python REPL to regenerate: +import math +for x in range(256): + print("{:3},".format(int((math.sin(x/128.0*math.pi)+1.0)*127.5+0.5))), + if x&15 == 15: print +*/ +static const uint8_t PROGMEM _NeoPixelSineTable[256] = { + 128,131,134,137,140,143,146,149,152,155,158,162,165,167,170,173, + 176,179,182,185,188,190,193,196,198,201,203,206,208,211,213,215, + 218,220,222,224,226,228,230,232,234,235,237,238,240,241,243,244, + 245,246,248,249,250,250,251,252,253,253,254,254,254,255,255,255, + 255,255,255,255,254,254,254,253,253,252,251,250,250,249,248,246, + 245,244,243,241,240,238,237,235,234,232,230,228,226,224,222,220, + 218,215,213,211,208,206,203,201,198,196,193,190,188,185,182,179, + 176,173,170,167,165,162,158,155,152,149,146,143,140,137,134,131, + 128,124,121,118,115,112,109,106,103,100, 97, 93, 90, 88, 85, 82, + 79, 76, 73, 70, 67, 65, 62, 59, 57, 54, 52, 49, 47, 44, 42, 40, + 37, 35, 33, 31, 29, 27, 25, 23, 21, 20, 18, 17, 15, 14, 12, 11, + 10, 9, 7, 6, 5, 5, 4, 3, 2, 2, 1, 1, 1, 0, 0, 0, + 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 9, + 10, 11, 12, 14, 15, 17, 18, 20, 21, 23, 25, 27, 29, 31, 33, 35, + 37, 40, 42, 44, 47, 49, 52, 54, 57, 59, 62, 65, 67, 70, 73, 76, + 79, 82, 85, 88, 90, 93, 97,100,103,106,109,112,115,118,121,124}; + +/* Similar to above, but for an 8-bit gamma-correction table. + Copy & paste this snippet into a Python REPL to regenerate: +import math +gamma=2.6 +for x in range(256): + print("{:3},".format(int(math.pow((x)/255.0,gamma)*255.0+0.5))), + if x&15 == 15: print +*/ +static const uint8_t PROGMEM _NeoPixelGammaTable[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, + 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, + 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, + 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, + 20, 21, 21, 22, 22, 23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29, + 30, 31, 31, 32, 33, 34, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42, + 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 75, + 76, 77, 78, 80, 81, 82, 84, 85, 86, 88, 89, 90, 92, 93, 94, 96, + 97, 99,100,102,103,105,106,108,109,111,112,114,115,117,119,120, + 122,124,125,127,129,130,132,134,136,137,139,141,143,145,146,148, + 150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180, + 182,184,186,188,191,193,195,197,199,202,204,206,209,211,213,215, + 218,220,223,225,227,230,232,235,237,240,242,245,247,250,252,255}; + +/*! + @brief Class that stores state and functions for interacting with + Adafruit NeoPixels and compatible devices. +*/ class Adafruit_NeoPixel { public: // Constructor: number of LEDs, pin number, LED type - Adafruit_NeoPixel(uint16_t n, uint8_t p=6, neoPixelType t=NEO_GRB + NEO_KHZ800); + Adafruit_NeoPixel(uint16_t n, int16_t pin=6, + neoPixelType type=NEO_GRB + NEO_KHZ800); Adafruit_NeoPixel(void); ~Adafruit_NeoPixel(); - void - begin(void), - show(void), - setPin(uint8_t p), - setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b), - setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t w), - setPixelColor(uint16_t n, uint32_t c), - setBrightness(uint8_t), - clear(), - updateLength(uint16_t n), - updateType(neoPixelType t); - uint8_t - *getPixels(void) const, - getBrightness(void) const; - int8_t - getPin(void) { return pin; }; - uint16_t - numPixels(void) const; - static uint32_t - Color(uint8_t r, uint8_t g, uint8_t b), - Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w); - uint32_t - getPixelColor(uint16_t n) const; - inline bool - canShow(void) { return (micros() - endTime) >= 50L; } + void begin(void); + void show(void); + void setPin(int16_t p); + void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b); + void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b, + uint8_t w); + void setPixelColor(uint16_t n, uint32_t c); + void fill(uint32_t c=0, uint16_t first=0, uint16_t count=0); + void setBrightness(uint8_t); + void clear(void); + void updateLength(uint16_t n); + void updateType(neoPixelType t); + /*! + @brief Check whether a call to show() will start sending data + immediately or will 'block' for a required interval. NeoPixels + require a short quiet time (about 300 microseconds) after the + last bit is received before the data 'latches' and new data can + start being received. Usually one's sketch is implicitly using + this time to generate a new frame of animation...but if it + finishes very quickly, this function could be used to see if + there's some idle time available for some low-priority + concurrent task. + @return 1 or true if show() will start sending immediately, 0 or false + if show() would block (meaning some idle time is available). + */ + bool canShow(void) { + // It's normal and possible for endTime to exceed micros() if the + // 32-bit clock counter has rolled over (about every 70 minutes). + // Since both are uint32_t, a negative delta correctly maps back to + // positive space, and it would seem like the subtraction below would + // suffice. But a problem arises if code invokes show() very + // infrequently...the micros() counter may roll over MULTIPLE times in + // that interval, the delta calculation is no longer correct and the + // next update may stall for a very long time. The check below resets + // the latch counter if a rollover has occurred. This can cause an + // extra delay of up to 300 microseconds in the rare case where a + // show() call happens precisely around the rollover, but that's + // neither likely nor especially harmful, vs. other code that might + // stall for 30+ minutes, or having to document and frequently remind + // and/or provide tech support explaining an unintuitive need for + // show() calls at least once an hour. + uint32_t now = micros(); + if (endTime > now) { + endTime = now; + } + return (now - endTime) >= 300L; + } + /*! + @brief Get a pointer directly to the NeoPixel data buffer in RAM. + Pixel data is stored in a device-native format (a la the NEO_* + constants) and is not translated here. Applications that access + this buffer will need to be aware of the specific data format + and handle colors appropriately. + @return Pointer to NeoPixel buffer (uint8_t* array). + @note This is for high-performance applications where calling + setPixelColor() on every single pixel would be too slow (e.g. + POV or light-painting projects). There is no bounds checking + on the array, creating tremendous potential for mayhem if one + writes past the ends of the buffer. Great power, great + responsibility and all that. + */ + uint8_t *getPixels(void) const { return pixels; }; + uint8_t getBrightness(void) const; + /*! + @brief Retrieve the pin number used for NeoPixel data output. + @return Arduino pin number (-1 if not set). + */ + int16_t getPin(void) const { return pin; }; + /*! + @brief Return the number of pixels in an Adafruit_NeoPixel strip object. + @return Pixel count (0 if not set). + */ + uint16_t numPixels(void) const { return numLEDs; } + uint32_t getPixelColor(uint16_t n) const; + /*! + @brief An 8-bit integer sine wave function, not directly compatible + with standard trigonometric units like radians or degrees. + @param x Input angle, 0-255; 256 would loop back to zero, completing + the circle (equivalent to 360 degrees or 2 pi radians). + One can therefore use an unsigned 8-bit variable and simply + add or subtract, allowing it to overflow/underflow and it + still does the expected contiguous thing. + @return Sine result, 0 to 255, or -128 to +127 if type-converted to + a signed int8_t, but you'll most likely want unsigned as this + output is often used for pixel brightness in animation effects. + */ + static uint8_t sine8(uint8_t x) { + return pgm_read_byte(&_NeoPixelSineTable[x]); // 0-255 in, 0-255 out + } + /*! + @brief An 8-bit gamma-correction function for basic pixel brightness + adjustment. Makes color transitions appear more perceptially + correct. + @param x Input brightness, 0 (minimum or off/black) to 255 (maximum). + @return Gamma-adjusted brightness, can then be passed to one of the + setPixelColor() functions. This uses a fixed gamma correction + exponent of 2.6, which seems reasonably okay for average + NeoPixels in average tasks. If you need finer control you'll + need to provide your own gamma-correction function instead. + */ + static uint8_t gamma8(uint8_t x) { + return pgm_read_byte(&_NeoPixelGammaTable[x]); // 0-255 in, 0-255 out + } + /*! + @brief Convert separate red, green and blue values into a single + "packed" 32-bit RGB color. + @param r Red brightness, 0 to 255. + @param g Green brightness, 0 to 255. + @param b Blue brightness, 0 to 255. + @return 32-bit packed RGB value, which can then be assigned to a + variable for later use or passed to the setPixelColor() + function. Packed RGB format is predictable, regardless of + LED strand color order. + */ + static uint32_t Color(uint8_t r, uint8_t g, uint8_t b) { + return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; + } + /*! + @brief Convert separate red, green, blue and white values into a + single "packed" 32-bit WRGB color. + @param r Red brightness, 0 to 255. + @param g Green brightness, 0 to 255. + @param b Blue brightness, 0 to 255. + @param w White brightness, 0 to 255. + @return 32-bit packed WRGB value, which can then be assigned to a + variable for later use or passed to the setPixelColor() + function. Packed WRGB format is predictable, regardless of + LED strand color order. + */ + static uint32_t Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w) { + return ((uint32_t)w << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; + } + static uint32_t ColorHSV(uint16_t hue, uint8_t sat=255, uint8_t val=255); + /*! + @brief A gamma-correction function for 32-bit packed RGB or WRGB + colors. Makes color transitions appear more perceptially + correct. + @param x 32-bit packed RGB or WRGB color. + @return Gamma-adjusted packed color, can then be passed in one of the + setPixelColor() functions. Like gamma8(), this uses a fixed + gamma correction exponent of 2.6, which seems reasonably okay + for average NeoPixels in average tasks. If you need finer + control you'll need to provide your own gamma-correction + function instead. + */ + static uint32_t gamma32(uint32_t x); - private: + protected: - boolean #ifdef NEO_KHZ400 // If 400 KHz NeoPixel support enabled... - is800KHz, // ...true if 800 KHz pixels + bool is800KHz; ///< true if 800 KHz pixels #endif - begun; // true if begin() previously called - uint16_t - numLEDs, // Number of RGB LEDs in strip - numBytes; // Size of 'pixels' buffer below (3 or 4 bytes/pixel) - int8_t - pin; // Output pin number (-1 if not yet set) - uint8_t - brightness, - *pixels, // Holds LED color values (3 or 4 bytes each) - rOffset, // Index of red byte within each 3- or 4-byte pixel - gOffset, // Index of green byte - bOffset, // Index of blue byte - wOffset; // Index of white byte (same as rOffset if no white) - uint32_t - endTime; // Latch timing reference + bool begun; ///< true if begin() previously called + uint16_t numLEDs; ///< Number of RGB LEDs in strip + uint16_t numBytes; ///< Size of 'pixels' buffer below + int16_t pin; ///< Output pin number (-1 if not yet set) + uint8_t brightness; ///< Strip brightness 0-255 (stored as +1) + uint8_t *pixels; ///< Holds LED color values (3 or 4 bytes each) + uint8_t rOffset; ///< Red index within each 3- or 4-byte pixel + uint8_t gOffset; ///< Index of green byte + uint8_t bOffset; ///< Index of blue byte + uint8_t wOffset; ///< Index of white (==rOffset if no white) + uint32_t endTime; ///< Latch timing reference #ifdef __AVR__ - volatile uint8_t - *port; // Output PORT register - uint8_t - pinMask; // Output PORT bitmask + volatile uint8_t *port; ///< Output PORT register + uint8_t pinMask; ///< Output PORT bitmask +#endif +#if defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32) + GPIO_TypeDef *gpioPort; ///< Output GPIO PORT + uint32_t gpioPin; ///< Output GPIO PIN #endif - }; #endif // ADAFRUIT_NEOPIXEL_H diff --git a/lib/Adafruit_NeoPixel/CONTRIBUTING.md b/lib/Adafruit_NeoPixel/CONTRIBUTING.md new file mode 100644 index 000000000..aa753894e --- /dev/null +++ b/lib/Adafruit_NeoPixel/CONTRIBUTING.md @@ -0,0 +1,13 @@ +# Contribution Guidelines + +This library is the culmination of the expertise of many members of the open source community who have dedicated their time and hard work. The best way to ask for help or propose a new idea is to [create a new issue](https://github.com/adafruit/Adafruit_NeoPixel/issues/new) while creating a Pull Request with your code changes allows you to share your own innovations with the rest of the community. + +The following are some guidelines to observe when creating issues or PRs: + +- Be friendly; it is important that we can all enjoy a safe space as we are all working on the same project and it is okay for people to have different ideas + +- [Use code blocks](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code); it helps us help you when we can read your code! On that note also refrain from pasting more than 30 lines of code in a post, instead [create a gist](https://gist.github.com/) if you need to share large snippets + +- Use reasonable titles; refrain from using overly long or capitalized titles as they are usually annoying and do little to encourage others to help :smile: + +- Be detailed; refrain from mentioning code problems without sharing your source code and always give information regarding your board and version of the library diff --git a/lib/Adafruit_NeoPixel/README.md b/lib/Adafruit_NeoPixel/README.md index 7aaaa206a..8c150501f 100644 --- a/lib/Adafruit_NeoPixel/README.md +++ b/lib/Adafruit_NeoPixel/README.md @@ -1,11 +1,153 @@ -# Adafruit NeoPixel Library [![Build Status](https://travis-ci.org/adafruit/Adafruit_NeoPixel.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_NeoPixel) +# Adafruit NeoPixel Library [![Build Status](https://github.com/adafruit/Adafruit_NeoPixel/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_NeoPixel/actions)[![Documentation](https://github.com/adafruit/ci-arduino/blob/master/assets/doxygen_badge.svg)](http://adafruit.github.io/Adafruit_NeoPixel/html/index.html) Arduino library for controlling single-wire-based LED pixels and strip such as the [Adafruit 60 LED/meter Digital LED strip][strip], the [Adafruit FLORA RGB Smart Pixel][flora], the [Adafruit Breadboard-friendly RGB Smart Pixel][pixel], the [Adafruit NeoPixel Stick][stick], and the [Adafruit NeoPixel Shield][shield]. After downloading, rename folder to 'Adafruit_NeoPixel' and install in Arduino Libraries folder. Restart Arduino IDE, then open File->Sketchbook->Library->Adafruit_NeoPixel->strandtest sketch. +Compatibility notes: Port A is not supported on any AVR processors at this time + [flora]: http://adafruit.com/products/1060 [strip]: http://adafruit.com/products/1138 [pixel]: http://adafruit.com/products/1312 [stick]: http://adafruit.com/products/1426 [shield]: http://adafruit.com/products/1430 + +--- + +## Installation + +### First Method + +![image](https://user-images.githubusercontent.com/36513474/68967967-3e37f480-0803-11ea-91d9-601848c306ee.png) + +1. In the Arduino IDE, navigate to Sketch > Include Library > Manage Libraries +1. Then the Library Manager will open and you will find a list of libraries that are already installed or ready for installation. +1. Then search for Neopixel strip using the search bar. +1. Click on the text area and then select the specific version and install it. + +### Second Method + +1. Navigate to the [Releases page](https://github.com/adafruit/Adafruit_NeoPixel/releases). +1. Download the latest release. +1. Extract the zip file +1. In the Arduino IDE, navigate to Sketch > Include Library > Add .ZIP Library + +## Features + +- ### Simple to use + + Controlling NeoPixels “from scratch” is quite a challenge, so we provide a library letting you focus on the fun and interesting bits. + +- ### Give back + + The library is free; you don’t have to pay for anything. Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! + +- ### Supported Chipsets + + We have included code for the following chips - sometimes these break for exciting reasons that we can't control in which case please open an issue! + + - AVR ATmega and ATtiny (any 8-bit) - 8 MHz, 12 MHz and 16 MHz + - Teensy 3.x and LC + - Arduino Due + - Arduino 101 + - ATSAMD21 (Arduino Zero/M0 and other SAMD21 boards) @ 48 MHz + - ATSAMD51 @ 120 MHz + - Adafruit STM32 Feather @ 120 MHz + - ESP8266 any speed + - ESP32 any speed + - Nordic nRF52 (Adafruit Feather nRF52), nRF51 (micro:bit) + + Check forks for other architectures not listed here! + +- ### GNU Lesser General Public License + + Adafruit_NeoPixel is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + +## Functions + +- begin() +- updateLength() +- updateType() +- show() +- delay_ns() +- setPin() +- setPixelColor() +- fill() +- ColorHSV() +- getPixelColor() +- setBrightness() +- getBrightness() +- clear() +- gamma32() + +## Examples + +There are many examples implemented in this library. One of the examples is below. You can find other examples [here](https://github.com/adafruit/Adafruit_NeoPixel/tree/master/examples) + +### Simple + +```Cpp +#include +#ifdef __AVR__ + #include +#endif +#define PIN 6 +#define NUMPIXELS 16 + +Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); +#define DELAYVAL 500 + +void setup() { +#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000) + clock_prescale_set(clock_div_1); +#endif + + pixels.begin(); +} + +void loop() { + pixels.clear(); + + for(int i=0; i +#include "driver/rmt.h" + +#if defined(ESP_IDF_VERSION) +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) +#define HAS_ESP_IDF_4 +#endif +#endif + +// This code is adapted from the ESP-IDF v3.4 RMT "led_strip" example, altered +// to work with the Arduino version of the ESP-IDF (3.2) + +#define WS2812_T0H_NS (400) +#define WS2812_T0L_NS (850) +#define WS2812_T1H_NS (800) +#define WS2812_T1L_NS (450) + +#define WS2811_T0H_NS (500) +#define WS2811_T0L_NS (2000) +#define WS2811_T1H_NS (1200) +#define WS2811_T1L_NS (1300) + +static uint32_t t0h_ticks = 0; +static uint32_t t1h_ticks = 0; +static uint32_t t0l_ticks = 0; +static uint32_t t1l_ticks = 0; + +// Limit the number of RMT channels available for the Neopixels. Defaults to all +// channels (8 on ESP32, 4 on ESP32-S2 and S3). Redefining this value will free +// any channels with a higher number for other uses, such as IR send-and-recieve +// libraries. Redefine as 1 to restrict Neopixels to only a single channel. +#define ADAFRUIT_RMT_CHANNEL_MAX RMT_CHANNEL_MAX + +#define RMT_LL_HW_BASE (&RMT) + +bool rmt_reserved_channels[ADAFRUIT_RMT_CHANNEL_MAX]; + +static void IRAM_ATTR ws2812_rmt_adapter(const void *src, rmt_item32_t *dest, size_t src_size, + size_t wanted_num, size_t *translated_size, size_t *item_num) +{ + if (src == NULL || dest == NULL) { + *translated_size = 0; + *item_num = 0; + return; + } + const rmt_item32_t bit0 = {{{ t0h_ticks, 1, t0l_ticks, 0 }}}; //Logical 0 + const rmt_item32_t bit1 = {{{ t1h_ticks, 1, t1l_ticks, 0 }}}; //Logical 1 + size_t size = 0; + size_t num = 0; + uint8_t *psrc = (uint8_t *)src; + rmt_item32_t *pdest = dest; + while (size < src_size && num < wanted_num) { + for (int i = 0; i < 8; i++) { + // MSB first + if (*psrc & (1 << (7 - i))) { + pdest->val = bit1.val; + } else { + pdest->val = bit0.val; + } + num++; + pdest++; + } + size++; + psrc++; + } + *translated_size = size; + *item_num = num; +} + +void espShow(uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) { + // Reserve channel + rmt_channel_t channel = ADAFRUIT_RMT_CHANNEL_MAX; + for (size_t i = 0; i < ADAFRUIT_RMT_CHANNEL_MAX; i++) { + if (!rmt_reserved_channels[i]) { + rmt_reserved_channels[i] = true; + channel = i; + break; + } + } + if (channel == ADAFRUIT_RMT_CHANNEL_MAX) { + // Ran out of channels! + return; + } + +#if defined(HAS_ESP_IDF_4) + rmt_config_t config = RMT_DEFAULT_CONFIG_TX(pin, channel); + config.clk_div = 2; +#else + // Match default TX config from ESP-IDF version 3.4 + rmt_config_t config = { + .rmt_mode = RMT_MODE_TX, + .channel = channel, + .gpio_num = pin, + .clk_div = 2, + .mem_block_num = 1, + .tx_config = { + .carrier_freq_hz = 38000, + .carrier_level = RMT_CARRIER_LEVEL_HIGH, + .idle_level = RMT_IDLE_LEVEL_LOW, + .carrier_duty_percent = 33, + .carrier_en = false, + .loop_en = false, + .idle_output_en = true, + } + }; +#endif + rmt_config(&config); + rmt_driver_install(config.channel, 0, 0); + + // Convert NS timings to ticks + uint32_t counter_clk_hz = 0; + +#if defined(HAS_ESP_IDF_4) + rmt_get_counter_clock(channel, &counter_clk_hz); +#else + // this emulates the rmt_get_counter_clock() function from ESP-IDF 3.4 + if (RMT_LL_HW_BASE->conf_ch[config.channel].conf1.ref_always_on == RMT_BASECLK_REF) { + uint32_t div_cnt = RMT_LL_HW_BASE->conf_ch[config.channel].conf0.div_cnt; + uint32_t div = div_cnt == 0 ? 256 : div_cnt; + counter_clk_hz = REF_CLK_FREQ / (div); + } else { + uint32_t div_cnt = RMT_LL_HW_BASE->conf_ch[config.channel].conf0.div_cnt; + uint32_t div = div_cnt == 0 ? 256 : div_cnt; + counter_clk_hz = APB_CLK_FREQ / (div); + } +#endif + + // NS to tick converter + float ratio = (float)counter_clk_hz / 1e9; + + if (is800KHz) { + t0h_ticks = (uint32_t)(ratio * WS2812_T0H_NS); + t0l_ticks = (uint32_t)(ratio * WS2812_T0L_NS); + t1h_ticks = (uint32_t)(ratio * WS2812_T1H_NS); + t1l_ticks = (uint32_t)(ratio * WS2812_T1L_NS); + } else { + t0h_ticks = (uint32_t)(ratio * WS2811_T0H_NS); + t0l_ticks = (uint32_t)(ratio * WS2811_T0L_NS); + t1h_ticks = (uint32_t)(ratio * WS2811_T1H_NS); + t1l_ticks = (uint32_t)(ratio * WS2811_T1L_NS); + } + + // Initialize automatic timing translator + rmt_translator_init(config.channel, ws2812_rmt_adapter); + + // Write and wait to finish + rmt_write_sample(config.channel, pixels, (size_t)numBytes, true); + rmt_wait_tx_done(config.channel, pdMS_TO_TICKS(100)); + + // Free channel again + rmt_driver_uninstall(config.channel); + rmt_reserved_channels[channel] = false; + + gpio_set_direction(pin, GPIO_MODE_OUTPUT); +} + +#endif diff --git a/lib/Adafruit_NeoPixel/esp8266.c b/lib/Adafruit_NeoPixel/esp8266.c index 9b7602b92..dfdf5775c 100644 --- a/lib/Adafruit_NeoPixel/esp8266.c +++ b/lib/Adafruit_NeoPixel/esp8266.c @@ -2,10 +2,12 @@ // ESP8266 work for the NeoPixelBus library: github.com/Makuna/NeoPixelBus // Needs to be a separate .c file to enforce IRAM_ATTR execution. -#ifdef ESP8266 +#if defined(ESP8266) #include +#ifdef ESP8266 #include +#endif static uint32_t _getCycleCount(void) __attribute__((always_inline)); static inline uint32_t _getCycleCount(void) { @@ -14,25 +16,29 @@ static inline uint32_t _getCycleCount(void) { return ccount; } - #ifndef CORE_POST_3_0_0 - #define IRAM_ATTR ICACHE_RAM_ATTR - #endif - - -void IRAM_ATTR espShow( +#ifdef ESP8266 +IRAM_ATTR void espShow( + uint8_t pin, uint8_t *pixels, uint32_t numBytes, __attribute__((unused)) boolean is800KHz) { +#else +void espShow( uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) { +#endif -#define CYCLES_800_T0H (F_CPU / 2500000) // 0.4us -#define CYCLES_800_T1H (F_CPU / 1250000) // 0.8us -#define CYCLES_800 (F_CPU / 800000) // 1.25us per bit +#define CYCLES_800_T0H (F_CPU / 2500001) // 0.4us +#define CYCLES_800_T1H (F_CPU / 1250001) // 0.8us +#define CYCLES_800 (F_CPU / 800001) // 1.25us per bit #define CYCLES_400_T0H (F_CPU / 2000000) // 0.5uS #define CYCLES_400_T1H (F_CPU / 833333) // 1.2us #define CYCLES_400 (F_CPU / 400000) // 2.5us per bit uint8_t *p, *end, pix, mask; - uint32_t t, time0, time1, period, c, startTime, pinMask; + uint32_t t, time0, time1, period, c, startTime; +#ifdef ESP8266 + uint32_t pinMask; pinMask = _BV(pin); +#endif + p = pixels; end = p + numBytes; pix = *p++; @@ -56,10 +62,18 @@ void IRAM_ATTR espShow( for(t = time0;; t = time0) { if(pix & mask) t = time1; // Bit high duration while(((c = _getCycleCount()) - startTime) < period); // Wait for bit start +#ifdef ESP8266 GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinMask); // Set high +#else + gpio_set_level(pin, HIGH); +#endif startTime = c; // Save start time while(((c = _getCycleCount()) - startTime) < t); // Wait high duration +#ifdef ESP8266 GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask); // Set low +#else + gpio_set_level(pin, LOW); +#endif if(!(mask >>= 1)) { // Next bit/byte if(p >= end) break; pix = *p++; diff --git a/lib/Adafruit_NeoPixel/examples/RGBWstrandtest/.trinket.test.skip b/lib/Adafruit_NeoPixel/examples/RGBWstrandtest/.trinket.test.skip new file mode 100644 index 000000000..e69de29bb diff --git a/lib/Adafruit_NeoPixel/examples/RGBWstrandtest/RGBWstrandtest.ino b/lib/Adafruit_NeoPixel/examples/RGBWstrandtest/RGBWstrandtest.ino index ad54c1d5e..95335cdfc 100644 --- a/lib/Adafruit_NeoPixel/examples/RGBWstrandtest/RGBWstrandtest.ino +++ b/lib/Adafruit_NeoPixel/examples/RGBWstrandtest/RGBWstrandtest.ino @@ -1,263 +1,177 @@ +// NeoPixel test program showing use of the WHITE channel for RGBW +// pixels only (won't look correct on regular RGB NeoPixel strips). + #include #ifdef __AVR__ - #include + #include // Required for 16 MHz Adafruit Trinket #endif -#define PIN 6 +// Which pin on the Arduino is connected to the NeoPixels? +// On a Trinket or Gemma we suggest changing this to 1: +#define LED_PIN 6 -#define NUM_LEDS 60 +// How many NeoPixels are attached to the Arduino? +#define LED_COUNT 60 -#define BRIGHTNESS 50 - -Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRBW + NEO_KHZ800); - -int gamma[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, - 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, - 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, - 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, - 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25, - 25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36, - 37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50, - 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, - 69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89, - 90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114, - 115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142, - 144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175, - 177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213, - 215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 }; +// NeoPixel brightness, 0 (min) to 255 (max) +#define BRIGHTNESS 50 // Set BRIGHTNESS to about 1/5 (max = 255) +// Declare our NeoPixel strip object: +Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRBW + NEO_KHZ800); +// Argument 1 = Number of pixels in NeoPixel strip +// Argument 2 = Arduino pin number (most are valid) +// Argument 3 = Pixel type flags, add together as needed: +// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) +// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) +// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) +// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) +// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products) void setup() { - Serial.begin(115200); - // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket - #if defined (__AVR_ATtiny85__) - if (F_CPU == 16000000) clock_prescale_set(clock_div_1); - #endif - // End of trinket special code + // These lines are specifically to support the Adafruit Trinket 5V 16 MHz. + // Any other board, you can remove this part (but no harm leaving it): +#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000) + clock_prescale_set(clock_div_1); +#endif + // END of Trinket-specific code. + + strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) + strip.show(); // Turn OFF all pixels ASAP strip.setBrightness(BRIGHTNESS); - strip.begin(); - strip.show(); // Initialize all pixels to 'off' } void loop() { - // Some example procedures showing how to display to the pixels: - colorWipe(strip.Color(255, 0, 0), 50); // Red - colorWipe(strip.Color(0, 255, 0), 50); // Green - colorWipe(strip.Color(0, 0, 255), 50); // Blue - colorWipe(strip.Color(0, 0, 0, 255), 50); // White + // Fill along the length of the strip in various colors... + colorWipe(strip.Color(255, 0, 0) , 50); // Red + colorWipe(strip.Color( 0, 255, 0) , 50); // Green + colorWipe(strip.Color( 0, 0, 255) , 50); // Blue + colorWipe(strip.Color( 0, 0, 0, 255), 50); // True white (not RGB white) - whiteOverRainbow(20,75,5); - - pulseWhite(5); - - // fullWhite(); - // delay(2000); - - rainbowFade2White(3,3,1); + whiteOverRainbow(75, 5); + pulseWhite(5); + rainbowFade2White(3, 3, 1); } -// Fill the dots one after the other with a color -void colorWipe(uint32_t c, uint8_t wait) { - for(uint16_t i=0; i= strip.numPixels()) whiteLength = strip.numPixels() - 1; + + int head = whiteLength - 1; + int tail = 0; + int loops = 3; + int loopNum = 0; + uint32_t lastTime = millis(); + uint32_t firstPixelHue = 0; + + for(;;) { // Repeat forever (or until a 'break' or 'return') + for(int i=0; i= tail) && (i <= head)) || // If between head & tail... + ((tail > head) && ((i >= tail) || (i <= head)))) { + strip.setPixelColor(i, strip.Color(0, 0, 0, 255)); // Set white + } else { // else set rainbow + int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels()); + strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue))); + } + } + + strip.show(); // Update strip with new contents + // There's no delay here, it just runs full-tilt until the timer and + // counter combination below runs out. + + firstPixelHue += 40; // Advance just a little along the color wheel + + if((millis() - lastTime) > whiteSpeed) { // Time to update head/tail? + if(++head >= strip.numPixels()) { // Advance head, wrap around + head = 0; + if(++loopNum >= loops) return; + } + if(++tail >= strip.numPixels()) { // Advance tail, wrap around + tail = 0; + } + lastTime = millis(); // Save time of last movement + } } } void pulseWhite(uint8_t wait) { - for(int j = 0; j < 256 ; j++){ - for(uint16_t i=0; i= 0 ; j--){ - for(uint16_t i=0; i 255 - fadeMax ){ - fadeVal--; - } - - strip.show(); - delay(wait); - } - + for(int j=0; j<256; j++) { // Ramp up from 0 to 255 + // Fill entire strip with white at gamma-corrected brightness level 'j': + strip.fill(strip.Color(0, 0, 0, strip.gamma8(j))); + strip.show(); + delay(wait); } - - - delay(500); - - - for(int k = 0 ; k < whiteLoops ; k ++){ - - for(int j = 0; j < 256 ; j++){ - - for(uint16_t i=0; i < strip.numPixels(); i++) { - strip.setPixelColor(i, strip.Color(0,0,0, gamma[j] ) ); - } - strip.show(); - } - - delay(2000); - for(int j = 255; j >= 0 ; j--){ - - for(uint16_t i=0; i < strip.numPixels(); i++) { - strip.setPixelColor(i, strip.Color(0,0,0, gamma[j] ) ); - } - strip.show(); - } + for(int j=255; j>=0; j--) { // Ramp down from 255 to 0 + strip.fill(strip.Color(0, 0, 0, strip.gamma8(j))); + strip.show(); + delay(wait); } - - delay(500); - - } -void whiteOverRainbow(uint8_t wait, uint8_t whiteSpeed, uint8_t whiteLength ) { - - if(whiteLength >= strip.numPixels()) whiteLength = strip.numPixels() - 1; +void rainbowFade2White(int wait, int rainbowLoops, int whiteLoops) { + int fadeVal=0, fadeMax=100; - int head = whiteLength - 1; - int tail = 0; + // Hue of first pixel runs 'rainbowLoops' complete loops through the color + // wheel. Color wheel has a range of 65536 but it's OK if we roll over, so + // just count from 0 to rainbowLoops*65536, using steps of 256 so we + // advance around the wheel at a decent clip. + for(uint32_t firstPixelHue = 0; firstPixelHue < rainbowLoops*65536; + firstPixelHue += 256) { - int loops = 3; - int loopNum = 0; + for(int i=0; i= tail && i <= head) || (tail > head && i >= tail) || (tail > head && i <= head) ){ - strip.setPixelColor(i, strip.Color(0,0,0, 255 ) ); - } - else{ - strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255)); - } - - } + strip.show(); + delay(wait); - if(millis() - lastTime > whiteSpeed) { - head++; - tail++; - if(head == strip.numPixels()){ - loopNum++; - } - lastTime = millis(); - } - - if(loopNum == loops) return; - - head%=strip.numPixels(); - tail%=strip.numPixels(); - strip.show(); - delay(wait); + if(firstPixelHue < 65536) { // First loop, + if(fadeVal < fadeMax) fadeVal++; // fade in + } else if(firstPixelHue >= ((rainbowLoops-1) * 65536)) { // Last loop, + if(fadeVal > 0) fadeVal--; // fade out + } else { + fadeVal = fadeMax; // Interim loop, make sure fade is at max } } - -} -void fullWhite() { - - for(uint16_t i=0; i=0; j--) { // Ramp down 255 to 0 + strip.fill(strip.Color(0, 0, 0, strip.gamma8(j))); + strip.show(); } - strip.show(); - delay(wait); } -} -// Input a value 0 to 255 to get a color value. -// The colours are a transition r - g - b - back to r. -uint32_t Wheel(byte WheelPos) { - WheelPos = 255 - WheelPos; - if(WheelPos < 85) { - return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3,0); - } - if(WheelPos < 170) { - WheelPos -= 85; - return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3,0); - } - WheelPos -= 170; - return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0,0); + delay(500); // Pause 1/2 second } - -uint8_t red(uint32_t c) { - return (c >> 8); -} -uint8_t green(uint32_t c) { - return (c >> 16); -} -uint8_t blue(uint32_t c) { - return (c); -} - - diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLE/.arduinoble.test.only b/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLE/.arduinoble.test.only new file mode 100644 index 000000000..e69de29bb diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLE/.test.skip b/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLE/.test.skip new file mode 100644 index 000000000..e69de29bb diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLE/StrandtestArduinoBLE.ino b/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLE/StrandtestArduinoBLE.ino new file mode 100644 index 000000000..80e02d21b --- /dev/null +++ b/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLE/StrandtestArduinoBLE.ino @@ -0,0 +1,231 @@ +/**************************************************************************** + * This example is based on StrandtestBLE example and adapts it to use + * the new ArduinoBLE library. + * + * https://github.com/arduino-libraries/ArduinoBLE + * + * Supported boards: + * Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT, + Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board. + * + * You can use a generic BLE central app, like LightBlue (iOS and Android) or + * nRF Connect (Android), to interact with the services and characteristics + * created in this sketch. + * + * This example code is in the public domain. + * + */ +#include + +#define PIN 15 // Pin where NeoPixels are connected + +// Declare our NeoPixel strip object: +Adafruit_NeoPixel strip(64, PIN, NEO_GRB + NEO_KHZ800); +// Argument 1 = Number of pixels in NeoPixel strip +// Argument 2 = Arduino pin number (most are valid) +// Argument 3 = Pixel type flags, add together as needed: +// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) +// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) +// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) +// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) +// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products) + +// NEOPIXEL BEST PRACTICES for most reliable operation: +// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections. +// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel. +// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR. +// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS +// connect GROUND (-) first, then +, then data. +// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip, +// a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED. +// (Skipping these may work OK on your workbench but can fail in the field) + +uint8_t rgb_values[3]; + +#include + +BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // BLE LED Service + +// BLE LED Switch Characteristic - custom 128-bit UUID, read and writable by central +BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite); + +void setup() +{ + Serial.begin(115200); + Serial.println("Hello World!"); + + // custom services and characteristics can be added as well + // begin initialization + if (!BLE.begin()) + { + Serial.println("starting BLE failed!"); + + while (1) + ; + } + + Serial.print("Peripheral address: "); + Serial.println(BLE.address()); + + // set advertised local name and service UUID: + BLE.setLocalName("LED"); + BLE.setAdvertisedService(ledService); + + // add the characteristic to the service + ledService.addCharacteristic(switchCharacteristic); + + // add service + BLE.addService(ledService); + + // set the initial value for the characeristic: + switchCharacteristic.writeValue(0); + + // start advertising + BLE.advertise(); + + strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) + strip.show(); // Turn OFF all pixels ASAP + + pinMode(PIN, OUTPUT); + digitalWrite(PIN, LOW); + +} + +void loop() +{ + BLEDevice central = BLE.central(); + + // if a central is connected to peripheral: + if (central) + { + Serial.print("Connected to central: "); + // print the central's MAC address: + Serial.println(central.address()); + + // while the central is still connected to peripheral: + while (central.connected()) + { + // if the remote device wrote to the characteristic, + // use the value to control the LED: + if (switchCharacteristic.written()) + { + switch (switchCharacteristic.value()) + { + case 'a': + colorWipe(strip.Color(255, 0, 0), 20); // Red + break; + case 'b': + colorWipe(strip.Color(0, 255, 0), 20); // Green + break; + case 'c': + colorWipe(strip.Color(0, 0, 255), 20); // Blue + break; + case 'd': + theaterChase(strip.Color(255, 0, 0), 20); // Red + break; + case 'e': + theaterChase(strip.Color(0, 255, 0), 20); // Green + break; + case 'f': + theaterChase(strip.Color(255, 0, 255), 20); // Cyan + break; + case 'g': + rainbow(10); + break; + case 'h': + theaterChaseRainbow(20); + break; + } + } + } + } +} + +// Fill strip pixels one after another with a color. Strip is NOT cleared +// first; anything there will be covered pixel by pixel. Pass in color +// (as a single 'packed' 32-bit value, which you can get by calling +// strip.Color(red, green, blue) as shown in the loop() function above), +// and a delay time (in milliseconds) between pixels. +void colorWipe(uint32_t color, int wait) +{ + for (int i = 0; i < strip.numPixels(); i++) + { // For each pixel in strip... + strip.setPixelColor(i, color); // Set pixel's color (in RAM) + strip.show(); // Update strip to match + delay(wait); // Pause for a moment + } +} + +// Theater-marquee-style chasing lights. Pass in a color (32-bit value, +// a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms) +// between frames. +void theaterChase(uint32_t color, int wait) +{ + for (int a = 0; a < 10; a++) + { // Repeat 10 times... + for (int b = 0; b < 3; b++) + { // 'b' counts from 0 to 2... + strip.clear(); // Set all pixels in RAM to 0 (off) + // 'c' counts up from 'b' to end of strip in steps of 3... + for (int c = b; c < strip.numPixels(); c += 3) + { + strip.setPixelColor(c, color); // Set pixel 'c' to value 'color' + } + strip.show(); // Update strip with new contents + delay(wait); // Pause for a moment + } + } +} + +// Rainbow cycle along whole strip. Pass delay time (in ms) between frames. +void rainbow(int wait) +{ + // Hue of first pixel runs 5 complete loops through the color wheel. + // Color wheel has a range of 65536 but it's OK if we roll over, so + // just count from 0 to 5*65536. Adding 256 to firstPixelHue each time + // means we'll make 5*65536/256 = 1280 passes through this outer loop: + for (long firstPixelHue = 0; firstPixelHue < 5 * 65536; firstPixelHue += 256) + { + for (int i = 0; i < strip.numPixels(); i++) + { // For each pixel in strip... + // Offset pixel hue by an amount to make one full revolution of the + // color wheel (range of 65536) along the length of the strip + // (strip.numPixels() steps): + int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels()); + // strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or + // optionally add saturation and value (brightness) (each 0 to 255). + // Here we're using just the single-argument hue variant. The result + // is passed through strip.gamma32() to provide 'truer' colors + // before assigning to each pixel: + strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue))); + } + strip.show(); // Update strip with new contents + delay(wait); // Pause for a moment + } +} + +// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames. +void theaterChaseRainbow(int wait) +{ + int firstPixelHue = 0; // First pixel starts at red (hue 0) + for (int a = 0; a < 30; a++) + { // Repeat 30 times... + for (int b = 0; b < 3; b++) + { // 'b' counts from 0 to 2... + strip.clear(); // Set all pixels in RAM to 0 (off) + // 'c' counts up from 'b' to end of strip in increments of 3... + for (int c = b; c < strip.numPixels(); c += 3) + { + // hue of pixel 'c' is offset by an amount to make one full + // revolution of the color wheel (range 65536) along the length + // of the strip (strip.numPixels() steps): + int hue = firstPixelHue + c * 65536L / strip.numPixels(); + uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB + strip.setPixelColor(c, color); // Set pixel 'c' to value 'color' + } + strip.show(); // Update strip with new contents + delay(wait); // Pause for a moment + firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames + } + } +} diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLECallback/.arduinoble.test.only b/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLECallback/.arduinoble.test.only new file mode 100644 index 000000000..e69de29bb diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLECallback/.test.skip b/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLECallback/.test.skip new file mode 100644 index 000000000..e69de29bb diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLECallback/StrandtestArduinoBLECallback.ino b/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLECallback/StrandtestArduinoBLECallback.ino new file mode 100644 index 000000000..b986943ae --- /dev/null +++ b/lib/Adafruit_NeoPixel/examples/StrandtestArduinoBLECallback/StrandtestArduinoBLECallback.ino @@ -0,0 +1,239 @@ +/**************************************************************************** + * This example is based on StrandtestArduinoBLE example to make use of + * callbacks features of the ArduinoBLE library. + * + * https://github.com/arduino-libraries/ArduinoBLE + * + * Supported boards: + * Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT, + Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board. + * + * You can use a generic BLE central app, like LightBlue (iOS and Android) or + * nRF Connect (Android), to interact with the services and characteristics + * created in this sketch. + * + * This example code is in the public domain. + * + */ +#include + +#define PIN 15 // Pin where NeoPixels are connected + +// Declare our NeoPixel strip object: +Adafruit_NeoPixel strip(64, PIN, NEO_GRB + NEO_KHZ800); +// Argument 1 = Number of pixels in NeoPixel strip +// Argument 2 = Arduino pin number (most are valid) +// Argument 3 = Pixel type flags, add together as needed: +// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) +// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) +// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) +// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) +// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products) + +// NEOPIXEL BEST PRACTICES for most reliable operation: +// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections. +// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel. +// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR. +// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS +// connect GROUND (-) first, then +, then data. +// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip, +// a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED. +// (Skipping these may work OK on your workbench but can fail in the field) + +uint8_t rgb_values[3]; + +#include + +BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // BLE LED Service + +// BLE LED Switch Characteristic - custom 128-bit UUID, read and writable by central +BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite); + +void setup() +{ + Serial.begin(115200); + Serial.println("Hello World!"); + + // custom services and characteristics can be added as well + // begin initialization + if (!BLE.begin()) + { + Serial.println("starting BLE failed!"); + + while (1) + ; + } + + Serial.print("Peripheral address: "); + Serial.println(BLE.address()); + + // set advertised local name and service UUID: + BLE.setLocalName("LEDCallback"); + BLE.setAdvertisedService(ledService); + + // add the characteristic to the service + ledService.addCharacteristic(switchCharacteristic); + + // add service + BLE.addService(ledService); + // assign event handlers for connected, disconnected to peripheral + BLE.setEventHandler(BLEConnected, blePeripheralConnectHandler); + BLE.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler); + + // assign event handlers for characteristic + switchCharacteristic.setEventHandler(BLEWritten, switchCharacteristicWritten); + // set the initial value for the characeristic: + switchCharacteristic.writeValue(0); + + // start advertising + BLE.advertise(); + + strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) + strip.show(); // Turn OFF all pixels ASAP + + pinMode(PIN, OUTPUT); + digitalWrite(PIN, LOW); +} + +void loop() +{ + // poll for BLE events + BLE.poll(); +} + +void blePeripheralConnectHandler(BLEDevice central) +{ + // central connected event handler + Serial.print("Connected event, central: "); + Serial.println(central.address()); +} + +void blePeripheralDisconnectHandler(BLEDevice central) +{ + // central disconnected event handler + Serial.print("Disconnected event, central: "); + Serial.println(central.address()); +} + +void switchCharacteristicWritten(BLEDevice central, BLECharacteristic characteristic) +{ + // central wrote new value to characteristic, update LED + Serial.print("Characteristic event, written: "); + + switch (switchCharacteristic.value()) + { + case 'a': + colorWipe(strip.Color(255, 0, 0), 20); // Red + break; + case 'b': + colorWipe(strip.Color(0, 255, 0), 20); // Green + break; + case 'c': + colorWipe(strip.Color(0, 0, 255), 20); // Blue + break; + case 'd': + theaterChase(strip.Color(255, 0, 0), 20); // Red + break; + case 'e': + theaterChase(strip.Color(0, 255, 0), 20); // Green + break; + case 'f': + theaterChase(strip.Color(255, 0, 255), 20); // Cyan + break; + case 'g': + rainbow(10); + break; + case 'h': + theaterChaseRainbow(20); + break; + } +} + +// Fill strip pixels one after another with a color. Strip is NOT cleared +// first; anything there will be covered pixel by pixel. Pass in color +// (as a single 'packed' 32-bit value, which you can get by calling +// strip.Color(red, green, blue) as shown in the loop() function above), +// and a delay time (in milliseconds) between pixels. +void colorWipe(uint32_t color, int wait) +{ + for (int i = 0; i < strip.numPixels(); i++) + { // For each pixel in strip... + strip.setPixelColor(i, color); // Set pixel's color (in RAM) + strip.show(); // Update strip to match + delay(wait); // Pause for a moment + } +} + +// Theater-marquee-style chasing lights. Pass in a color (32-bit value, +// a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms) +// between frames. +void theaterChase(uint32_t color, int wait) +{ + for (int a = 0; a < 10; a++) + { // Repeat 10 times... + for (int b = 0; b < 3; b++) + { // 'b' counts from 0 to 2... + strip.clear(); // Set all pixels in RAM to 0 (off) + // 'c' counts up from 'b' to end of strip in steps of 3... + for (int c = b; c < strip.numPixels(); c += 3) + { + strip.setPixelColor(c, color); // Set pixel 'c' to value 'color' + } + strip.show(); // Update strip with new contents + delay(wait); // Pause for a moment + } + } +} + +// Rainbow cycle along whole strip. Pass delay time (in ms) between frames. +void rainbow(int wait) +{ + // Hue of first pixel runs 5 complete loops through the color wheel. + // Color wheel has a range of 65536 but it's OK if we roll over, so + // just count from 0 to 5*65536. Adding 256 to firstPixelHue each time + // means we'll make 5*65536/256 = 1280 passes through this outer loop: + for (long firstPixelHue = 0; firstPixelHue < 5 * 65536; firstPixelHue += 256) + { + for (int i = 0; i < strip.numPixels(); i++) + { // For each pixel in strip... + // Offset pixel hue by an amount to make one full revolution of the + // color wheel (range of 65536) along the length of the strip + // (strip.numPixels() steps): + int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels()); + // strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or + // optionally add saturation and value (brightness) (each 0 to 255). + // Here we're using just the single-argument hue variant. The result + // is passed through strip.gamma32() to provide 'truer' colors + // before assigning to each pixel: + strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue))); + } + strip.show(); // Update strip with new contents + delay(wait); // Pause for a moment + } +} + +// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames. +void theaterChaseRainbow(int wait) +{ + int firstPixelHue = 0; // First pixel starts at red (hue 0) + for (int a = 0; a < 30; a++) + { // Repeat 30 times... + for (int b = 0; b < 3; b++) + { // 'b' counts from 0 to 2... + strip.clear(); // Set all pixels in RAM to 0 (off) + // 'c' counts up from 'b' to end of strip in increments of 3... + for (int c = b; c < strip.numPixels(); c += 3) + { + // hue of pixel 'c' is offset by an amount to make one full + // revolution of the color wheel (range 65536) along the length + // of the strip (strip.numPixels() steps): + int hue = firstPixelHue + c * 65536L / strip.numPixels(); + uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB + strip.setPixelColor(c, color); // Set pixel 'c' to value 'color' + } + strip.show(); // Update strip with new contents + delay(wait); // Pause for a moment + firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames + } + } +} diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestBLE/.arduinoble.test.only b/lib/Adafruit_NeoPixel/examples/StrandtestBLE/.arduinoble.test.only new file mode 100644 index 000000000..e69de29bb diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestBLE/.test.skip b/lib/Adafruit_NeoPixel/examples/StrandtestBLE/.test.skip new file mode 100644 index 000000000..e69de29bb diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestBLE/BLESerial.cpp b/lib/Adafruit_NeoPixel/examples/StrandtestBLE/BLESerial.cpp new file mode 100644 index 000000000..d1693dec8 --- /dev/null +++ b/lib/Adafruit_NeoPixel/examples/StrandtestBLE/BLESerial.cpp @@ -0,0 +1,133 @@ +#include "BLESerial.h" + +// #define BLE_SERIAL_DEBUG + +BLESerial* BLESerial::_instance = NULL; + +BLESerial::BLESerial(unsigned char req, unsigned char rdy, unsigned char rst) : + BLEPeripheral(req, rdy, rst) +{ + this->_txCount = 0; + this->_rxHead = this->_rxTail = 0; + this->_flushed = 0; + BLESerial::_instance = this; + + addAttribute(this->_uartService); + addAttribute(this->_uartNameDescriptor); + setAdvertisedServiceUuid(this->_uartService.uuid()); + addAttribute(this->_rxCharacteristic); + addAttribute(this->_rxNameDescriptor); + this->_rxCharacteristic.setEventHandler(BLEWritten, BLESerial::_received); + addAttribute(this->_txCharacteristic); + addAttribute(this->_txNameDescriptor); +} + +void BLESerial::begin(...) { + BLEPeripheral::begin(); + #ifdef BLE_SERIAL_DEBUG + Serial.println(F("BLESerial::begin()")); + #endif +} + +void BLESerial::poll() { + if (millis() < this->_flushed + 100) { + BLEPeripheral::poll(); + } else { + flush(); + } +} + +void BLESerial::end() { + this->_rxCharacteristic.setEventHandler(BLEWritten, NULL); + this->_rxHead = this->_rxTail = 0; + flush(); + BLEPeripheral::disconnect(); +} + +int BLESerial::available(void) { + BLEPeripheral::poll(); + int retval = (this->_rxHead - this->_rxTail + sizeof(this->_rxBuffer)) % sizeof(this->_rxBuffer); + #ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLESerial::available() = ")); + Serial.println(retval); + #endif + return retval; +} + +int BLESerial::peek(void) { + BLEPeripheral::poll(); + if (this->_rxTail == this->_rxHead) return -1; + uint8_t byte = this->_rxBuffer[this->_rxTail]; + #ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLESerial::peek() = ")); + Serial.print((char) byte); + Serial.print(F(" 0x")); + Serial.println(byte, HEX); + #endif + return byte; +} + +int BLESerial::read(void) { + BLEPeripheral::poll(); + if (this->_rxTail == this->_rxHead) return -1; + this->_rxTail = (this->_rxTail + 1) % sizeof(this->_rxBuffer); + uint8_t byte = this->_rxBuffer[this->_rxTail]; + #ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLESerial::read() = ")); + Serial.print((char) byte); + Serial.print(F(" 0x")); + Serial.println(byte, HEX); + #endif + return byte; +} + +void BLESerial::flush(void) { + if (this->_txCount == 0) return; + this->_txCharacteristic.setValue(this->_txBuffer, this->_txCount); + this->_flushed = millis(); + this->_txCount = 0; + BLEPeripheral::poll(); + #ifdef BLE_SERIAL_DEBUG + Serial.println(F("BLESerial::flush()")); + #endif +} + +size_t BLESerial::write(uint8_t byte) { + BLEPeripheral::poll(); + if (this->_txCharacteristic.subscribed() == false) return 0; + this->_txBuffer[this->_txCount++] = byte; + if (this->_txCount == sizeof(this->_txBuffer)) flush(); + #ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLESerial::write(")); + Serial.print((char) byte); + Serial.print(F(" 0x")); + Serial.print(byte, HEX); + Serial.println(F(") = 1")); + #endif + return 1; +} + +BLESerial::operator bool() { + bool retval = BLEPeripheral::connected(); + #ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLESerial::operator bool() = ")); + Serial.println(retval); + #endif + return retval; +} + +void BLESerial::_received(const uint8_t* data, size_t size) { + for (int i = 0; i < size; i++) { + this->_rxHead = (this->_rxHead + 1) % sizeof(this->_rxBuffer); + this->_rxBuffer[this->_rxHead] = data[i]; + } + #ifdef BLE_SERIAL_DEBUG + Serial.print(F("BLESerial::received(")); + for (int i = 0; i < size; i++) Serial.print((char) data[i]); + Serial.println(F(")")); + #endif +} + +void BLESerial::_received(BLECentral& /*central*/, BLECharacteristic& rxCharacteristic) { + BLESerial::_instance->_received(rxCharacteristic.value(), rxCharacteristic.valueLength()); +} diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestBLE/BLESerial.h b/lib/Adafruit_NeoPixel/examples/StrandtestBLE/BLESerial.h new file mode 100644 index 000000000..01904c788 --- /dev/null +++ b/lib/Adafruit_NeoPixel/examples/StrandtestBLE/BLESerial.h @@ -0,0 +1,46 @@ +#ifndef _BLE_SERIAL_H_ +#define _BLE_SERIAL_H_ + +#include +#include + +class BLESerial : public BLEPeripheral, public Stream +{ + public: + BLESerial(unsigned char req, unsigned char rdy, unsigned char rst); + + void begin(...); + void poll(); + void end(); + + virtual int available(void); + virtual int peek(void); + virtual int read(void); + virtual void flush(void); + virtual size_t write(uint8_t byte); + using Print::write; + virtual operator bool(); + + private: + unsigned long _flushed; + static BLESerial* _instance; + + size_t _rxHead; + size_t _rxTail; + size_t _rxCount() const; + uint8_t _rxBuffer[BLE_ATTRIBUTE_MAX_VALUE_LENGTH]; + size_t _txCount; + uint8_t _txBuffer[BLE_ATTRIBUTE_MAX_VALUE_LENGTH]; + + BLEService _uartService = BLEService("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"); + BLEDescriptor _uartNameDescriptor = BLEDescriptor("2901", "UART"); + BLECharacteristic _rxCharacteristic = BLECharacteristic("6E400002-B5A3-F393-E0A9-E50E24DCCA9E", BLEWriteWithoutResponse, BLE_ATTRIBUTE_MAX_VALUE_LENGTH); + BLEDescriptor _rxNameDescriptor = BLEDescriptor("2901", "RX - Receive Data (Write)"); + BLECharacteristic _txCharacteristic = BLECharacteristic("6E400003-B5A3-F393-E0A9-E50E24DCCA9E", BLENotify, BLE_ATTRIBUTE_MAX_VALUE_LENGTH); + BLEDescriptor _txNameDescriptor = BLEDescriptor("2901", "TX - Transfer Data (Notify)"); + + void _received(const uint8_t* data, size_t size); + static void _received(BLECentral& /*central*/, BLECharacteristic& rxCharacteristic); +}; + +#endif diff --git a/lib/Adafruit_NeoPixel/examples/StrandtestBLE/StrandtestBLE.ino b/lib/Adafruit_NeoPixel/examples/StrandtestBLE/StrandtestBLE.ino new file mode 100644 index 000000000..593b35b6d --- /dev/null +++ b/lib/Adafruit_NeoPixel/examples/StrandtestBLE/StrandtestBLE.ino @@ -0,0 +1,192 @@ +/**************************************************************************** + * This example was developed by the Hackerspace San Salvador to demonstrate + * the simultaneous use of the NeoPixel library and the Bluetooth SoftDevice. + * To compile this example you'll need to add support for the NRF52 based + * following the instructions at: + * https://github.com/sandeepmistry/arduino-nRF5 + * Or adding the following URL to the board manager URLs on Arduino preferences: + * https://sandeepmistry.github.io/arduino-nRF5/package_nRF5_boards_index.json + * Then you can install the BLEPeripheral library avaiable at: + * https://github.com/sandeepmistry/arduino-BLEPeripheral + * To test it, compile this example and use the UART module from the nRF + * Toolbox App for Android. Edit the interface and send the characters + * 'a' to 'i' to switch the animation. + * There is a delay because this example blocks the thread of execution but + * the change will be shown after the current animation ends. (This might + * take a couple of seconds) + * For more info write us at: info _at- teubi.co + */ +#include +#include +#include "BLESerial.h" +#include + +#define PIN 15 // Pin where NeoPixels are connected + +// Declare our NeoPixel strip object: +Adafruit_NeoPixel strip(64, PIN, NEO_GRB + NEO_KHZ800); +// Argument 1 = Number of pixels in NeoPixel strip +// Argument 2 = Arduino pin number (most are valid) +// Argument 3 = Pixel type flags, add together as needed: +// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) +// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) +// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) +// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) +// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products) + +// NEOPIXEL BEST PRACTICES for most reliable operation: +// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections. +// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel. +// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR. +// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS +// connect GROUND (-) first, then +, then data. +// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip, +// a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED. +// (Skipping these may work OK on your workbench but can fail in the field) + +// define pins (varies per shield/board) +#define BLE_REQ 10 +#define BLE_RDY 2 +#define BLE_RST 9 + +// create ble serial instance, see pinouts above +BLESerial BLESerial(BLE_REQ, BLE_RDY, BLE_RST); + +uint8_t current_state = 0; +uint8_t rgb_values[3]; + +void setup() { + Serial.begin(115200); + Serial.println("Hello World!"); + // custom services and characteristics can be added as well + BLESerial.setLocalName("UART_HS"); + BLESerial.begin(); + + strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) + strip.show(); // Turn OFF all pixels ASAP + + //pinMode(PIN, OUTPUT); + //digitalWrite(PIN, LOW); + + current_state = 'a'; +} + +void loop() { + while(BLESerial.available()) { + uint8_t character = BLESerial.read(); + switch(character) { + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + current_state = character; + break; + }; + } + switch(current_state) { + case 'a': + colorWipe(strip.Color(255, 0, 0), 20); // Red + break; + case 'b': + colorWipe(strip.Color( 0, 255, 0), 20); // Green + break; + case 'c': + colorWipe(strip.Color( 0, 0, 255), 20); // Blue + break; + case 'd': + theaterChase(strip.Color(255, 0, 0), 20); // Red + break; + case 'e': + theaterChase(strip.Color( 0, 255, 0), 20); // Green + break; + case 'f': + theaterChase(strip.Color(255, 0, 255), 20); // Cyan + break; + case 'g': + rainbow(10); + break; + case 'h': + theaterChaseRainbow(20); + break; + } +} + +// Fill strip pixels one after another with a color. Strip is NOT cleared +// first; anything there will be covered pixel by pixel. Pass in color +// (as a single 'packed' 32-bit value, which you can get by calling +// strip.Color(red, green, blue) as shown in the loop() function above), +// and a delay time (in milliseconds) between pixels. +void colorWipe(uint32_t color, int wait) { + for(int i=0; i RGB + strip.setPixelColor(c, color); // Set pixel 'c' to value 'color' + } + strip.show(); // Update strip with new contents + delay(wait); // Pause for a moment + firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames + } + } +} diff --git a/lib/Adafruit_NeoPixel/examples/buttoncycler/buttoncycler.ino b/lib/Adafruit_NeoPixel/examples/buttoncycler/buttoncycler.ino index cf1598a80..f6d87edcb 100644 --- a/lib/Adafruit_NeoPixel/examples/buttoncycler/buttoncycler.ino +++ b/lib/Adafruit_NeoPixel/examples/buttoncycler/buttoncycler.ino @@ -1,165 +1,164 @@ -// This is a demonstration on how to use an input device to trigger changes on your neo pixels. -// You should wire a momentary push button to connect from ground to a digital IO pin. When you -// press the button it will change to a new pixel animation. Note that you need to press the -// button once to start the first animation! +// Simple demonstration on using an input device to trigger changes on your +// NeoPixels. Wire a momentary push button to connect from ground to a +// digital IO pin. When the button is pressed it will change to a new pixel +// animation. Initial state has all pixels off -- press the button once to +// start the first animation. As written, the button does not interrupt an +// animation in-progress, it works only when idle. #include +#ifdef __AVR__ + #include // Required for 16 MHz Adafruit Trinket +#endif -#define BUTTON_PIN 2 // Digital IO pin connected to the button. This will be - // driven with a pull-up resistor so the switch should - // pull the pin to ground momentarily. On a high -> low - // transition the button press logic will execute. +// Digital IO pin connected to the button. This will be driven with a +// pull-up resistor so the switch pulls the pin to ground momentarily. +// On a high -> low transition the button press logic will execute. +#define BUTTON_PIN 2 -#define PIXEL_PIN 6 // Digital IO pin connected to the NeoPixels. +#define PIXEL_PIN 6 // Digital IO pin connected to the NeoPixels. -#define PIXEL_COUNT 16 +#define PIXEL_COUNT 16 // Number of NeoPixels -// Parameter 1 = number of pixels in strip, neopixel stick has 8 -// Parameter 2 = pin number (most are valid) -// Parameter 3 = pixel type flags, add together as needed: -// NEO_RGB Pixels are wired for RGB bitstream -// NEO_GRB Pixels are wired for GRB bitstream, correct for neopixel stick -// NEO_KHZ400 400 KHz bitstream (e.g. FLORA pixels) -// NEO_KHZ800 800 KHz bitstream (e.g. High Density LED strip), correct for neopixel stick -Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800); +// Declare our NeoPixel strip object: +Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800); +// Argument 1 = Number of pixels in NeoPixel strip +// Argument 2 = Arduino pin number (most are valid) +// Argument 3 = Pixel type flags, add together as needed: +// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) +// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) +// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) +// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) +// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products) -bool oldState = HIGH; -int showType = 0; +boolean oldState = HIGH; +int mode = 0; // Currently-active animation mode, 0-9 void setup() { pinMode(BUTTON_PIN, INPUT_PULLUP); - strip.begin(); - strip.show(); // Initialize all pixels to 'off' + strip.begin(); // Initialize NeoPixel strip object (REQUIRED) + strip.show(); // Initialize all pixels to 'off' } void loop() { // Get current button state. - bool newState = digitalRead(BUTTON_PIN); + boolean newState = digitalRead(BUTTON_PIN); // Check if state changed from high to low (button press). - if (newState == LOW && oldState == HIGH) { + if((newState == LOW) && (oldState == HIGH)) { // Short delay to debounce button. delay(20); // Check if button is still low after debounce. newState = digitalRead(BUTTON_PIN); - if (newState == LOW) { - showType++; - if (showType > 9) - showType=0; - startShow(showType); + if(newState == LOW) { // Yes, still low + if(++mode > 8) mode = 0; // Advance to next mode, wrap around after #8 + switch(mode) { // Start the new animation... + case 0: + colorWipe(strip.Color( 0, 0, 0), 50); // Black/off + break; + case 1: + colorWipe(strip.Color(255, 0, 0), 50); // Red + break; + case 2: + colorWipe(strip.Color( 0, 255, 0), 50); // Green + break; + case 3: + colorWipe(strip.Color( 0, 0, 255), 50); // Blue + break; + case 4: + theaterChase(strip.Color(127, 127, 127), 50); // White + break; + case 5: + theaterChase(strip.Color(127, 0, 0), 50); // Red + break; + case 6: + theaterChase(strip.Color( 0, 0, 127), 50); // Blue + break; + case 7: + rainbow(10); + break; + case 8: + theaterChaseRainbow(50); + break; + } } } - // Set the last button state to the old state. + // Set the last-read button state to the old state. oldState = newState; } -void startShow(int i) { - switch(i){ - case 0: colorWipe(strip.Color(0, 0, 0), 50); // Black/off - break; - case 1: colorWipe(strip.Color(255, 0, 0), 50); // Red - break; - case 2: colorWipe(strip.Color(0, 255, 0), 50); // Green - break; - case 3: colorWipe(strip.Color(0, 0, 255), 50); // Blue - break; - case 4: theaterChase(strip.Color(127, 127, 127), 50); // White - break; - case 5: theaterChase(strip.Color(127, 0, 0), 50); // Red - break; - case 6: theaterChase(strip.Color( 0, 0, 127), 50); // Blue - break; - case 7: rainbow(20); - break; - case 8: rainbowCycle(20); - break; - case 9: theaterChaseRainbow(50); - break; +// Fill strip pixels one after another with a color. Strip is NOT cleared +// first; anything there will be covered pixel by pixel. Pass in color +// (as a single 'packed' 32-bit value, which you can get by calling +// strip.Color(red, green, blue) as shown in the loop() function above), +// and a delay time (in milliseconds) between pixels. +void colorWipe(uint32_t color, int wait) { + for(int i=0; i RGB + strip.setPixelColor(c, color); // Set pixel 'c' to value 'color' } + strip.show(); // Update strip with new contents + delay(wait); // Pause for a moment + firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames } } } - -// Input a value 0 to 255 to get a color value. -// The colours are a transition r - g - b - back to r. -uint32_t Wheel(byte WheelPos) { - WheelPos = 255 - WheelPos; - if(WheelPos < 85) { - return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3); - } - if(WheelPos < 170) { - WheelPos -= 85; - return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3); - } - WheelPos -= 170; - return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0); -} diff --git a/lib/Adafruit_NeoPixel/examples/simple/simple.ino b/lib/Adafruit_NeoPixel/examples/simple/simple.ino index 3b5e3b707..09f458ecb 100644 --- a/lib/Adafruit_NeoPixel/examples/simple/simple.ino +++ b/lib/Adafruit_NeoPixel/examples/simple/simple.ino @@ -1,47 +1,50 @@ // NeoPixel Ring simple sketch (c) 2013 Shae Erisson -// released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library +// Released under the GPLv3 license to match the rest of the +// Adafruit NeoPixel library #include #ifdef __AVR__ - #include + #include // Required for 16 MHz Adafruit Trinket #endif // Which pin on the Arduino is connected to the NeoPixels? -// On a Trinket or Gemma we suggest changing this to 1 -#define PIN 6 +#define PIN 6 // On Trinket or Gemma, suggest changing this to 1 // How many NeoPixels are attached to the Arduino? -#define NUMPIXELS 16 +#define NUMPIXELS 16 // Popular NeoPixel ring size -// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals. -// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest -// example for more information on possible values. -Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); +// When setting up the NeoPixel library, we tell it how many pixels, +// and which pin to use to send signals. Note that for older NeoPixel +// strips you might need to change the third parameter -- see the +// strandtest example for more information on possible values. +Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); -int delayval = 500; // delay for half a second +#define DELAYVAL 500 // Time (in milliseconds) to pause between pixels void setup() { - // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket -#if defined (__AVR_ATtiny85__) - if (F_CPU == 16000000) clock_prescale_set(clock_div_1); + // These lines are specifically to support the Adafruit Trinket 5V 16 MHz. + // Any other board, you can remove this part (but no harm leaving it): +#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000) + clock_prescale_set(clock_div_1); #endif - // End of trinket special code + // END of Trinket-specific code. - pixels.begin(); // This initializes the NeoPixel library. + pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) } void loop() { + pixels.clear(); // Set all pixel colors to 'off' - // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one. + // The first NeoPixel in a strand is #0, second is 1, all the way up + // to the count of pixels minus one. + for(int i=0; i +#ifdef __AVR__ + #include // Required for 16 MHz Adafruit Trinket +#endif + +// Which pin on the Arduino is connected to the NeoPixels? +int pin = 6; // On Trinket or Gemma, suggest changing this to 1 + +// How many NeoPixels are attached to the Arduino? +int numPixels = 16; // Popular NeoPixel ring size + +// NeoPixel color format & data rate. See the strandtest example for +// information on possible values. +int pixelFormat = NEO_GRB + NEO_KHZ800; + +// Rather than declaring the whole NeoPixel object here, we just create +// a pointer for one, which we'll then allocate later... +Adafruit_NeoPixel *pixels; + +#define DELAYVAL 500 // Time (in milliseconds) to pause between pixels + +void setup() { + // These lines are specifically to support the Adafruit Trinket 5V 16 MHz. + // Any other board, you can remove this part (but no harm leaving it): +#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000) + clock_prescale_set(clock_div_1); +#endif + // END of Trinket-specific code. + + // Right about here is where we could read 'pin', 'numPixels' and/or + // 'pixelFormat' from EEPROM or a file on SD or whatever. This is a simple + // example and doesn't do that -- those variables are just set to fixed + // values at the top of this code -- but this is where it would happen. + + // Then create a new NeoPixel object dynamically with these values: + pixels = new Adafruit_NeoPixel(numPixels, pin, pixelFormat); + + // Going forward from here, code works almost identically to any other + // NeoPixel example, but instead of the dot operator on function calls + // (e.g. pixels.begin()), we instead use pointer indirection (->) like so: + pixels->begin(); // INITIALIZE NeoPixel strip object (REQUIRED) + // You'll see more of this in the loop() function below. +} + +void loop() { + pixels->clear(); // Set all pixel colors to 'off' + + // The first NeoPixel in a strand is #0, second is 1, all the way up + // to the count of pixels minus one. + for(int i=0; iColor() takes RGB values, from 0,0,0 up to 255,255,255 + // Here we're using a moderately bright green color: + pixels->setPixelColor(i, pixels->Color(0, 150, 0)); + + pixels->show(); // Send the updated pixel colors to the hardware. + + delay(DELAYVAL); // Pause before next pass through loop + } +} diff --git a/lib/Adafruit_NeoPixel/examples/strandtest/strandtest.ino b/lib/Adafruit_NeoPixel/examples/strandtest/strandtest.ino index 350b0a549..d7b08e330 100644 --- a/lib/Adafruit_NeoPixel/examples/strandtest/strandtest.ino +++ b/lib/Adafruit_NeoPixel/examples/strandtest/strandtest.ino @@ -1,134 +1,147 @@ +// A basic everyday NeoPixel strip test program. + +// NEOPIXEL BEST PRACTICES for most reliable operation: +// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections. +// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel. +// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR. +// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS +// connect GROUND (-) first, then +, then data. +// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip, +// a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED. +// (Skipping these may work OK on your workbench but can fail in the field) + #include #ifdef __AVR__ - #include + #include // Required for 16 MHz Adafruit Trinket #endif -#define PIN 6 +// Which pin on the Arduino is connected to the NeoPixels? +// On a Trinket or Gemma we suggest changing this to 1: +#define LED_PIN 6 -// Parameter 1 = number of pixels in strip -// Parameter 2 = Arduino pin number (most are valid) -// Parameter 3 = pixel type flags, add together as needed: +// How many NeoPixels are attached to the Arduino? +#define LED_COUNT 60 + +// Declare our NeoPixel strip object: +Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800); +// Argument 1 = Number of pixels in NeoPixel strip +// Argument 2 = Arduino pin number (most are valid) +// Argument 3 = Pixel type flags, add together as needed: // NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) // NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) // NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) // NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) // NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products) -Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800); -// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across -// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input -// and minimize distance between Arduino and first pixel. Avoid connecting -// on a live circuit...if you must, connect GND first. + +// setup() function -- runs once at startup -------------------------------- void setup() { - // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket - #if defined (__AVR_ATtiny85__) - if (F_CPU == 16000000) clock_prescale_set(clock_div_1); - #endif - // End of trinket special code + // These lines are specifically to support the Adafruit Trinket 5V 16 MHz. + // Any other board, you can remove this part (but no harm leaving it): +#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000) + clock_prescale_set(clock_div_1); +#endif + // END of Trinket-specific code. - - strip.begin(); - strip.show(); // Initialize all pixels to 'off' + strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) + strip.show(); // Turn OFF all pixels ASAP + strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255) } + +// loop() function -- runs repeatedly as long as board is on --------------- + void loop() { - // Some example procedures showing how to display to the pixels: - colorWipe(strip.Color(255, 0, 0), 50); // Red - colorWipe(strip.Color(0, 255, 0), 50); // Green - colorWipe(strip.Color(0, 0, 255), 50); // Blue -//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW - // Send a theater pixel chase in... - theaterChase(strip.Color(127, 127, 127), 50); // White - theaterChase(strip.Color(127, 0, 0), 50); // Red - theaterChase(strip.Color(0, 0, 127), 50); // Blue + // Fill along the length of the strip in various colors... + colorWipe(strip.Color(255, 0, 0), 50); // Red + colorWipe(strip.Color( 0, 255, 0), 50); // Green + colorWipe(strip.Color( 0, 0, 255), 50); // Blue - rainbow(20); - rainbowCycle(20); - theaterChaseRainbow(50); + // Do a theater marquee effect in various colors... + theaterChase(strip.Color(127, 127, 127), 50); // White, half brightness + theaterChase(strip.Color(127, 0, 0), 50); // Red, half brightness + theaterChase(strip.Color( 0, 0, 127), 50); // Blue, half brightness + + rainbow(10); // Flowing rainbow cycle along the whole strip + theaterChaseRainbow(50); // Rainbow-enhanced theaterChase variant } -// Fill the dots one after the other with a color -void colorWipe(uint32_t c, uint8_t wait) { - for(uint16_t i=0; i RGB + strip.setPixelColor(c, color); // Set pixel 'c' to value 'color' } + strip.show(); // Update strip with new contents + delay(wait); // Pause for a moment + firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames } } } - -// Input a value 0 to 255 to get a color value. -// The colours are a transition r - g - b - back to r. -uint32_t Wheel(byte WheelPos) { - WheelPos = 255 - WheelPos; - if(WheelPos < 85) { - return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3); - } - if(WheelPos < 170) { - WheelPos -= 85; - return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3); - } - WheelPos -= 170; - return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0); -} diff --git a/lib/Adafruit_NeoPixel/examples/strandtest_wheel/.esp8266.test.skip b/lib/Adafruit_NeoPixel/examples/strandtest_wheel/.esp8266.test.skip new file mode 100644 index 000000000..e69de29bb diff --git a/lib/Adafruit_NeoPixel/examples/strandtest_wheel/strandtest_wheel.ino b/lib/Adafruit_NeoPixel/examples/strandtest_wheel/strandtest_wheel.ino new file mode 100644 index 000000000..c0ca41edc --- /dev/null +++ b/lib/Adafruit_NeoPixel/examples/strandtest_wheel/strandtest_wheel.ino @@ -0,0 +1,134 @@ +#include +#ifdef __AVR__ + #include +#endif + +#define PIN 6 + +// Parameter 1 = number of pixels in strip +// Parameter 2 = Arduino pin number (most are valid) +// Parameter 3 = pixel type flags, add together as needed: +// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) +// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) +// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) +// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) +// NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products) +Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800); + +// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across +// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input +// and minimize distance between Arduino and first pixel. Avoid connecting +// on a live circuit...if you must, connect GND first. + +void setup() { + // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket + #if defined (__AVR_ATtiny85__) + if (F_CPU == 16000000) clock_prescale_set(clock_div_1); + #endif + // End of trinket special code + + strip.begin(); + strip.setBrightness(50); + strip.show(); // Initialize all pixels to 'off' +} + +void loop() { + // Some example procedures showing how to display to the pixels: + colorWipe(strip.Color(255, 0, 0), 50); // Red + colorWipe(strip.Color(0, 255, 0), 50); // Green + colorWipe(strip.Color(0, 0, 255), 50); // Blue +//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW + // Send a theater pixel chase in... + theaterChase(strip.Color(127, 127, 127), 50); // White + theaterChase(strip.Color(127, 0, 0), 50); // Red + theaterChase(strip.Color(0, 0, 127), 50); // Blue + + rainbow(20); + rainbowCycle(20); + theaterChaseRainbow(50); +} + +// Fill the dots one after the other with a color +void colorWipe(uint32_t c, uint8_t wait) { + for(uint16_t i=0; i +#include "sysctl.h" + +void k210Show( + uint8_t pin, uint8_t *pixels, uint32_t numBytes, boolean is800KHz) +{ + +#define CYCLES_800_T0H (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 2500000) // 0.4us +#define CYCLES_800_T1H (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 1250000) // 0.8us +#define CYCLES_800 (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 800000) // 1.25us per bit +#define CYCLES_400_T0H (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 2000000) // 0.5uS +#define CYCLES_400_T1H (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 833333) // 1.2us +#define CYCLES_400 (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 400000) // 2.5us per bit + + uint8_t *p, *end, pix, mask; + uint32_t t, time0, time1, period, c, startTime; + + p = pixels; + end = p + numBytes; + pix = *p++; + mask = 0x80; + startTime = 0; + +#ifdef NEO_KHZ400 + if (is800KHz) + { +#endif + time0 = CYCLES_800_T0H; + time1 = CYCLES_800_T1H; + period = CYCLES_800; +#ifdef NEO_KHZ400 + } + else + { // 400 KHz bitstream + time0 = CYCLES_400_T0H; + time1 = CYCLES_400_T1H; + period = CYCLES_400; + } +#endif + + for (t = time0;; t = time0) + { + if (pix & mask) + t = time1; // Bit high duration + while (((c = read_cycle()) - startTime) < period) + ; // Wait for bit start + digitalWrite(pin, HIGH); + startTime = c; // Save start time + while (((c = read_cycle()) - startTime) < t) + ; // Wait high duration + digitalWrite(pin, LOW); + + if (!(mask >>= 1)) + { // Next bit/byte + if (p >= end) + break; + pix = *p++; + mask = 0x80; + } + } + while ((read_cycle() - startTime) < period) + ; // Wait for last bit +} + +#endif // KENDRYTE_K210 diff --git a/lib/Adafruit_NeoPixel/keywords.txt b/lib/Adafruit_NeoPixel/keywords.txt index 76f9446df..4003ede9d 100644 --- a/lib/Adafruit_NeoPixel/keywords.txt +++ b/lib/Adafruit_NeoPixel/keywords.txt @@ -1,29 +1,72 @@ ####################################### # Syntax Coloring Map For Adafruit_NeoPixel -####################################### +####################################### # Class ####################################### Adafruit_NeoPixel KEYWORD1 ####################################### -# Methods and Functions +# Methods and Functions ####################################### -setPixelColor KEYWORD2 +begin KEYWORD2 +show KEYWORD2 setPin KEYWORD2 -setBrightness KEYWORD2 +setPixelColor KEYWORD2 +fill KEYWORD2 +setBrightness KEYWORD2 +clear KEYWORD2 +updateLength KEYWORD2 +updateType KEYWORD2 +canShow KEYWORD2 +getPixels KEYWORD2 +getBrightness KEYWORD2 +getPin KEYWORD2 numPixels KEYWORD2 -getPixelColor KEYWORD2 +getPixelColor KEYWORD2 +sine8 KEYWORD2 +gamma8 KEYWORD2 Color KEYWORD2 +ColorHSV KEYWORD2 +gamma32 KEYWORD2 ####################################### # Constants ####################################### - -NEO_GRB LITERAL1 + NEO_COLMASK LITERAL1 -NEO_KHZ800 LITERAL1 NEO_SPDMASK LITERAL1 -NEO_RGB LITERAL1 +NEO_KHZ800 LITERAL1 NEO_KHZ400 LITERAL1 +NEO_RGB LITERAL1 +NEO_RBG LITERAL1 +NEO_GRB LITERAL1 +NEO_GBR LITERAL1 +NEO_BRG LITERAL1 +NEO_BGR LITERAL1 +NEO_WRGB LITERAL1 +NEO_WRBG LITERAL1 +NEO_WGRB LITERAL1 +NEO_WGBR LITERAL1 +NEO_WBRG LITERAL1 +NEO_WBGR LITERAL1 +NEO_RWGB LITERAL1 +NEO_RWBG LITERAL1 +NEO_RGWB LITERAL1 +NEO_RGBW LITERAL1 +NEO_RBWG LITERAL1 +NEO_RBGW LITERAL1 +NEO_GWRB LITERAL1 +NEO_GWBR LITERAL1 +NEO_GRWB LITERAL1 +NEO_GRBW LITERAL1 +NEO_GBWR LITERAL1 +NEO_GBRW LITERAL1 +NEO_BWRG LITERAL1 +NEO_BWGR LITERAL1 +NEO_BRWG LITERAL1 +NEO_BRGW LITERAL1 +NEO_BGWR LITERAL1 +NEO_BGRW LITERAL1 + diff --git a/lib/Adafruit_NeoPixel/library.properties b/lib/Adafruit_NeoPixel/library.properties index 4de596975..cc4bbc499 100644 --- a/lib/Adafruit_NeoPixel/library.properties +++ b/lib/Adafruit_NeoPixel/library.properties @@ -1,5 +1,5 @@ name=Adafruit NeoPixel -version=1.0.6 +version=1.8.7 author=Adafruit maintainer=Adafruit sentence=Arduino library for controlling single-wire-based LED pixels and strip. diff --git a/lib/Adafruit_NeoPixel/rp2040.c b/lib/Adafruit_NeoPixel/rp2040.c new file mode 100644 index 000000000..388a43bf2 --- /dev/null +++ b/lib/Adafruit_NeoPixel/rp2040.c @@ -0,0 +1,53 @@ +// This sketch is based on the SDK example here: +// https://github.com/raspberrypi/pico-examples/tree/master/pio/ws2812 + +/** + Copyright (c) 2020 Raspberry Pi (Trading) Ltd. + + SPDX-License-Identifier: BSD-3-Clause +*/ + +#if defined(ARDUINO_ARCH_RP2040) + +#include +#include "hardware/pio.h" +#include "hardware/clocks.h" + +#include "rp2040_pio.h" + +void rp2040Init(uint8_t pin, bool is800KHz) +{ + // todo get free sm + PIO pio = pio0; + int sm = 0; + uint offset = pio_add_program(pio, &ws2812_program); + + if (is800KHz) + { + // 800kHz, 8 bit transfers + ws2812_program_init(pio, sm, offset, pin, 800000, 8); + } + else + { + // 400kHz, 8 bit transfers + ws2812_program_init(pio, sm, offset, pin, 400000, 8); + } +} + +void rp2040Show(uint8_t pin, uint8_t *pixels, uint32_t numBytes, bool is800KHz) +{ + static bool init = true; + + if (init) + { + // On first pass through initialise the PIO + rp2040Init(pin, is800KHz); + init = false; + } + + while(numBytes--) + // Bits for transmission must be shifted to top 8 bits + pio_sm_put_blocking(pio0, 0, ((uint32_t)*pixels++)<< 24); +} + +#endif // KENDRYTE_K210 diff --git a/lib/Adafruit_NeoPixel/rp2040_pio.h b/lib/Adafruit_NeoPixel/rp2040_pio.h new file mode 100644 index 000000000..63fc275f3 --- /dev/null +++ b/lib/Adafruit_NeoPixel/rp2040_pio.h @@ -0,0 +1,61 @@ +// -------------------------------------------------- // +// This file is autogenerated by pioasm; do not edit! // +// -------------------------------------------------- // + +// Unless you know what you are doing... +// Lines 47 and 52 have been edited to set transmit bit count + +#if !PICO_NO_HARDWARE +#include "hardware/pio.h" +#endif + +// ------ // +// ws2812 // +// ------ // + +#define ws2812_wrap_target 0 +#define ws2812_wrap 3 + +#define ws2812_T1 2 +#define ws2812_T2 5 +#define ws2812_T3 3 + +static const uint16_t ws2812_program_instructions[] = { + // .wrap_target + 0x6221, // 0: out x, 1 side 0 [2] + 0x1123, // 1: jmp !x, 3 side 1 [1] + 0x1400, // 2: jmp 0 side 1 [4] + 0xa442, // 3: nop side 0 [4] + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program ws2812_program = { + .instructions = ws2812_program_instructions, + .length = 4, + .origin = -1, +}; + +static inline pio_sm_config ws2812_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + ws2812_wrap_target, offset + ws2812_wrap); + sm_config_set_sideset(&c, 1, false, false); + return c; +} + +#include "hardware/clocks.h" +static inline void ws2812_program_init(PIO pio, uint sm, uint offset, uint pin, float freq, uint bits) { + pio_gpio_init(pio, pin); + pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, true); + pio_sm_config c = ws2812_program_get_default_config(offset); + sm_config_set_sideset_pins(&c, pin); + sm_config_set_out_shift(&c, false, true, bits); // <----<<< Length changed to "bits" + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); + int cycles_per_bit = ws2812_T1 + ws2812_T2 + ws2812_T3; + float div = clock_get_hz(clk_sys) / (freq * cycles_per_bit); + sm_config_set_clkdiv(&c, div); + pio_sm_init(pio, sm, offset, &c); + pio_sm_set_enabled(pio, sm, true); +} + +#endif diff --git a/lib/ESPEasySerial/ESPEasySerial_ESP32.cpp b/lib/ESPEasySerial/ESPEasySerial_ESP32.cpp index 2e2552f3b..29bcc0c93 100644 --- a/lib/ESPEasySerial/ESPEasySerial_ESP32.cpp +++ b/lib/ESPEasySerial/ESPEasySerial_ESP32.cpp @@ -100,7 +100,10 @@ HardwareSerial * ESPeasySerial::getHW() { switch (_serialtype) { case ESPEasySerialPort::serial0: return &Serial; case ESPEasySerialPort::serial1: return &Serial1; - case ESPEasySerialPort::serial2: return &Serial2; + case ESPEasySerialPort::serial2: + #ifndef ESP32S2 + return &Serial2; + #endif default: break; } @@ -111,7 +114,10 @@ const HardwareSerial * ESPeasySerial::getHW() const { switch (_serialtype) { case ESPEasySerialPort::serial0: return &Serial; case ESPEasySerialPort::serial1: return &Serial1; - case ESPEasySerialPort::serial2: return &Serial2; + case ESPEasySerialPort::serial2: + #ifndef ESP32S2 + return &Serial2; + #endif default: break; } return nullptr; diff --git a/lib/ESPEasySerial/library.json b/lib/ESPEasySerial/library.json index 131eb39a5..a21b93605 100644 --- a/lib/ESPEasySerial/library.json +++ b/lib/ESPEasySerial/library.json @@ -1,10 +1,10 @@ { "name": "ESPeasySerial", - "version": "2.0.5", + "version": "2.0.6", "keywords": [ "serial", "io", "softwareserial", "hardwareserial" ], - "description": "Wrapper for SoftwareSerial, SC16IS752 I2C to UART bridge and HardwareSerial for ESP8266 and ESP32", + "description": "Wrapper for SoftwareSerial, SC16IS752 I2C to UART bridge and HardwareSerial for ESP8266 and ESP32/ESP32S2", "repository": { "type": "git", diff --git a/lib/ESPEasySerial/library.properties b/lib/ESPEasySerial/library.properties index 53b875ef4..8feb08756 100644 --- a/lib/ESPEasySerial/library.properties +++ b/lib/ESPEasySerial/library.properties @@ -1,8 +1,8 @@ name=ESPeasySerial -version=2.0.5 +version=2.0.6 author=Gijs Noorlander maintainer=Gijs Noorlander -sentence=Wrapper for SoftwareSerial, SC16IS752 I2C to UART bridge and HardwareSerial for ESP8266 and ESP32. +sentence=Wrapper for SoftwareSerial, SC16IS752 I2C to UART bridge and HardwareSerial for ESP8266 and ESP32/ESP32S2. paragraph= depends=SC16IS752 category=Signal Input/Output diff --git a/lib/TinyGPSPlus-1.0.2/src/TinyGPS++.cpp b/lib/TinyGPSPlus-1.0.2/src/TinyGPS++.cpp index e4d102954..a8b1687c5 100644 --- a/lib/TinyGPSPlus-1.0.2/src/TinyGPS++.cpp +++ b/lib/TinyGPSPlus-1.0.2/src/TinyGPS++.cpp @@ -26,6 +26,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include #include #include +#include TinyGPSPlus::TinyGPSPlus() : parity(0) diff --git a/platformio.ini b/platformio.ini index cba79aa4e..c8afabf10 100644 --- a/platformio.ini +++ b/platformio.ini @@ -11,7 +11,8 @@ ; *********************************************************************; [platformio] -description = Firmware for ESP82xx/ESP32 for easy IoT deployment of sensors. +description = Firmware for ESP82xx/ESP32/ESP32-s2 for easy IoT deployment of sensors. +boards_dir = boards extra_configs = platformio_core_defs.ini platformio_esp82xx_base.ini diff --git a/platformio_core_defs.ini b/platformio_core_defs.ini index 688c9c7f9..63d3ffc1c 100644 --- a/platformio_core_defs.ini +++ b/platformio_core_defs.ini @@ -159,12 +159,24 @@ platform = espressif32@1.12.4 platform = espressif32@2.1.0 build_flags = -[core_esp32_3_3_0] -platform = espressif32@3.3.0 -build_flags = +[core_esp32_3_3_2] +platform = https://github.com/platformio/platform-espressif32.git#feature/arduino-idf-master +platform_packages = framework-arduinoespressif32 @ https://github.com/Jason2866/esp32-arduino-lib-builder/releases/download/424/framework-arduinoespressif32-master-cdcf92440.tar.gz +build_flags = -DESP32_STAGE + +[core_esp32_3_3_2_esp32s2] +platform = https://github.com/platformio/platform-espressif32.git#feature/arduino-idf-master +platform_packages = framework-arduinoespressif32 @ https://github.com/Jason2866/arduino-esp32/releases/download/v.2.0-post/framework-arduinoespressif32_i2c.zip +build_flags = -DESP32_STAGE + + +[core_esp32_3_0_0] +platform = espressif32@3.0.0 +platform_packages = framework-arduinoespressif32 @ https://github.com/Jason2866/arduino-esp32/releases/download/1.0.5-rc6/esp32-1.0.5-rc6.zip + [core_esp32_stage] platform = espressif32 -platform_packages = platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git +platform_packages = framework-arduinoespressif32 @ https://github.com/Jason2866/arduino-esp32/releases/download/v.2.0-post/framework-arduinoespressif32_i2c.zip build_flags = -DESP32_STAGE diff --git a/platformio_esp32_envs.ini b/platformio_esp32_envs.ini index 3c16abd94..de66b1c9e 100644 --- a/platformio_esp32_envs.ini +++ b/platformio_esp32_envs.ini @@ -9,8 +9,8 @@ lib_ignore = ESP8266WiFi, ESP8266Ping, ESP8266WebServer, ESP8266H [esp32_common] -extends = common, core_esp32_3_3_0 -lib_deps = https://github.com/TD-er/ESPEasySerial.git#v2.0.5, adafruit/Adafruit ILI9341 @ ^1.5.6, Adafruit GFX Library, LOLIN_EPD, adafruit/Adafruit BusIO @ ~1.9.0, VL53L0X @ 1.3.0, SparkFun VL53L1X 4m Laser Distance Sensor @ 1.2.9, td-er/SparkFun MAX1704x Fuel Gauge Arduino Library @ ^1.0.1 +extends = common, core_esp32_3_3_2 +lib_deps = td-er/ESPeasySerial @ 2.0.6, adafruit/Adafruit ILI9341 @ ^1.5.6, Adafruit GFX Library, LOLIN_EPD, Adafruit BusIO, VL53L0X @ 1.3.0, SparkFun VL53L1X 4m Laser Distance Sensor @ 1.2.9, td-er/SparkFun MAX1704x Fuel Gauge Arduino Library @ ^1.0.1 lib_ignore = ${esp32_always.lib_ignore}, ESP32_ping, IRremoteESP8266, HeatpumpIR board_build.f_flash = 80000000L board_build.flash_mode = dout @@ -19,12 +19,12 @@ board_build.partitions = esp32_partition_app1810k_spiffs316k.csv extra_scripts = post:tools/pio/post_esp32.py ${extra_scripts_default.extra_scripts} build_unflags = -Wall -build_flags = ${core_esp32_stage.build_flags} +build_flags = ${core_esp32_3_3_2.build_flags} ${mqtt_flags.build_flags} -DCONFIG_FREERTOS_ASSERT_DISABLE -DCONFIG_LWIP_ESP_GRATUITOUS_ARP - -DCONFIG_LWIP_GARP_TMR_INTERVAL=30 -fno-strict-aliasing + -DCORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_NONE monitor_filters = esp32_exception_decoder @@ -37,6 +37,22 @@ board = esp32dev extra_scripts = ${esp32_common.extra_scripts} pre:tools/pio/pre_custom_esp32.py + +; ESP32-S2 +[env:custom_ESP32s2_4M316k] +extends = esp32_common +build_flags = ${esp32_common.build_flags} + -DPLUGIN_BUILD_CUSTOM + -DESP32S2 + -DBOARD_HAS_PSRAM + -DESP32_ENABLE_PSRAM + -mfix-esp32-psram-cache-issue +board = esp32-s2-saola-1 +extra_scripts = ${esp32_common.extra_scripts} + pre:tools/pio/pre_custom_esp32.py +platform_packages = ${core_esp32_3_3_2_esp32s2.platform_packages} + + [env:custom_IR_ESP32_4M316k] extends = esp32_common platform = ${esp32_common.platform} diff --git a/platformio_esp82xx_base.ini b/platformio_esp82xx_base.ini index 95a3eacbb..df9ab575e 100644 --- a/platformio_esp82xx_base.ini +++ b/platformio_esp82xx_base.ini @@ -48,7 +48,7 @@ extends = common board_build.f_cpu = 80000000L build_flags = ${debug_flags.build_flags} ${mqtt_flags.build_flags} -DHTTPCLIENT_1_1_COMPATIBLE=0 build_unflags = -DDEBUG_ESP_PORT -lib_deps = https://github.com/TD-er/ESPEasySerial.git#v2.0.5, adafruit/Adafruit ILI9341 @ ^1.5.6, Adafruit GFX Library, LOLIN_EPD, adafruit/Adafruit BusIO @ ~1.9.0, bblanchon/ArduinoJson @ ^6.17.2, VL53L0X @ 1.3.0, SparkFun VL53L1X 4m Laser Distance Sensor @ 1.2.9, td-er/RABurton ESP8266 Mutex @ ^1.0.2, td-er/SparkFun MAX1704x Fuel Gauge Arduino Library @ ^1.0.1 +lib_deps = td-er/ESPeasySerial @ 2.0.6, adafruit/Adafruit ILI9341 @ ^1.5.6, Adafruit GFX Library, LOLIN_EPD, adafruit/Adafruit BusIO @ ~1.9.0, bblanchon/ArduinoJson @ ^6.17.2, VL53L0X @ 1.3.0, SparkFun VL53L1X 4m Laser Distance Sensor @ 1.2.9, td-er/RABurton ESP8266 Mutex @ ^1.0.2, td-er/SparkFun MAX1704x Fuel Gauge Arduino Library @ ^1.0.1 lib_ignore = ${esp82xx_defaults.lib_ignore}, IRremoteESP8266, HeatpumpIR, LittleFS(esp8266), ServoESP32, TinyWireM board = esp12e monitor_filters = esp8266_exception_decoder diff --git a/src/ESPEasy_common.h b/src/ESPEasy_common.h index d2d0f21e5..9f112a49b 100644 --- a/src/ESPEasy_common.h +++ b/src/ESPEasy_common.h @@ -106,14 +106,19 @@ namespace std #define SMALLEST_OTA_IMAGE 276848 // smallest known 2-step OTA image #define MAX_SKETCH_SIZE 1044464 // 1020 kB - 16 bytes - #define PIN_D_MAX 16 #endif #if defined(ESP32) // Temp fix for a missing core_version.h within ESP Arduino core. Wait until they actually have different releases #define ARDUINO_ESP8266_RELEASE "2_4_0" - #define NODE_TYPE_ID NODE_TYPE_ID_ESP_EASY32_STD + #ifdef ESP32S2 + #define NODE_TYPE_ID NODE_TYPE_ID_ESP_EASY32S2_STD + #elif defined(ESP32C3) + #define NODE_TYPE_ID NODE_TYPE_ID_ESP_EASY32C3_STD + #else + #define NODE_TYPE_ID NODE_TYPE_ID_ESP_EASY32_STD + #endif #if ESP_IDF_VERSION_MAJOR < 3 #define ICACHE_RAM_ATTR IRAM_ATTR #endif @@ -123,13 +128,18 @@ namespace std #define FILE_RULES "/rules1.txt" #include // #include "esp32_ping.h" - #if ESP_IDF_VERSION_MAJOR > 3 - #include + + #ifdef ESP32S2 + #include #else - #include + #if ESP_IDF_VERSION_MAJOR > 3 + #include + #else + #include + #endif #endif - #include "esp_wifi.h" // Needed to call ESP-IDF functions like esp_wifi_.... - #define PIN_D_MAX 39 + + #include // Needed to call ESP-IDF functions like esp_wifi_.... #ifdef PLUGIN_BUILD_MAX_ESP32 #define MAX_SKETCH_SIZE 4194304 // 0x400000 look at partitions in csv file #else // PLUGIN_BUILD_MAX_ESP32 diff --git a/src/_C018.ino b/src/_C018.ino index 81f2e3eb9..47e0db80c 100644 --- a/src/_C018.ino +++ b/src/_C018.ino @@ -307,7 +307,7 @@ struct C018_data_struct { if (rn2xx3_handler::RN_state::must_perform_init == state) { if (myLora->get_busy_count() > 10) { - if (_resetPin != -1) { + if (validGpio(_resetPin)) { pinMode(_resetPin, OUTPUT); digitalWrite(_resetPin, LOW); delay(50); @@ -363,7 +363,7 @@ private: while (retries > 0 && !autobaud_success) { if (retries == 1) { - if (_resetPin != -1) { + if (validGpio(_resetPin)) { pinMode(_resetPin, OUTPUT); digitalWrite(_resetPin, LOW); delay(50); diff --git a/src/_P001_Switch.ino b/src/_P001_Switch.ino index d8598a5f2..d7b252d8b 100644 --- a/src/_P001_Switch.ino +++ b/src/_P001_Switch.ino @@ -250,7 +250,7 @@ boolean Plugin_001(uint8_t function, struct EventStruct *event, String& string) case PLUGIN_INIT: { // apply INIT only if PORT is in range. Do not start INIT if port not set in the device page. - if ((CONFIG_PIN1 >= 0) && (CONFIG_PIN1 <= PIN_D_MAX)) + if (validGpio(CONFIG_PIN1)) { portStatusStruct newStatus; const uint32_t key = createKey(PLUGIN_ID_001, CONFIG_PIN1); @@ -411,7 +411,7 @@ boolean Plugin_001(uint8_t function, struct EventStruct *event, String& string) // Bug fixed: avoid 10xSEC in case of a non-fully configured device (no GPIO defined yet) const String monitorEventString = F("GPIO"); - if ((CONFIG_PIN1 >= 0) && (CONFIG_PIN1 <= PIN_D_MAX)) + if (validGpio(CONFIG_PIN1)) { const uint32_t key = createKey(PLUGIN_ID_001, CONFIG_PIN1); // WARNING operator [],creates an entry in map if key doesn't exist: diff --git a/src/_P004_Dallas.ino b/src/_P004_Dallas.ino index 5d1798059..809f21d3c 100644 --- a/src/_P004_Dallas.ino +++ b/src/_P004_Dallas.ino @@ -128,7 +128,7 @@ boolean Plugin_004(uint8_t function, struct EventStruct *event, String& string) Plugin_004_DallasPin_TX = Plugin_004_DallasPin_RX; } - if (Plugin_004_DallasPin_RX != -1 && Plugin_004_DallasPin_TX != -1) { + if (validGpio(Plugin_004_DallasPin_RX) && validGpio(Plugin_004_DallasPin_TX)) { Dallas_addr_selector_webform_load(event->TaskIndex, Plugin_004_DallasPin_RX, Plugin_004_DallasPin_TX, P004_NR_OUTPUT_VALUES); { @@ -187,7 +187,7 @@ boolean Plugin_004(uint8_t function, struct EventStruct *event, String& string) Plugin_004_DallasPin_TX = Plugin_004_DallasPin_RX; } - if (Plugin_004_DallasPin_RX != -1 && Plugin_004_DallasPin_TX != -1) { + if (validGpio(Plugin_004_DallasPin_RX) && validGpio(Plugin_004_DallasPin_TX)) { // save the address for selected device and store into extra tasksettings Dallas_addr_selector_webform_save(event->TaskIndex, Plugin_004_DallasPin_RX, Plugin_004_DallasPin_TX, P004_NR_OUTPUT_VALUES); @@ -235,7 +235,7 @@ boolean Plugin_004(uint8_t function, struct EventStruct *event, String& string) Plugin_004_DallasPin_TX = Plugin_004_DallasPin_RX; } - if ((addr[0] != 0) && (Plugin_004_DallasPin_RX != -1) && (Plugin_004_DallasPin_TX != -1)) { + if ((addr[0] != 0) && (validGpio(Plugin_004_DallasPin_RX)) && (validGpio(Plugin_004_DallasPin_TX))) { const uint8_t res = P004_RESOLUTION; initPluginTaskData(event->TaskIndex, new (std::nothrow) P004_data_struct(Plugin_004_DallasPin_RX, Plugin_004_DallasPin_TX, addr, res)); P004_data_struct *P004_data = diff --git a/src/_P012_LCD.ino b/src/_P012_LCD.ino index 18e69a747..28ee9e463 100644 --- a/src/_P012_LCD.ino +++ b/src/_P012_LCD.ino @@ -155,7 +155,7 @@ boolean Plugin_012(uint8_t function, struct EventStruct *event, String& string) break; } - if (CONFIG_PIN3 != -1) { + if (validGpio(CONFIG_PIN3)) { pinMode(CONFIG_PIN3, INPUT_PULLUP); } success = true; @@ -164,7 +164,7 @@ boolean Plugin_012(uint8_t function, struct EventStruct *event, String& string) case PLUGIN_TEN_PER_SECOND: { - if (CONFIG_PIN3 != -1) + if (validGpio(CONFIG_PIN3)) { if (digitalRead(CONFIG_PIN3) == P012_INVERSE_BTN) { diff --git a/src/_P017_PN532.ino b/src/_P017_PN532.ino index a2bd7ab63..98d0e40d9 100644 --- a/src/_P017_PN532.ino +++ b/src/_P017_PN532.ino @@ -227,7 +227,7 @@ boolean Plugin_017(uint8_t function, struct EventStruct *event, String& string) \*********************************************************************************************/ boolean Plugin_017_Init(int8_t resetPin) { - if (resetPin != -1) + if (validGpio(resetPin)) { if (loglevelActiveFor(LOG_LEVEL_INFO)) { String log = F("PN532: Reset on pin: "); diff --git a/src/_P020_Ser2Net.ino b/src/_P020_Ser2Net.ino index a6832b35c..f6f48a79d 100644 --- a/src/_P020_Ser2Net.ino +++ b/src/_P020_Ser2Net.ino @@ -193,7 +193,7 @@ boolean Plugin_020(uint8_t function, struct EventStruct *event, String& string) break; } - if (P020_RESET_TARGET_PIN != -1) { + if (validGpio(P020_RESET_TARGET_PIN)) { if (loglevelActiveFor(LOG_LEVEL_DEBUG)) { String log; log.reserve(38); diff --git a/src/_P023_OLED.ino b/src/_P023_OLED.ino index 542de726b..374ab14fd 100644 --- a/src/_P023_OLED.ino +++ b/src/_P023_OLED.ino @@ -185,7 +185,7 @@ boolean Plugin_023(uint8_t function, struct EventStruct *event, String& string) P023_data->sendStrXY("ESP Easy ", 0, 0); - if (CONFIG_PIN3 != -1) { + if (validGpio(CONFIG_PIN3)) { pinMode(CONFIG_PIN3, INPUT_PULLUP); } success = true; @@ -195,7 +195,7 @@ boolean Plugin_023(uint8_t function, struct EventStruct *event, String& string) case PLUGIN_TEN_PER_SECOND: { - if (CONFIG_PIN3 != -1) + if (validGpio(CONFIG_PIN3)) { if (!digitalRead(CONFIG_PIN3)) { diff --git a/src/_P035_IRTX.ino b/src/_P035_IRTX.ino index 9d7f9022d..64034114c 100644 --- a/src/_P035_IRTX.ino +++ b/src/_P035_IRTX.ino @@ -99,7 +99,7 @@ boolean Plugin_035(uint8_t function, struct EventStruct *event, String &command) case PLUGIN_INIT: { int irPin = CONFIG_PIN1; - if (Plugin_035_irSender == 0 && irPin != -1) + if (Plugin_035_irSender == 0 && validGpio(irPin)) { if (loglevelActiveFor(LOG_LEVEL_INFO)) { addLog(LOG_LEVEL_INFO, F("INIT: IR TX")); @@ -117,7 +117,7 @@ boolean Plugin_035(uint8_t function, struct EventStruct *event, String &command) } #ifdef P016_P035_Extended_AC - if (Plugin_035_commonAc == nullptr && irPin != -1) + if (Plugin_035_commonAc == nullptr && validGpio(irPin)) { if (loglevelActiveFor(LOG_LEVEL_INFO)) { addLog(LOG_LEVEL_INFO, F("INIT AC: IR TX")); diff --git a/src/_P036_FrameOLED.ino b/src/_P036_FrameOLED.ino index d78ea0e5f..b488f831b 100644 --- a/src/_P036_FrameOLED.ino +++ b/src/_P036_FrameOLED.ino @@ -515,7 +515,7 @@ boolean Plugin_036(uint8_t function, struct EventStruct *event, String& string) } #endif - if (CONFIG_PIN3 != -1) // Button related setup + if (validGpio(CONFIG_PIN3)) // Button related setup { #ifdef INPUT_PULLDOWN @@ -570,7 +570,7 @@ boolean Plugin_036(uint8_t function, struct EventStruct *event, String& string) return success; } - if (CONFIG_PIN3 != -1) + if (validGpio(CONFIG_PIN3)) { P036_data->registerButtonState(digitalRead(CONFIG_PIN3), bitRead(P036_FLAGS_0, P036_FLAG_PIN3_INVERSE)); // Bit 16 } @@ -596,7 +596,7 @@ boolean Plugin_036(uint8_t function, struct EventStruct *event, String& string) P036_data->bAlternativHeader = (++P036_data->HeaderCount > (Settings.TaskDeviceTimer[event->TaskIndex] * 5)); // change header after half of display time - if ((CONFIG_PIN3 != -1) && P036_data->ButtonState) + if ((validGpio(CONFIG_PIN3)) && P036_data->ButtonState) { if (bitRead(P036_FLAGS_0, P036_FLAG_STEP_PAGES_BUTTON) && (UserVar[event->BaseVarIndex] == 1)) { // Bit 19 When display already on, switch to next page when enabled if (P036_data->ScrollingPages.Scrolling == 0) { // page scrolling not running -> switch to next page is allowed diff --git a/src/_P042_Candle.ino b/src/_P042_Candle.ino index 8ab5323d6..88af364a9 100644 --- a/src/_P042_Candle.ino +++ b/src/_P042_Candle.ino @@ -269,7 +269,7 @@ boolean Plugin_042(uint8_t function, struct EventStruct *event, String& string) if (!Candle_pixels || GPIO_Set == false) { - GPIO_Set = CONFIG_PIN1 > -1; + GPIO_Set = validGpio(CONFIG_PIN1); if (Candle_pixels) { delete Candle_pixels; } diff --git a/src/_P044_P1WifiGateway.ino b/src/_P044_P1WifiGateway.ino index fd72bd335..e614db7ee 100644 --- a/src/_P044_P1WifiGateway.ino +++ b/src/_P044_P1WifiGateway.ino @@ -117,7 +117,7 @@ boolean Plugin_044(uint8_t function, struct EventStruct *event, String& string) break; } - if (P044_RESET_TARGET_PIN != -1) { + if (validGpio(P044_RESET_TARGET_PIN)) { pinMode(P044_RESET_TARGET_PIN, OUTPUT); digitalWrite(P044_RESET_TARGET_PIN, LOW); delay(500); diff --git a/src/_P076_HLW8012.ino b/src/_P076_HLW8012.ino index e23e61278..9a29af0df 100644 --- a/src/_P076_HLW8012.ino +++ b/src/_P076_HLW8012.ino @@ -375,7 +375,7 @@ boolean Plugin_076(uint8_t function, struct EventStruct *event, String &string) const uint8_t CF1_PIN = CONFIG_PIN2; const uint8_t SEL_PIN = CONFIG_PIN1; - if (CF_PIN != -1 && CF1_PIN != -1 && SEL_PIN != -1) { + if (validGpio(CF_PIN) && validGpio(CF1_PIN) && validGpio(SEL_PIN)) { Plugin_076_hlw = new (std::nothrow) HLW8012; if (Plugin_076_hlw) { uint8_t currentRead = PCONFIG(4); diff --git a/src/_P080_DallasIButton.ino b/src/_P080_DallasIButton.ino index e93bc6759..e93d6203c 100644 --- a/src/_P080_DallasIButton.ino +++ b/src/_P080_DallasIButton.ino @@ -64,7 +64,7 @@ boolean Plugin_080(uint8_t function, struct EventStruct *event, String& string) // Scan the onewire bus and fill dropdown list with devicecount on this GPIO. Plugin_080_DallasPin = CONFIG_PIN1; - if (Plugin_080_DallasPin != -1) { + if (validGpio(Plugin_080_DallasPin)) { Dallas_addr_selector_webform_load(event->TaskIndex, Plugin_080_DallasPin, Plugin_080_DallasPin); } success = true; @@ -92,7 +92,7 @@ boolean Plugin_080(uint8_t function, struct EventStruct *event, String& string) { Plugin_080_DallasPin = CONFIG_PIN1; - if (Plugin_080_DallasPin != -1) { + if (validGpio(Plugin_080_DallasPin)) { uint8_t addr[8]; Dallas_plugin_get_addr(addr, event->TaskIndex); Dallas_startConversion(addr, Plugin_080_DallasPin, Plugin_080_DallasPin); diff --git a/src/_P082_GPS.ino b/src/_P082_GPS.ino index 7addb6183..7756158c1 100644 --- a/src/_P082_GPS.ino +++ b/src/_P082_GPS.ino @@ -251,7 +251,7 @@ boolean Plugin_082(uint8_t function, struct EventStruct *event, String& string) success = true; serialHelper_log_GpioDescription(port, serial_rx, serial_tx); - if (pps_pin != -1) { + if (validGpio(pps_pin)) { // pinMode(pps_pin, INPUT_PULLUP); attachInterrupt(pps_pin, Plugin_082_interrupt, RISING); } @@ -264,7 +264,7 @@ boolean Plugin_082(uint8_t function, struct EventStruct *event, String& string) case PLUGIN_EXIT: { const int16_t pps_pin = CONFIG_PIN3; - if (pps_pin != -1) { + if (validGpio(pps_pin)) { detachInterrupt(pps_pin); } success = true; diff --git a/src/_P088_HeatpumpIR.ino b/src/_P088_HeatpumpIR.ino index 8fb16f364..ef944840c 100644 --- a/src/_P088_HeatpumpIR.ino +++ b/src/_P088_HeatpumpIR.ino @@ -115,7 +115,7 @@ boolean Plugin_088(uint8_t function, struct EventStruct *event, String& string) case PLUGIN_INIT: { int irPin = Settings.TaskDevicePin1[event->TaskIndex]; - if (irPin != -1) + if (validGpio(irPin)) { addLog(LOG_LEVEL_INFO, F("P088: Heatpump IR transmitter activated")); if (Plugin_088_irSender != NULL) diff --git a/src/_P097_Esp32Touch.ino b/src/_P097_Esp32Touch.ino index 84264130c..dbbe77d2e 100644 --- a/src/_P097_Esp32Touch.ino +++ b/src/_P097_Esp32Touch.ino @@ -31,8 +31,11 @@ // Share this bitmap among all instances of this plugin DRAM_ATTR uint32_t p097_pinTouched = 0; DRAM_ATTR uint32_t p097_pinTouchedPrev = 0; +#ifdef ESP32S2 +DRAM_ATTR uint32_t p097_timestamp[15] = { 0 }; +#else DRAM_ATTR uint32_t p097_timestamp[10] = { 0 }; - +#endif boolean Plugin_097(uint8_t function, struct EventStruct *event, String& string) { @@ -192,7 +195,9 @@ void P097_setEventParams(int pin, uint16_t threshold) { if (getADC_gpio_info(pin, adc, ch, t)) { switch (t) { +#ifndef ESP32S2 case 0: touchAttachInterrupt(T0, P097_got_T0, threshold); break; +#endif case 1: touchAttachInterrupt(T1, P097_got_T1, threshold); break; case 2: touchAttachInterrupt(T2, P097_got_T2, threshold); break; case 3: touchAttachInterrupt(T3, P097_got_T3, threshold); break; @@ -202,11 +207,22 @@ void P097_setEventParams(int pin, uint16_t threshold) { case 7: touchAttachInterrupt(T7, P097_got_T7, threshold); break; case 8: touchAttachInterrupt(T8, P097_got_T8, threshold); break; case 9: touchAttachInterrupt(T9, P097_got_T9, threshold); break; +#ifdef ESP32S2 +/* + case 10: touchAttachInterrupt(T10, P097_got_T10, threshold); break; + case 11: touchAttachInterrupt(T11, P097_got_T11, threshold); break; + case 12: touchAttachInterrupt(T12, P097_got_T12, threshold); break; + case 13: touchAttachInterrupt(T13, P097_got_T13, threshold); break; + case 14: touchAttachInterrupt(T14, P097_got_T14, threshold); break; +*/ +#endif } } } +#ifndef ESP32S2 void P097_got_T0() IRAM_ATTR; +#endif void P097_got_T1() IRAM_ATTR; void P097_got_T2() IRAM_ATTR; void P097_got_T3() IRAM_ATTR; @@ -216,12 +232,21 @@ void P097_got_T6() IRAM_ATTR; void P097_got_T7() IRAM_ATTR; void P097_got_T8() IRAM_ATTR; void P097_got_T9() IRAM_ATTR; +#ifdef ESP32S2 +void P097_got_T10() IRAM_ATTR; +void P097_got_T11() IRAM_ATTR; +void P097_got_T12() IRAM_ATTR; +void P097_got_T13() IRAM_ATTR; +void P097_got_T14() IRAM_ATTR; +#endif +#ifndef ESP32S2 void P097_got_T0() { bitSet(p097_pinTouched, 0); if (p097_timestamp[0] == 0) { p097_timestamp[0] = millis(); } } +#endif void P097_got_T1() { bitSet(p097_pinTouched, 1); @@ -277,6 +302,39 @@ void P097_got_T9() { if (p097_timestamp[9] == 0) { p097_timestamp[9] = millis(); } } +#ifdef ESP32S2 +void P097_got_T10() { + bitSet(p097_pinTouched, 10); + + if (p097_timestamp[10] == 0) { p097_timestamp[10] = millis(); } +} + +void P097_got_T11() { + bitSet(p097_pinTouched, 11); + + if (p097_timestamp[11] == 0) { p097_timestamp[11] = millis(); } +} + +void P097_got_T12() { + bitSet(p097_pinTouched, 12); + + if (p097_timestamp[12] == 0) { p097_timestamp[12] = millis(); } +} + +void P097_got_T13() { + bitSet(p097_pinTouched, 13); + + if (p097_timestamp[13] == 0) { p097_timestamp[13] = millis(); } +} + +void P097_got_T14() { + bitSet(p097_pinTouched, 14); + + if (p097_timestamp[14] == 0) { p097_timestamp[14] = millis(); } +} + +#endif + #endif // ifdef ESP32 diff --git a/src/_P100_DS2423_counter.ino b/src/_P100_DS2423_counter.ino index 549a40c33..1dcaa7411 100644 --- a/src/_P100_DS2423_counter.ino +++ b/src/_P100_DS2423_counter.ino @@ -61,7 +61,7 @@ boolean Plugin_100(uint8_t function, struct EventStruct *event, String& string) // Scan the onewire bus and fill dropdown list with devicecount on this GPIO. int8_t Plugin_100_DallasPin = CONFIG_PIN1; - if (Plugin_100_DallasPin != -1) { + if (validGpio(Plugin_100_DallasPin)) { Dallas_addr_selector_webform_load(event->TaskIndex, Plugin_100_DallasPin, Plugin_100_DallasPin); // Counter select @@ -112,7 +112,7 @@ boolean Plugin_100(uint8_t function, struct EventStruct *event, String& string) Dallas_plugin_get_addr(addr, event->TaskIndex); if (addr[0] != 0) { - if (CONFIG_PIN1 != -1) { + if (validGpio(CONFIG_PIN1)) { float value = 0; if (Dallas_readCounter(addr, &value, CONFIG_PIN1, CONFIG_PIN1, PCONFIG(0))) diff --git a/src/_P109_ThermOLED.ino b/src/_P109_ThermOLED.ino index b859ba523..c3996ebe9 100644 --- a/src/_P109_ThermOLED.ino +++ b/src/_P109_ThermOLED.ino @@ -233,7 +233,8 @@ boolean Plugin_109(byte function, struct EventStruct *event, String& string) { argName = F("Plugin_109_template"); argName += varNr + 1; - strncpy(P109_deviceTemplate[varNr], web_server.arg(argName).c_str(), sizeof(P109_deviceTemplate[varNr])); + strncpy(P109_deviceTemplate[varNr], web_server.arg(argName).c_str(), sizeof(P109_deviceTemplate[varNr]) - 1); + P109_deviceTemplate[varNr][sizeof(P109_deviceTemplate[varNr]) - 1] = 0; } SaveCustomTaskSettings(event->TaskIndex, reinterpret_cast(&P109_deviceTemplate), sizeof(P109_deviceTemplate)); @@ -279,17 +280,17 @@ boolean Plugin_109(byte function, struct EventStruct *event, String& string) logstr += Settings.TaskDevicePin3[event->TaskIndex]; addLog(LOG_LEVEL_INFO, logstr); - if (Settings.TaskDevicePin1[event->TaskIndex] != -1) + if (validGpio(Settings.TaskDevicePin1[event->TaskIndex]) ) { pinMode(Settings.TaskDevicePin1[event->TaskIndex], INPUT_PULLUP); } - if (Settings.TaskDevicePin2[event->TaskIndex] != -1) + if (validGpio(Settings.TaskDevicePin2[event->TaskIndex]) ) { pinMode(Settings.TaskDevicePin2[event->TaskIndex], INPUT_PULLUP); } - if (Settings.TaskDevicePin3[event->TaskIndex] != -1) + if (validGpio(Settings.TaskDevicePin3[event->TaskIndex]) ) { pinMode(Settings.TaskDevicePin3[event->TaskIndex], INPUT_PULLUP); } @@ -356,7 +357,7 @@ boolean Plugin_109(byte function, struct EventStruct *event, String& string) unsigned long current_time; if (Plugin_109_init) { - if (Settings.TaskDevicePin1[event->TaskIndex] != -1) + if (validGpio(Settings.TaskDevicePin1[event->TaskIndex]) ) { if (!digitalRead(Settings.TaskDevicePin1[event->TaskIndex])) { @@ -388,7 +389,7 @@ boolean Plugin_109(byte function, struct EventStruct *event, String& string) } } - if (Settings.TaskDevicePin2[event->TaskIndex] != -1) + if (validGpio(Settings.TaskDevicePin2[event->TaskIndex]) ) { if (!digitalRead(Settings.TaskDevicePin2[event->TaskIndex])) { @@ -420,7 +421,7 @@ boolean Plugin_109(byte function, struct EventStruct *event, String& string) } } - if (Settings.TaskDevicePin3[event->TaskIndex] != -1) + if (validGpio(Settings.TaskDevicePin3[event->TaskIndex]) ) { if (!digitalRead(Settings.TaskDevicePin3[event->TaskIndex])) { diff --git a/src/_Plugin_Helper.h b/src/_Plugin_Helper.h index 2dea469ab..d7cad7fd2 100644 --- a/src/_Plugin_Helper.h +++ b/src/_Plugin_Helper.h @@ -31,6 +31,7 @@ #include "src/Helpers/ESPEasy_Storage.h" #include "src/Helpers/ESPEasy_time_calc.h" #include "src/Helpers/I2C_access.h" +#include "src/Helpers/Hardware.h" #include "src/Helpers/Misc.h" #include "src/Helpers/Numerical.h" #include "src/Helpers/PortStatus.h" diff --git a/src/src/CustomBuild/ESPEasyLimits.h b/src/src/CustomBuild/ESPEasyLimits.h index 56e0b72a9..fe6dcb2a5 100644 --- a/src/src/CustomBuild/ESPEasyLimits.h +++ b/src/src/CustomBuild/ESPEasyLimits.h @@ -33,7 +33,11 @@ #define TASKS_MAX 32 #endif #ifndef MAX_GPIO - #define MAX_GPIO 39 + #ifdef ESP32S2 + #define MAX_GPIO 46 + #else + #define MAX_GPIO 39 + #endif #endif #endif diff --git a/src/src/CustomBuild/ESPEasy_buildinfo.h b/src/src/CustomBuild/ESPEasy_buildinfo.h index 6a1917bc6..e2bc62c60 100644 --- a/src/src/CustomBuild/ESPEasy_buildinfo.h +++ b/src/src/CustomBuild/ESPEasy_buildinfo.h @@ -26,7 +26,13 @@ # define BUILD_NOTES " - Mega" #endif // if defined(ESP8266) #if defined(ESP32) - # define BUILD_NOTES " - Mega32" + #if defined(ESP32S2) + # define BUILD_NOTES " - Mega32-s2" + #elif defined(ESP32C2) + # define BUILD_NOTES " - Mega32-c3" + #else + # define BUILD_NOTES " - Mega32" + #endif #endif // if defined(ESP32) #endif diff --git a/src/src/DataStructs/ESPEasy_EventStruct.h b/src/src/DataStructs/ESPEasy_EventStruct.h index 8f602a8df..f21009022 100644 --- a/src/src/DataStructs/ESPEasy_EventStruct.h +++ b/src/src/DataStructs/ESPEasy_EventStruct.h @@ -63,9 +63,9 @@ public: taskIndex_t TaskIndex = INVALID_TASK_INDEX; // index position in TaskSettings array, 0-11 controllerIndex_t ControllerIndex = INVALID_CONTROLLER_INDEX; // index position in Settings.Controller, 0-3 notifierIndex_t NotificationIndex = INVALID_NOTIFIER_INDEX; // index position in Settings.Notification, 0-3 - uint8_t BaseVarIndex = 0; + uint8_t BaseVarIndex = 0; Sensor_VType sensorType = Sensor_VType::SENSOR_TYPE_NOT_SET; - uint8_t OriginTaskIndex = 0; + uint8_t OriginTaskIndex = 0; }; #endif // ESPEASY_EVENTSTRUCT_H diff --git a/src/src/DataStructs/NodeStruct.cpp b/src/src/DataStructs/NodeStruct.cpp index 31f15a1c7..ef94692e6 100644 --- a/src/src/DataStructs/NodeStruct.cpp +++ b/src/src/DataStructs/NodeStruct.cpp @@ -6,6 +6,8 @@ const __FlashStringHelper * getNodeTypeDisplayString(uint8_t nodeType) { case NODE_TYPE_ID_ESP_EASY_STD: return F("ESP Easy"); case NODE_TYPE_ID_ESP_EASYM_STD: return F("ESP Easy Mega"); case NODE_TYPE_ID_ESP_EASY32_STD: return F("ESP Easy 32"); + case NODE_TYPE_ID_ESP_EASY32S2_STD: return F("ESP Easy 32-s2"); + case NODE_TYPE_ID_ESP_EASY32C3_STD: return F("ESP Easy 32-c3"); case NODE_TYPE_ID_RPI_EASY_STD: return F("RPI Easy"); case NODE_TYPE_ID_ARDUINO_EASY_STD: return F("Arduino Easy"); case NODE_TYPE_ID_NANO_EASY_STD: return F("Nano Easy"); diff --git a/src/src/DataStructs/NodeStruct.h b/src/src/DataStructs/NodeStruct.h index 86bd888b5..436591540 100644 --- a/src/src/DataStructs/NodeStruct.h +++ b/src/src/DataStructs/NodeStruct.h @@ -10,6 +10,8 @@ #define NODE_TYPE_ID_RPI_EASY_STD 5 // https://github.com/enesbcs/rpieasy #define NODE_TYPE_ID_ESP_EASYM_STD 17 #define NODE_TYPE_ID_ESP_EASY32_STD 33 +#define NODE_TYPE_ID_ESP_EASY32S2_STD 34 +#define NODE_TYPE_ID_ESP_EASY32C3_STD 35 #define NODE_TYPE_ID_ARDUINO_EASY_STD 65 #define NODE_TYPE_ID_NANO_EASY_STD 81 @@ -25,8 +27,8 @@ struct NodeStruct String nodeName; IPAddress ip; uint16_t build; - uint8_t age; - uint8_t nodeType; + uint8_t age; + uint8_t nodeType; uint16_t webgui_portnumber; }; typedef std::map NodesMap; diff --git a/src/src/DataStructs/RTC_cache_handler_struct.h b/src/src/DataStructs/RTC_cache_handler_struct.h index 7ef6feef0..9717e6522 100644 --- a/src/src/DataStructs/RTC_cache_handler_struct.h +++ b/src/src/DataStructs/RTC_cache_handler_struct.h @@ -7,6 +7,7 @@ #include "../../ESPEasy_common.h" #include +#include // Locations where to store the cached data diff --git a/src/src/DataStructs/UserVarStruct.h b/src/src/DataStructs/UserVarStruct.h index e97cf5dc2..2b3ee171b 100644 --- a/src/src/DataStructs/UserVarStruct.h +++ b/src/src/DataStructs/UserVarStruct.h @@ -5,6 +5,8 @@ #include "../DataTypes/TaskIndex.h" +#include + struct UserVarStruct { UserVarStruct(); diff --git a/src/src/DataStructs/WiFiEventData.cpp b/src/src/DataStructs/WiFiEventData.cpp index 0aafaf489..478ad9382 100644 --- a/src/src/DataStructs/WiFiEventData.cpp +++ b/src/src/DataStructs/WiFiEventData.cpp @@ -127,7 +127,7 @@ void WiFiEventData_t::setWiFiConnected() { } void WiFiEventData_t::setWiFiServicesInitialized() { - if (!unprocessedWifiEvents()) { + if (!unprocessedWifiEvents() && WiFiConnected() && WiFiGotIP()) { addLog(LOG_LEVEL_DEBUG, F("WiFi : WiFi services initialized")); bitSet(wifiStatus, ESPEASY_WIFI_SERVICES_INITIALIZED); wifiConnectInProgress = false; diff --git a/src/src/DataTypes/SPI_options.cpp b/src/src/DataTypes/SPI_options.cpp index 32e931d40..bab3f6788 100644 --- a/src/src/DataTypes/SPI_options.cpp +++ b/src/src/DataTypes/SPI_options.cpp @@ -12,6 +12,7 @@ const __FlashStringHelper* getSPI_optionToString(SPI_Options_e option) { case SPI_Options_e::UserDefined: return F("User-defined: CLK, MISO, MOSI GPIO-pins"); } + return F("Unknown"); } const __FlashStringHelper* getSPI_optionToShortString(SPI_Options_e option) { @@ -25,6 +26,7 @@ const __FlashStringHelper* getSPI_optionToShortString(SPI_Options_e option) { case SPI_Options_e::UserDefined: return F("User-defined SPI"); } + return F("Unknown"); } #endif // ifdef ESP32 diff --git a/src/src/ESPEasyCore/ESPEasyEth.cpp b/src/src/ESPEasyCore/ESPEasyEth.cpp index b466399a4..98b67d274 100644 --- a/src/src/ESPEasyCore/ESPEasyEth.cpp +++ b/src/src/ESPEasyCore/ESPEasyEth.cpp @@ -2,6 +2,7 @@ #ifdef HAS_ETHERNET +#include "../CustomBuild/ESPEasyLimits.h" #include "../ESPEasyCore/ESPEasyNetwork.h" #include "../ESPEasyCore/ESPEasy_Log.h" #include "../Globals/ESPEasyWiFiEvent.h" diff --git a/src/src/ESPEasyCore/ESPEasyGPIO.cpp b/src/src/ESPEasyCore/ESPEasyGPIO.cpp index 0801f9454..36daebf50 100644 --- a/src/src/ESPEasyCore/ESPEasyGPIO.cpp +++ b/src/src/ESPEasyCore/ESPEasyGPIO.cpp @@ -484,11 +484,7 @@ bool checkValidPortRange(pluginID_t pluginID, int port) switch (pluginID) { case PLUGIN_GPIO: - { - int pinnr = -1; - bool input, output, warning; - return getGpioInfo(port, pinnr, input, output, warning); - } + return validGpio(port); case PLUGIN_MCP: case PLUGIN_PCF: diff --git a/src/src/ESPEasyCore/ESPEasyWiFiEvent.cpp b/src/src/ESPEasyCore/ESPEasyWiFiEvent.cpp index 37e6c4980..8691ab139 100644 --- a/src/src/ESPEasyCore/ESPEasyWiFiEvent.cpp +++ b/src/src/ESPEasyCore/ESPEasyWiFiEvent.cpp @@ -55,9 +55,139 @@ static bool ignoreDisconnectEvent = false; #if ESP_IDF_VERSION_MAJOR > 3 void WiFiEvent(WiFiEvent_t event, WiFiEventInfo_t info) { + switch (event) { + case ARDUINO_EVENT_WIFI_READY: + // ESP32 WiFi ready + break; + case ARDUINO_EVENT_WIFI_STA_START: + addLog(LOG_LEVEL_INFO, F("WiFi : STA Started")); + break; + case ARDUINO_EVENT_WIFI_STA_STOP: + addLog(LOG_LEVEL_INFO, F("WiFi : STA Stopped")); + break; + case ARDUINO_EVENT_WIFI_AP_START: + addLog(LOG_LEVEL_INFO, F("WiFi : AP Started")); + break; + case ARDUINO_EVENT_WIFI_AP_STOP: + addLog(LOG_LEVEL_INFO, F("WiFi : AP Stopped")); + break; + case ARDUINO_EVENT_WIFI_STA_LOST_IP: + // ESP32 station lost IP and the IP is reset to 0 + #ifdef HAS_ETHERNET + if (active_network_medium == NetworkMedium_t::Ethernet) { + EthEventData.markLostIP(); + } + else + #endif + WiFiEventData.markLostIP(); + addLog(LOG_LEVEL_INFO, + active_network_medium == NetworkMedium_t::Ethernet ? + F("ETH : Lost IP") : F("WiFi : Lost IP")); + break; + + case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED: + // Receive probe request packet in soft-AP interface + // TODO TD-er: Must implement like onProbeRequestAPmode for ESP8266 + addLog(LOG_LEVEL_INFO, F("WiFi : AP got probed")); + break; + + case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE: + #if ESP_IDF_VERSION_MAJOR > 3 + WiFiEventData.setAuthMode(info.wifi_sta_authmode_change.new_mode); + #else + WiFiEventData.setAuthMode(info.auth_change.new_mode); + #endif + break; + + case ARDUINO_EVENT_WIFI_STA_CONNECTED: + { + char ssid_copy[33] = { 0 }; // Ensure space for maximum len SSID (32) plus trailing 0 + #if ESP_IDF_VERSION_MAJOR > 3 + memcpy(ssid_copy, info.wifi_sta_connected.ssid, info.wifi_sta_connected.ssid_len); + ssid_copy[32] = 0; // Potentially add 0-termination if none present earlier + WiFiEventData.markConnected((const char*) ssid_copy, info.wifi_sta_connected.bssid, info.wifi_sta_connected.channel); + #else + memcpy(ssid_copy, info.connected.ssid, info.connected.ssid_len); + ssid_copy[32] = 0; // Potentially add 0-termination if none present earlier + WiFiEventData.markConnected((const char*) ssid_copy, info.connected.bssid, info.connected.channel); + #endif + break; + } + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: + if (!ignoreDisconnectEvent) { + ignoreDisconnectEvent = true; + #if ESP_IDF_VERSION_MAJOR > 3 + WiFiEventData.markDisconnect(static_cast(info.wifi_sta_disconnected.reason)); + #else + WiFiEventData.markDisconnect(static_cast(info.disconnected.reason)); + #endif + WiFi.persistent(false); + WiFi.disconnect(true); + } + break; + case ARDUINO_EVENT_WIFI_STA_GOT_IP: + ignoreDisconnectEvent = false; + WiFiEventData.markGotIP(); + break; + case ARDUINO_EVENT_WIFI_AP_STACONNECTED: + #if ESP_IDF_VERSION_MAJOR > 3 + WiFiEventData.markConnectedAPmode(info.wifi_ap_staconnected.mac); + #else + WiFiEventData.markConnectedAPmode(info.sta_connected.mac); + #endif + break; + case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED: + #if ESP_IDF_VERSION_MAJOR > 3 + WiFiEventData.markDisconnectedAPmode(info.wifi_ap_stadisconnected.mac); + #else + WiFiEventData.markDisconnectedAPmode(info.sta_disconnected.mac); + #endif + break; + case ARDUINO_EVENT_WIFI_SCAN_DONE: + WiFiEventData.processedScanDone = false; + break; +#ifdef HAS_ETHERNET + case ARDUINO_EVENT_ETH_START: + if (ethPrepare()) { + addLog(LOG_LEVEL_INFO, F("ETH : Started")); + } else { + addLog(LOG_LEVEL_ERROR, F("ETH : Could not prepare ETH!")); + } + break; + case ARDUINO_EVENT_ETH_CONNECTED: + addLog(LOG_LEVEL_INFO, F("ETH : Connected")); + EthEventData.markConnected(); + break; + case ARDUINO_EVENT_ETH_GOT_IP: + EthEventData.markGotIP(); + addLog(LOG_LEVEL_INFO, F("ETH : Got IP")); + break; + case ARDUINO_EVENT_ETH_DISCONNECTED: + addLog(LOG_LEVEL_ERROR, F("ETH Disconnected")); + EthEventData.markDisconnect(); + break; + case ARDUINO_EVENT_ETH_STOP: + addLog(LOG_LEVEL_INFO, F("ETH Stopped")); + break; + #if ESP_IDF_VERSION_MAJOR > 3 + case ARDUINO_EVENT_ETH_GOT_IP6: + #else + case ARDUINO_EVENT_GOT_IP6: + #endif + addLog(LOG_LEVEL_INFO, F("ETH Got IP6")); + break; +#endif //HAS_ETHERNET + default: + { + String log = F("UNKNOWN WIFI/ETH EVENT: "); + log += event; + addLog(LOG_LEVEL_ERROR, log); + } + break; + } +} #else void WiFiEvent(system_event_id_t event, system_event_info_t info) { -#endif switch (event) { case SYSTEM_EVENT_WIFI_READY: // ESP32 WiFi ready @@ -186,6 +316,8 @@ void WiFiEvent(system_event_id_t event, system_event_info_t info) { } } +#endif + #endif // ifdef ESP32 #ifdef ESP8266 diff --git a/src/src/ESPEasyCore/ESPEasyWifi.cpp b/src/src/ESPEasyCore/ESPEasyWifi.cpp index 71c7d342a..717573a31 100644 --- a/src/src/ESPEasyCore/ESPEasyWifi.cpp +++ b/src/src/ESPEasyCore/ESPEasyWifi.cpp @@ -21,10 +21,13 @@ #include "../Helpers/StringConverter.h" #include "../Helpers/StringGenerator_WiFi.h" +#ifdef ESP32 +#include +#endif + // FIXME TD-er: Cleanup of WiFi code #ifdef ESPEASY_WIFI_CLEANUP_WORK_IN_PROGRESS bool ESPEasyWiFi_t::begin() { - return true; } @@ -749,6 +752,13 @@ void WifiDisconnect() #ifdef ESP32 WiFi.disconnect(); WiFi.removeEvent(wm_event_id); + { + const IPAddress ip; + const IPAddress gw; + const IPAddress subnet; + const IPAddress dns; + WiFi.config(ip, gw, subnet, dns); + } #endif #ifdef ESP8266 // Only call disconnect when STA is active @@ -1105,6 +1115,7 @@ void setWifiMode(WiFiMode_t wifimode) { if (wifimode == WIFI_OFF) { + WifiDisconnect(); WiFiEventData.markWiFiTurnOn(); delay(100); #if defined(ESP32) diff --git a/src/src/ESPEasyCore/ESPEasy_setup.cpp b/src/src/ESPEasyCore/ESPEasy_setup.cpp index 459aded02..2f23ca608 100644 --- a/src/src/ESPEasyCore/ESPEasy_setup.cpp +++ b/src/src/ESPEasyCore/ESPEasy_setup.cpp @@ -99,6 +99,9 @@ void ESPEasy_setup() initWiFi(); run_compiletime_checks(); +#ifdef ESP32_ENABLE_PSRAM + psramInit(); +#endif #ifndef BUILD_NO_RAM_TRACKER lowestFreeStack = getFreeStackWatermark(); lowestRAM = FreeMem(); @@ -134,6 +137,12 @@ void ESPEasy_setup() #ifndef BUILD_NO_RAM_TRACKER logMemUsageAfter(F("initLog()")); #endif + #ifdef ESP32_ENABLE_PSRAM + if (psramFound()) { + addLog(LOG_LEVEL_INFO, F("Found PSRAM")); + } + #endif + if (SpiffsSectors() < 32) diff --git a/src/src/Helpers/ESPEasy_checks.cpp b/src/src/Helpers/ESPEasy_checks.cpp index ef7b66cf9..849f0e3e3 100644 --- a/src/src/Helpers/ESPEasy_checks.cpp +++ b/src/src/Helpers/ESPEasy_checks.cpp @@ -82,18 +82,35 @@ void run_compiletime_checks() { check_size(); #endif check_size(); + #if ESP_IDF_VERSION_MAJOR > 3 + // String class has increased with 4 bytes + check_size(); // Is not stored + #else check_size(); // Is not stored + #endif + // LogStruct is mainly dependent on the number of lines. // Has to be round up to multiple of 4. + #if ESP_IDF_VERSION_MAJOR > 3 + // String class has increased with 4 bytes + const unsigned int LogStructSize = ((12u + 21 * LOG_STRUCT_MESSAGE_LINES) + 3) & ~3; + #else const unsigned int LogStructSize = ((12u + 17 * LOG_STRUCT_MESSAGE_LINES) + 3) & ~3; + #endif check_size(); // Is not stored check_size(); // Is not stored check_size(); #ifdef USES_NOTIFIER check_size(); #endif + #if ESP_IDF_VERSION_MAJOR > 3 + // String class has increased with 4 bytes + check_size(); + #else check_size(); + #endif + check_size(); check_size(); check_size(); diff --git a/src/src/Helpers/ESPEasy_time.h b/src/src/Helpers/ESPEasy_time.h index b569bb7b3..b4b81e321 100644 --- a/src/src/Helpers/ESPEasy_time.h +++ b/src/src/Helpers/ESPEasy_time.h @@ -5,7 +5,7 @@ #include "../DataTypes/ESPEasyTimeSource.h" - +#include class ESPEasy_time { public: diff --git a/src/src/Helpers/Hardware.cpp b/src/src/Helpers/Hardware.cpp index cd106ca6b..4f5786f42 100644 --- a/src/src/Helpers/Hardware.cpp +++ b/src/src/Helpers/Hardware.cpp @@ -1,6 +1,7 @@ #include "Hardware.h" #include "../Commands/GPIO.h" +#include "../CustomBuild/ESPEasyLimits.h" #include "../DataTypes/SPI_options.h" #include "../ESPEasyCore/ESPEasyGPIO.h" #include "../ESPEasyCore/ESPEasy_Log.h" @@ -18,6 +19,7 @@ #include "../Helpers/PortStatus.h" #include "../Helpers/StringConverter.h" + //#include "../../ESPEasy-Globals.h" #ifdef ESP32 @@ -33,7 +35,7 @@ void hardwareInit() // set GPIO pins state if not set to default bool hasPullUp, hasPullDown; - for (int gpio = 0; gpio <= PIN_D_MAX; ++gpio) { + for (int gpio = 0; gpio <= MAX_GPIO; ++gpio) { const bool serialPinConflict = (Settings.UseSerial && (gpio == 1 || gpio == 3)); if (!serialPinConflict) { const uint32_t key = createKey(1, gpio); @@ -183,30 +185,33 @@ void initI2C() { // configure hardware pins according to eeprom settings. if (Settings.isI2CEnabled()) { - addLog(LOG_LEVEL_INFO, F("INIT : I2C")); - I2CSelectClockSpeed(false); // Set normal clock speed - Wire.begin(Settings.Pin_i2c_sda, Settings.Pin_i2c_scl); + return; + } + addLog(LOG_LEVEL_INFO, F("INIT : I2C")); + I2CSelectClockSpeed(false); // Set normal clock speed - if (Settings.WireClockStretchLimit) - { - if (loglevelActiveFor(LOG_LEVEL_INFO)) { - String log = F("INIT : I2C custom clockstretchlimit:"); - log += Settings.WireClockStretchLimit; - addLog(LOG_LEVEL_INFO, log); - } - #if defined(ESP8266) - Wire.setClockStretchLimit(Settings.WireClockStretchLimit); - #endif // if defined(ESP8266) + if (Settings.WireClockStretchLimit) + { + if (loglevelActiveFor(LOG_LEVEL_INFO)) { + String log = F("INIT : I2C custom clockstretchlimit:"); + log += Settings.WireClockStretchLimit; + addLog(LOG_LEVEL_INFO, log); } + #if defined(ESP8266) + Wire.setClockStretchLimit(Settings.WireClockStretchLimit); + #endif // if defined(ESP8266) + #ifdef ESP32S2 + Wire.setTimeOut(Settings.WireClockStretchLimit); + #endif + } #ifdef FEATURE_I2CMULTIPLEXER - if (Settings.I2C_Multiplexer_ResetPin != -1) { // Initialize Reset pin to High if configured - pinMode(Settings.I2C_Multiplexer_ResetPin, OUTPUT); - digitalWrite(Settings.I2C_Multiplexer_ResetPin, HIGH); - } -#endif // ifdef FEATURE_I2CMULTIPLEXER + if (validGpio(Settings.I2C_Multiplexer_ResetPin)) { // Initialize Reset pin to High if configured + pinMode(Settings.I2C_Multiplexer_ResetPin, OUTPUT); + digitalWrite(Settings.I2C_Multiplexer_ResetPin, HIGH); } +#endif // ifdef FEATURE_I2CMULTIPLEXER // I2C Watchdog boot status check if (Settings.WDI2CAddress != 0) @@ -239,8 +244,13 @@ void I2CSelectClockSpeed(bool setLowSpeed) { // No need to change the clock speed. return; } - lastI2CClockSpeed = newI2CClockSpeed; + lastI2CClockSpeed = newI2CClockSpeed; + #ifdef ESP32 + Wire.begin(Settings.Pin_i2c_sda, Settings.Pin_i2c_scl, newI2CClockSpeed); + #else + Wire.begin(Settings.Pin_i2c_sda, Settings.Pin_i2c_scl); Wire.setClock(newI2CClockSpeed); + #endif } #ifdef FEATURE_I2CMULTIPLEXER @@ -397,7 +407,9 @@ int espeasy_analogRead(int pin, bool readAsTouch) { switch (adc) { case 0: + #ifndef ESP32S2 value = hallRead(); + #endif break; case 1: canread = true; @@ -512,6 +524,9 @@ uint8_t getChipCores() { const __FlashStringHelper * getChipModel() { #ifdef ESP32 + #ifdef ESP32S2 + return F("ESP32S2"); + #else { uint32_t chip_ver = REG_GET_FIELD(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_VER_PKG); uint32_t pkg_ver = chip_ver & 0x7; @@ -530,6 +545,7 @@ const __FlashStringHelper * getChipModel() { break; } } + #endif #elif defined(ESP8285) return F("ESP8285"); #elif defined(ESP8266) @@ -581,18 +597,28 @@ void readBootCause() { switch (rtc_get_reset_reason(0)) { case NO_MEAN: break; case POWERON_RESET: lastBootCause = BOOT_CAUSE_MANUAL_REBOOT; break; + #ifndef ESP32S2 case SW_RESET: lastBootCause = BOOT_CAUSE_SOFT_RESTART; break; case OWDT_RESET: lastBootCause = BOOT_CAUSE_SW_WATCHDOG; break; + #endif case DEEPSLEEP_RESET: lastBootCause = BOOT_CAUSE_DEEP_SLEEP; break; + #ifndef ESP32S2 case SDIO_RESET: lastBootCause = BOOT_CAUSE_MANUAL_REBOOT; break; + #endif case TG0WDT_SYS_RESET: case TG1WDT_SYS_RESET: + #ifndef ESP32S2 case RTCWDT_SYS_RESET: lastBootCause = BOOT_CAUSE_EXT_WD; break; - case INTRUSION_RESET: - case TGWDT_CPU_RESET: - case SW_CPU_RESET: lastBootCause = BOOT_CAUSE_SOFT_RESTART; break; // Both call to ESP.reset() and on exception crash + #endif + #ifndef ESP32S2 + case SW_CPU_RESET: + case TGWDT_CPU_RESET: + #endif + case INTRUSION_RESET: lastBootCause = BOOT_CAUSE_SOFT_RESTART; break; // Both call to ESP.reset() and on exception crash case RTCWDT_CPU_RESET: lastBootCause = BOOT_CAUSE_EXT_WD; break; + #ifndef ESP32S2 case EXT_CPU_RESET: lastBootCause = BOOT_CAUSE_MANUAL_REBOOT; break; // reset button or cold boot, only for core 1 + #endif case RTCWDT_BROWN_OUT_RESET: lastBootCause = BOOT_CAUSE_POWER_UNSTABLE; break; case RTCWDT_RTC_RESET: lastBootCause = BOOT_CAUSE_COLD_BOOT; break; } @@ -827,11 +853,86 @@ void addPredefinedRules(const GpioFactorySettingsStruct& gpio_settings) { #ifdef ESP32 // ******************************************************************************** -// Get info of a specific GPIO pin. +// Get info of a specific GPIO pin // ******************************************************************************** bool getGpioInfo(int gpio, int& pinnr, bool& input, bool& output, bool& warning) { pinnr = -1; // ESP32 does not label the pins, they just use the GPIO number. +#ifdef ESP32S2 + + // Input GPIOs: 0-21, 26, 33-46 + // Output GPIOs: 0-21, 26, 33-45 + input = gpio <= 46; + output = gpio <= 45; + + if ((gpio < 0) || ((gpio > 21) && (gpio < 26)) || ((gpio > 26) && (gpio < 33))) { + input = false; + output = false; + } + + if (gpio == 26) { + // Pin shared with the flash memory and/or PSRAM. + // Cannot be used as regular GPIO + input = false; + output = false; + warning = true; + } + + if ((gpio > 26) && (gpio < 33)) { + // SPIHD, SPIWP, SPICS0, SPICLK, SPIQ, SPID pins of ESP32-S2FH2 and ESP32-S2FH4 + // are connected to embedded flash and not recommended for other uses. + warning = true; + } + + + if ((input == false) && (output == false)) { + return false; + } + + if (gpio == 45) { + // VDD_SPI can work as the power supply for the external device at either + // 1.8 V (when GPIO45 is 1 during boot), or + // 3.3 V (when GPIO45 is 0 and at default state during boot). + warning = true; + } + + // GPIO 0 State during boot determines boot mode. + warning = gpio == 0; + + + if (gpio == 46) { + // Part of the boot strapping pins. + warning = true; + } + +/* + # ifdef HAS_ETHERNET + + // Check pins used for RMII Ethernet PHY + if (NetworkMedium_t::Ethernet == Settings.NetworkMedium) { + switch (gpio) { + case 0: + case 21: + case 19: + case 22: + case 25: + case 26: + case 27: + warning = true; + break; + } + + + // FIXME TD-er: Must we also check for pins used for MDC/MDIO and Eth PHY power? + } + + + # endif // ifdef HAS_ETHERNET + +*/ +#else + // ESP32 classic + // Input GPIOs: 0-19, 21-23, 25-27, 32-39 // Output GPIOs: 0-19, 21-23, 25-27, 32-33 input = gpio <= 39; @@ -899,6 +1000,8 @@ bool getGpioInfo(int gpio, int& pinnr, bool& input, bool& output, bool& warning) # endif // ifdef HAS_ETHERNET + +#endif return true; } @@ -913,6 +1016,14 @@ bool getGpioPullResistor(int gpio, bool& hasPullUp, bool& hasPullDown) { if (!getGpioInfo(gpio, pinnr, input, output, warning)) { return false; } + +#ifdef ESP32S2 + if (gpio <= 45) { + hasPullUp = true; + hasPullDown = true; + } +#else + // ESP32 classic if (gpio >= 34) { // For GPIO 34 .. 39, no pull-up nor pull-down. } else if (gpio == 12) { @@ -923,9 +1034,10 @@ bool getGpioPullResistor(int gpio, bool& hasPullUp, bool& hasPullDown) { hasPullUp = true; hasPullDown = true; } + +#endif return true; } - #endif #ifdef ESP8266 @@ -996,11 +1108,7 @@ bool getGpioPullResistor(int gpio, bool& hasPullUp, bool& hasPullDown) { hasPullDown = false; hasPullUp = false; - int pinnr; - bool input; - bool output; - bool warning; - if (!getGpioInfo(gpio, pinnr, input, output, warning)) { + if (!validGpio(gpio)) { return false; } if (gpio == 16) { @@ -1013,6 +1121,15 @@ bool getGpioPullResistor(int gpio, bool& hasPullUp, bool& hasPullDown) { #endif +bool validGpio(int gpio) { + if (gpio < 0 || gpio > MAX_GPIO) return false; + int pinnr; + bool input; + bool output; + bool warning; + return getGpioInfo(gpio, pinnr, input, output, warning); +} + #ifdef ESP32 @@ -1025,6 +1142,33 @@ bool getADC_gpio_info(int gpio_pin, int& adc, int& ch, int& t) { t = -1; +#ifdef ESP32S2 + switch (gpio_pin) { + case 1 : adc = 1; ch = 0; t = 1; break; + case 2 : adc = 1; ch = 1; t = 2; break; + case 3 : adc = 1; ch = 2; t = 3; break; + case 4 : adc = 1; ch = 3; t = 4; break; + case 5 : adc = 1; ch = 4; t = 5; break; + case 6 : adc = 1; ch = 5; t = 6; break; + case 7 : adc = 1; ch = 6; t = 7; break; + case 8 : adc = 1; ch = 7; t = 8; break; + case 9 : adc = 1; ch = 8; t = 9; break; + case 10 : adc = 1; ch = 9; t = 10; break; + case 11 : adc = 2; ch = 0; t = 11; break; + case 12 : adc = 2; ch = 1; t = 12; break; + case 13 : adc = 2; ch = 2; t = 13; break; + case 14 : adc = 2; ch = 3; t = 14; break; + case 15 : adc = 2; ch = 4; break; + case 16 : adc = 2; ch = 5; break; + case 17 : adc = 2; ch = 6; break; + case 18 : adc = 2; ch = 7; break; + case 19 : adc = 2; ch = 8; break; + case 20 : adc = 2; ch = 9; break; + default: + return false; + } +#else + // Classic ESP32 switch (gpio_pin) { case -1: adc = 0; break; // Hall effect Sensor case 36: adc = 1; ch = 0; break; @@ -1048,11 +1192,33 @@ bool getADC_gpio_info(int gpio_pin, int& adc, int& ch, int& t) default: return false; } +#endif return true; } int touchPinToGpio(int touch_pin) { +#ifdef ESP32S2 + switch (touch_pin) { + case 1: return T1; + case 2: return T2; + case 3: return T3; + case 4: return T4; + case 5: return T5; + case 6: return T6; + case 7: return T7; + case 8: return T8; + case 9: return T9; + case 10: return T10; + case 11: return T11; + case 12: return T12; + case 13: return T13; + case 14: return T14; + default: + break; + } +#else + // ESP32 classic switch (touch_pin) { case 0: return T0; case 1: return T1; @@ -1067,6 +1233,7 @@ int touchPinToGpio(int touch_pin) default: break; } +#endif return -1; } diff --git a/src/src/Helpers/Hardware.h b/src/src/Helpers/Hardware.h index 340aa5561..703a5d00c 100644 --- a/src/src/Helpers/Hardware.h +++ b/src/src/Helpers/Hardware.h @@ -113,6 +113,8 @@ bool getGpioInfo(int gpio, int& pinnr, bool& input, bool& output, bool& warning) bool getGpioPullResistor(int gpio, bool& hasPullUp, bool& hasPullDown); +bool validGpio(int gpio); + #ifdef ESP32 diff --git a/src/src/Helpers/Network.cpp b/src/src/Helpers/Network.cpp index 1b5a1b1d0..82a54f188 100644 --- a/src/src/Helpers/Network.cpp +++ b/src/src/Helpers/Network.cpp @@ -20,7 +20,7 @@ void statusLED(bool traffic) static int gnStatusValueCurrent = -1; static long int gnLastUpdate = millis(); - if (Settings.Pin_status_led == -1) { + if (!validGpio(Settings.Pin_status_led)) { return; } diff --git a/src/src/Helpers/StringGenerator_System.cpp b/src/src/Helpers/StringGenerator_System.cpp index ce4e18a88..c74ce4f91 100644 --- a/src/src/Helpers/StringGenerator_System.cpp +++ b/src/src/Helpers/StringGenerator_System.cpp @@ -52,39 +52,85 @@ const __FlashStringHelper * getLastBootCauseString() { } #ifdef ESP32 + #ifdef ESP32S2 + #include + #else + #include + #endif -#include // See https://github.com/espressif/esp-idf/blob/master/components/esp32/include/rom/rtc.h String getResetReasonString(uint8_t icore) { bool isDEEPSLEEP_RESET(false); + #ifdef ESP32S2 + + // See tools\sdk\esp32\include\esp_rom\include\esp32s2\rom\rtc.h + switch (rtc_get_reset_reason(icore)) { + case POWERON_RESET: return F("Vbat power on reset"); // 1 + case RTC_SW_SYS_RESET: return F("Software reset digital core"); // 3 + case DEEPSLEEP_RESET: isDEEPSLEEP_RESET = true; break; // 5 + case TG0WDT_SYS_RESET: return F("Timer Group0 Watch dog reset digital core"); // 7 + case TG1WDT_SYS_RESET: return F("Timer Group1 Watch dog reset digital core"); // 8 + case RTCWDT_SYS_RESET: return F("RTC Watch dog Reset digital core"); // 9 + case INTRUSION_RESET: return F("Instrusion tested to reset CPU"); // 10 + case TG0WDT_CPU_RESET: return F("Time Group0 reset CPU"); // 11 + case RTC_SW_CPU_RESET: return F("Software reset CPU"); // 12 + case RTCWDT_CPU_RESET: return F("RTC Watch dog Reset CPU"); // 13 + case RTCWDT_BROWN_OUT_RESET: return F("Reset when the vdd voltage is not stable"); // 15 + case RTCWDT_RTC_RESET: return F("RTC Watch dog reset digital core and rtc module"); // 16 + case TG1WDT_CPU_RESET: return F("Time Group1 reset CPU"); // 17 + case SUPER_WDT_RESET: return F("Super watchdog reset digital core and rtc module"); // 18 + case GLITCH_RTC_RESET: return F("Glitch reset digital core and rtc module"); // 19 + } + + #else + + // See https://github.com/espressif/esp-idf/blob/master/components/esp32/include/rom/rtc.h switch (rtc_get_reset_reason((RESET_REASON)icore)) { - case NO_MEAN: return F("NO_MEAN"); - case POWERON_RESET: return F("Vbat power on reset"); - case SW_RESET: return F("Software reset digital core"); - case OWDT_RESET: return F("Legacy watch dog reset digital core"); - case DEEPSLEEP_RESET: isDEEPSLEEP_RESET = true; break; - case SDIO_RESET: return F("Reset by SLC module, reset digital core"); - case TG0WDT_SYS_RESET: return F("Timer Group0 Watch dog reset digital core"); - case TG1WDT_SYS_RESET: return F("Timer Group1 Watch dog reset digital core"); - case RTCWDT_SYS_RESET: return F("RTC Watch dog Reset digital core"); - case INTRUSION_RESET: return F("Instrusion tested to reset CPU"); - case TGWDT_CPU_RESET: return F("Time Group reset CPU"); - case SW_CPU_RESET: return F("Software reset CPU"); - case RTCWDT_CPU_RESET: return F("RTC Watch dog Reset CPU"); - case EXT_CPU_RESET: return F("for APP CPU, reseted by PRO CPU"); + case NO_MEAN: return F("NO_MEAN"); + case POWERON_RESET: return F("Vbat power on reset"); + case SW_RESET: return F("Software reset digital core"); + case OWDT_RESET: return F("Legacy watch dog reset digital core"); + case DEEPSLEEP_RESET: isDEEPSLEEP_RESET = true; break; + case SDIO_RESET: return F("Reset by SLC module, reset digital core"); + case TG0WDT_SYS_RESET: return F("Timer Group0 Watch dog reset digital core"); + case TG1WDT_SYS_RESET: return F("Timer Group1 Watch dog reset digital core"); + case RTCWDT_SYS_RESET: return F("RTC Watch dog Reset digital core"); + case INTRUSION_RESET: return F("Instrusion tested to reset CPU"); + case TGWDT_CPU_RESET: return F("Time Group reset CPU"); + case SW_CPU_RESET: return F("Software reset CPU"); + case RTCWDT_CPU_RESET: return F("RTC Watch dog Reset CPU"); + case EXT_CPU_RESET: return F("for APP CPU, reseted by PRO CPU"); case RTCWDT_BROWN_OUT_RESET: return F("Reset when the vdd voltage is not stable"); - case RTCWDT_RTC_RESET: return F("RTC Watch dog reset digital core and rtc module"); + case RTCWDT_RTC_RESET: return F("RTC Watch dog reset digital core and rtc module"); default: break; } + #endif if (isDEEPSLEEP_RESET) { String reason = F("Deep Sleep, Wakeup reason ("); reason += rtc_get_wakeup_cause(); reason += ')'; + +/* + switch (reason) { + #if CONFIG_IDF_TARGET_ESP32 + case POWERON_RESET: + case SW_CPU_RESET: + case DEEPSLEEP_RESET: + case SW_RESET: + #elif CONFIG_IDF_TARGET_ESP32S2 + case POWERON_RESET: + case RTC_SW_CPU_RESET: + case DEEPSLEEP_RESET: + case RTC_SW_SYS_RESET: + #endif + } +*/ return reason; } + return getUnknownString(); } diff --git a/src/src/Helpers/StringProvider.cpp b/src/src/Helpers/StringProvider.cpp index 5b1f94275..196878079 100644 --- a/src/src/Helpers/StringProvider.cpp +++ b/src/src/Helpers/StringProvider.cpp @@ -66,10 +66,14 @@ const __FlashStringHelper * getLabel(LabelType::Enum label) { #endif #if defined(CORE_POST_2_5_0) || defined(ESP32) + #ifndef LIMIT_BUILD_SIZE case LabelType::HEAP_MAX_FREE_BLOCK: return F("Heap Max Free Block"); + #endif #endif // if defined(CORE_POST_2_5_0) || defined(ESP32) #if defined(CORE_POST_2_5_0) + #ifndef LIMIT_BUILD_SIZE case LabelType::HEAP_FRAGMENTATION: return F("Heap Fragmentation"); + #endif #endif // if defined(CORE_POST_2_5_0) #ifdef ESP32 @@ -240,13 +244,19 @@ String getValue(LabelType::Enum label) { #endif #if defined(CORE_POST_2_5_0) + #ifndef LIMIT_BUILD_SIZE case LabelType::HEAP_MAX_FREE_BLOCK: return String(ESP.getMaxFreeBlockSize()); + #endif #endif // if defined(CORE_POST_2_5_0) #if defined(ESP32) + #ifndef LIMIT_BUILD_SIZE case LabelType::HEAP_MAX_FREE_BLOCK: return String(ESP.getMaxAllocHeap()); + #endif #endif // if defined(ESP32) #if defined(CORE_POST_2_5_0) + #ifndef LIMIT_BUILD_SIZE case LabelType::HEAP_FRAGMENTATION: return String(ESP.getHeapFragmentation()); + #endif #endif // if defined(CORE_POST_2_5_0) #ifdef ESP32 case LabelType::HEAP_SIZE: return String(ESP.getHeapSize()); @@ -254,7 +264,7 @@ String getValue(LabelType::Enum label) { #ifdef ESP32_ENABLE_PSRAM case LabelType::PSRAM_SIZE: return String(ESP.getPsramSize()); case LabelType::PSRAM_FREE: return String(ESP.getFreePsram()); - case LabelType::PSRAM_MIN_FREE: return String(ESP.getMinFreeHeap()); + case LabelType::PSRAM_MIN_FREE: return String(ESP.getMinFreePsram()); case LabelType::PSRAM_MAX_FREE_BLOCK: return String(ESP.getMaxAllocPsram()); #endif // ESP32_ENABLE_PSRAM #endif // ifdef ESP32 diff --git a/src/src/Helpers/StringProvider.h b/src/src/Helpers/StringProvider.h index 0be5c51a2..57fc151c1 100644 --- a/src/src/Helpers/StringProvider.h +++ b/src/src/Helpers/StringProvider.h @@ -37,10 +37,14 @@ struct LabelType { FREE_HEAP_IRAM, #endif #if defined(CORE_POST_2_5_0) || defined(ESP32) + #ifndef LIMIT_BUILD_SIZE HEAP_MAX_FREE_BLOCK, // 7654 + #endif #endif // if defined(CORE_POST_2_5_0) || defined(ESP32) #if defined(CORE_POST_2_5_0) + #ifndef LIMIT_BUILD_SIZE HEAP_FRAGMENTATION, // 12 + #endif #endif // if defined(CORE_POST_2_5_0) #ifdef ESP32 diff --git a/src/src/WebServer/AdvancedConfigPage.cpp b/src/src/WebServer/AdvancedConfigPage.cpp index 5b9e1b052..e74c3ec51 100644 --- a/src/src/WebServer/AdvancedConfigPage.cpp +++ b/src/src/WebServer/AdvancedConfigPage.cpp @@ -201,6 +201,12 @@ void handle_advanced() { addHtml(F(" (decimal)")); addFormNumericBox(F("I2C ClockStretchLimit"), F("wireclockstretchlimit"), Settings.WireClockStretchLimit); // TODO define limits + #ifdef ESP8266 + addUnit(F("usec")); + #endif + #ifdef ESP32 + addUnit(F("1/80 usec")); + #endif #if defined(FEATURE_ARDUINO_OTA) addFormCheckBox(F("Enable Arduino OTA"), F("arduinootaenable"), Settings.ArduinoOTAEnable); #endif // if defined(FEATURE_ARDUINO_OTA) diff --git a/src/src/WebServer/HardwarePage.cpp b/src/src/WebServer/HardwarePage.cpp index 1f7f1395b..4230862a6 100644 --- a/src/src/WebServer/HardwarePage.cpp +++ b/src/src/WebServer/HardwarePage.cpp @@ -6,6 +6,8 @@ #include "../WebServer/Markup_Buttons.h" #include "../WebServer/Markup_Forms.h" +#include "../CustomBuild/ESPEasyLimits.h" + #include "../DataStructs/DeviceStruct.h" #include "../Globals/Settings.h" @@ -78,10 +80,7 @@ void handle_hardware() { if (Settings.UseSerial && ((gpio == 1) || (gpio == 3))) { // do not add the pin state select for these pins. } else { - int pinnr = -1; - bool input, output, warning; - - if (getGpioInfo(gpio, pinnr, input, output, warning)) { + if (validGpio(gpio)) { String int_pinlabel = "p"; int_pinlabel += gpio; Settings.setPinBootState(gpio, static_cast(getFormItemInt(int_pinlabel))); diff --git a/src/src/WebServer/JSON.cpp b/src/src/WebServer/JSON.cpp index 1f7a396de..6ed847beb 100644 --- a/src/src/WebServer/JSON.cpp +++ b/src/src/WebServer/JSON.cpp @@ -167,14 +167,33 @@ void handle_json() LabelType::RESET_REASON, LabelType::CPU_ECO_MODE, - #ifdef CORE_POST_2_5_0 - LabelType::HEAP_MAX_FREE_BLOCK, - LabelType::HEAP_FRAGMENTATION, - #endif // ifdef CORE_POST_2_5_0 + #if defined(CORE_POST_2_5_0) || defined(ESP32) + #ifndef LIMIT_BUILD_SIZE + LabelType::HEAP_MAX_FREE_BLOCK, // 7654 + #endif + #endif // if defined(CORE_POST_2_5_0) || defined(ESP32) + #if defined(CORE_POST_2_5_0) + #ifndef LIMIT_BUILD_SIZE + LabelType::HEAP_FRAGMENTATION, // 12 + #endif + #endif // if defined(CORE_POST_2_5_0) LabelType::FREE_MEM, #ifdef USE_SECOND_HEAP LabelType::FREE_HEAP_IRAM, #endif + LabelType::FREE_STACK, + + #ifdef ESP32 + LabelType::HEAP_SIZE, + LabelType::HEAP_MIN_FREE, + #ifdef ESP32_ENABLE_PSRAM + LabelType::PSRAM_SIZE, + LabelType::PSRAM_FREE, + LabelType::PSRAM_MIN_FREE, + LabelType::PSRAM_MAX_FREE_BLOCK, + #endif // ESP32_ENABLE_PSRAM + #endif // ifdef ESP32 + LabelType::SUNRISE, LabelType::SUNSET, LabelType::TIMEZONE_OFFSET, diff --git a/src/src/WebServer/Markup.cpp b/src/src/WebServer/Markup.cpp index 15580c609..f8eeb2f5b 100644 --- a/src/src/WebServer/Markup.cpp +++ b/src/src/WebServer/Markup.cpp @@ -3,6 +3,8 @@ #include "../WebServer/HTML_wrappers.h" +#include "../CustomBuild/ESPEasyLimits.h" + #include "../Globals/Settings.h" #include "../Helpers/Hardware.h" diff --git a/src/src/WebServer/SysInfoPage.cpp b/src/src/WebServer/SysInfoPage.cpp index 97f7d84aa..0ffcc17fc 100644 --- a/src/src/WebServer/SysInfoPage.cpp +++ b/src/src/WebServer/SysInfoPage.cpp @@ -353,18 +353,21 @@ void handle_sysinfo_memory() { addHtml(html); } # if defined(CORE_POST_2_5_0) || defined(ESP32) + # ifndef LIMIT_BUILD_SIZE addRowLabelValue(LabelType::HEAP_MAX_FREE_BLOCK); -# endif // if defined(CORE_POST_2_5_0) || defined(ESP32) + # endif // ifndef LIMIT_BUILD_SIZE +# endif // if defined(CORE_POST_2_5_0) || defined(ESP32) # if defined(CORE_POST_2_5_0) + # ifndef LIMIT_BUILD_SIZE addRowLabelValue(LabelType::HEAP_FRAGMENTATION); addHtml('%'); -# endif // ifdef CORE_POST_2_5_0 + # endif // ifndef LIMIT_BUILD_SIZE { #ifdef USE_SECOND_HEAP addRowLabelValue(LabelType::FREE_HEAP_IRAM); #endif } - +# endif // if defined(CORE_POST_2_5_0) addRowLabel(LabelType::FREE_STACK);