diff --git a/Firmware/FastLED/FastLED.cpp b/Firmware/FastLED/FastLED.cpp new file mode 100644 index 0000000..b9fc386 --- /dev/null +++ b/Firmware/FastLED/FastLED.cpp @@ -0,0 +1,284 @@ +#define FASTLED_INTERNAL +#include "FastLED.h" + + +#if defined(__SAM3X8E__) +volatile uint32_t fuckit; +#endif + +FASTLED_NAMESPACE_BEGIN + +void *pSmartMatrix = NULL; + +CFastLED FastLED; + +CLEDController *CLEDController::m_pHead = NULL; +CLEDController *CLEDController::m_pTail = NULL; +static uint32_t lastshow = 0; + +uint32_t _frame_cnt=0; +uint32_t _retry_cnt=0; + +// uint32_t CRGB::Squant = ((uint32_t)((__TIME__[4]-'0') * 28))<<16 | ((__TIME__[6]-'0')*50)<<8 | ((__TIME__[7]-'0')*28); + +CFastLED::CFastLED() { + // clear out the array of led controllers + // m_nControllers = 0; + m_Scale = 255; + m_nFPS = 0; + m_pPowerFunc = NULL; + m_nPowerData = 0xFFFFFFFF; +} + +CLEDController &CFastLED::addLeds(CLEDController *pLed, + struct CRGB *data, + int nLedsOrOffset, int nLedsIfOffset) { + int nOffset = (nLedsIfOffset > 0) ? nLedsOrOffset : 0; + int nLeds = (nLedsIfOffset > 0) ? nLedsIfOffset : nLedsOrOffset; + + pLed->init(); + pLed->setLeds(data + nOffset, nLeds); + FastLED.setMaxRefreshRate(pLed->getMaxRefreshRate(),true); + return *pLed; +} + +void CFastLED::show(uint8_t scale) { + // guard against showing too rapidly + while(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros)); + lastshow = micros(); + + // If we have a function for computing power, use it! + if(m_pPowerFunc) { + scale = (*m_pPowerFunc)(scale, m_nPowerData); + } + + CLEDController *pCur = CLEDController::head(); + while(pCur) { + uint8_t d = pCur->getDither(); + if(m_nFPS < 100) { pCur->setDither(0); } + pCur->showLeds(scale); + pCur->setDither(d); + pCur = pCur->next(); + } + countFPS(); +} + +int CFastLED::count() { + int x = 0; + CLEDController *pCur = CLEDController::head(); + while( pCur) { + x++; + pCur = pCur->next(); + } + return x; +} + +CLEDController & CFastLED::operator[](int x) { + CLEDController *pCur = CLEDController::head(); + while(x-- && pCur) { + pCur = pCur->next(); + } + if(pCur == NULL) { + return *(CLEDController::head()); + } else { + return *pCur; + } +} + +void CFastLED::showColor(const struct CRGB & color, uint8_t scale) { + while(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros)); + lastshow = micros(); + + // If we have a function for computing power, use it! + if(m_pPowerFunc) { + scale = (*m_pPowerFunc)(scale, m_nPowerData); + } + + CLEDController *pCur = CLEDController::head(); + while(pCur) { + uint8_t d = pCur->getDither(); + if(m_nFPS < 100) { pCur->setDither(0); } + pCur->showColor(color, scale); + pCur->setDither(d); + pCur = pCur->next(); + } + countFPS(); +} + +void CFastLED::clear(bool writeData) { + if(writeData) { + showColor(CRGB(0,0,0), 0); + } + clearData(); +} + +void CFastLED::clearData() { + CLEDController *pCur = CLEDController::head(); + while(pCur) { + pCur->clearLedData(); + pCur = pCur->next(); + } +} + +void CFastLED::delay(unsigned long ms) { + unsigned long start = millis(); + do { +#ifndef FASTLED_ACCURATE_CLOCK + // make sure to allow at least one ms to pass to ensure the clock moves + // forward + ::delay(1); +#endif + show(); + yield(); + } + while((millis()-start) < ms); +} + +void CFastLED::setTemperature(const struct CRGB & temp) { + CLEDController *pCur = CLEDController::head(); + while(pCur) { + pCur->setTemperature(temp); + pCur = pCur->next(); + } +} + +void CFastLED::setCorrection(const struct CRGB & correction) { + CLEDController *pCur = CLEDController::head(); + while(pCur) { + pCur->setCorrection(correction); + pCur = pCur->next(); + } +} + +void CFastLED::setDither(uint8_t ditherMode) { + CLEDController *pCur = CLEDController::head(); + while(pCur) { + pCur->setDither(ditherMode); + pCur = pCur->next(); + } +} + +void CFastLED::isBusy() { + #ifndef USE_WS2812SERIAL + return; + #else + CLEDController *pCur = CLEDController::head(); + pCur->busy(); + #endif +} + +// +// template void transpose8(unsigned char A[8], unsigned char B[8]) { +// uint32_t x, y, t; +// +// // Load the array and pack it into x and y. +// y = *(unsigned int*)(A); +// x = *(unsigned int*)(A+4); +// +// // x = (A[0]<<24) | (A[m]<<16) | (A[2*m]<<8) | A[3*m]; +// // y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m]; +// + // // pre-transform x + // t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7); + // t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14); + // + // // pre-transform y + // t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7); + // t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14); + // + // // final transform + // t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F); + // y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F); + // x = t; +// +// B[7*n] = y; y >>= 8; +// B[6*n] = y; y >>= 8; +// B[5*n] = y; y >>= 8; +// B[4*n] = y; +// +// B[3*n] = x; x >>= 8; +// B[2*n] = x; x >>= 8; +// B[n] = x; x >>= 8; +// B[0] = x; +// // B[0]=x>>24; B[n]=x>>16; B[2*n]=x>>8; B[3*n]=x>>0; +// // B[4*n]=y>>24; B[5*n]=y>>16; B[6*n]=y>>8; B[7*n]=y>>0; +// } +// +// void transposeLines(Lines & out, Lines & in) { +// transpose8<1,2>(in.bytes, out.bytes); +// transpose8<1,2>(in.bytes + 8, out.bytes + 1); +// } + +extern int noise_min; +extern int noise_max; + +void CFastLED::countFPS(int nFrames) { + static int br = 0; + static uint32_t lastframe = 0; // millis(); + + if(br++ >= nFrames) { + uint32_t now = millis(); + now -= lastframe; + if( now == 0 ) { + now = 1; // prevent division by zero below + } + m_nFPS = (br * 1000) / now; + br = 0; + lastframe = millis(); + } +} + +void CFastLED::setMaxRefreshRate(uint16_t refresh, bool constrain) { + if(constrain) { + // if we're constraining, the new value of m_nMinMicros _must_ be higher than previously (because we're only + // allowed to slow things down if constraining) + if(refresh > 0) { + m_nMinMicros = ( (1000000/refresh) > m_nMinMicros) ? (1000000/refresh) : m_nMinMicros; + } + } else if(refresh > 0) { + m_nMinMicros = 1000000 / refresh; + } else { + m_nMinMicros = 0; + } +} + +extern "C" int atexit(void (* /*func*/ )()) { return 0; } + +#ifdef FASTLED_NEEDS_YIELD +extern "C" void yield(void) { } +#endif + +#ifdef NEED_CXX_BITS +namespace __cxxabiv1 +{ + #if !defined(ESP8266) && !defined(ESP32) + extern "C" void __cxa_pure_virtual (void) {} + #endif + + /* guard variables */ + + /* The ABI requires a 64-bit type. */ + __extension__ typedef int __guard __attribute__((mode(__DI__))); + + extern "C" int __cxa_guard_acquire (__guard *) __attribute__((weak)); + extern "C" void __cxa_guard_release (__guard *) __attribute__((weak)); + extern "C" void __cxa_guard_abort (__guard *) __attribute__((weak)); + + extern "C" int __cxa_guard_acquire (__guard *g) + { + return !*(char *)(g); + } + + extern "C" void __cxa_guard_release (__guard *g) + { + *(char *)g = 1; + } + + extern "C" void __cxa_guard_abort (__guard *) + { + + } +} +#endif + +FASTLED_NAMESPACE_END diff --git a/Firmware/FastLED/FastLED.h b/Firmware/FastLED/FastLED.h new file mode 100644 index 0000000..865f811 --- /dev/null +++ b/Firmware/FastLED/FastLED.h @@ -0,0 +1,594 @@ +#ifndef __INC_FASTSPI_LED2_H +#define __INC_FASTSPI_LED2_H + +///@file FastLED.h +/// central include file for FastLED, defines the CFastLED class/object + +#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) +#define FASTLED_HAS_PRAGMA_MESSAGE +#endif + +#define FASTLED_VERSION 3003002 +#ifndef FASTLED_INTERNAL +# ifdef FASTLED_HAS_PRAGMA_MESSAGE +# pragma message "FastLED version 3.003.003" +# else +# warning FastLED version 3.003.003 (Not really a warning, just telling you here.) +# endif +#endif + +#ifndef __PROG_TYPES_COMPAT__ +#define __PROG_TYPES_COMPAT__ +#endif + +#ifdef SmartMatrix_h +#include +#endif + +#ifdef DmxSimple_h +#include +#endif + +#ifdef DmxSerial_h +#include +#endif + +#include + +#include "cpp_compat.h" + +#include "fastled_config.h" +#include "led_sysdefs.h" + +// Utility functions +#include "fastled_delay.h" +#include "bitswap.h" + +#include "controller.h" +#include "fastpin.h" +#include "fastspi_types.h" +#include "dmx.h" + +#include "platforms.h" +#include "fastled_progmem.h" + +#include "lib8tion.h" +#include "pixeltypes.h" +#include "hsv2rgb.h" +#include "colorutils.h" +#include "pixelset.h" +#include "colorpalettes.h" + +#include "noise.h" +#include "power_mgt.h" + +#include "fastspi.h" +#include "chipsets.h" + +FASTLED_NAMESPACE_BEGIN + +/// definitions for the spi chipset constants +enum ESPIChipsets { + LPD6803, + LPD8806, + WS2801, + WS2803, + SM16716, + P9813, + APA102, + SK9822, + DOTSTAR +}; + +enum ESM { SMART_MATRIX }; +enum OWS2811 { OCTOWS2811,OCTOWS2811_400, OCTOWS2813}; +enum SWS2812 { WS2812SERIAL }; + +#ifdef HAS_PIXIE +template class PIXIE : public PixieController {}; +#endif + +#ifdef FASTLED_HAS_CLOCKLESS +template class NEOPIXEL : public WS2812Controller800Khz {}; +template class SM16703 : public SM16703Controller {}; +template class TM1829 : public TM1829Controller800Khz {}; +template class TM1812 : public TM1809Controller800Khz {}; +template class TM1809 : public TM1809Controller800Khz {}; +template class TM1804 : public TM1809Controller800Khz {}; +template class TM1803 : public TM1803Controller400Khz {}; +template class UCS1903 : public UCS1903Controller400Khz {}; +template class UCS1903B : public UCS1903BController800Khz {}; +template class UCS1904 : public UCS1904Controller800Khz {}; +template class UCS2903 : public UCS2903Controller {}; +template class WS2812 : public WS2812Controller800Khz {}; +template class WS2852 : public WS2812Controller800Khz {}; +template class WS2812B : public WS2812Controller800Khz {}; +template class GS1903 : public WS2812Controller800Khz {}; +template class SK6812 : public SK6812Controller {}; +template class SK6822 : public SK6822Controller {}; +template class APA106 : public SK6822Controller {}; +template class PL9823 : public PL9823Controller {}; +template class WS2811 : public WS2811Controller800Khz {}; +template class WS2813 : public WS2813Controller {}; +template class APA104 : public WS2811Controller800Khz {}; +template class WS2811_400 : public WS2811Controller400Khz {}; +template class GE8822 : public GE8822Controller800Khz {}; +template class GW6205 : public GW6205Controller800Khz {}; +template class GW6205_400 : public GW6205Controller400Khz {}; +template class LPD1886 : public LPD1886Controller1250Khz {}; +template class LPD1886_8BIT : public LPD1886Controller1250Khz_8bit {}; +#ifdef DmxSimple_h +template class DMXSIMPLE : public DMXSimpleController {}; +#endif +#ifdef DmxSerial_h +template class DMXSERIAL : public DMXSerialController {}; +#endif +#endif + +enum EBlockChipsets { +#ifdef PORTA_FIRST_PIN + WS2811_PORTA, + WS2813_PORTA, + WS2811_400_PORTA, + TM1803_PORTA, + UCS1903_PORTA, +#endif +#ifdef PORTB_FIRST_PIN + WS2811_PORTB, + WS2813_PORTB, + WS2811_400_PORTB, + TM1803_PORTB, + UCS1903_PORTB, +#endif +#ifdef PORTC_FIRST_PIN + WS2811_PORTC, + WS2813_PORTC, + WS2811_400_PORTC, + TM1803_PORTC, + UCS1903_PORTC, +#endif +#ifdef PORTD_FIRST_PIN + WS2811_PORTD, + WS2813_PORTD, + WS2811_400_PORTD, + TM1803_PORTD, + UCS1903_PORTD, +#endif +#ifdef HAS_PORTDC + WS2811_PORTDC, + WS2813_PORTDC, + WS2811_400_PORTDC, + TM1803_PORTDC, + UCS1903_PORTDC, +#endif +}; + +#if defined(LIB8_ATTINY) +#define NUM_CONTROLLERS 2 +#else +#define NUM_CONTROLLERS 8 +#endif + +typedef uint8_t (*power_func)(uint8_t scale, uint32_t data); + +/// High level controller interface for FastLED. This class manages controllers, global settings and trackings +/// such as brightness, and refresh rates, and provides access functions for driving led data to controllers +/// via the show/showColor/clear methods. +/// @nosubgrouping +class CFastLED { + // int m_nControllers; + uint8_t m_Scale; ///< The current global brightness scale setting + uint16_t m_nFPS; ///< Tracking for current FPS value + uint32_t m_nMinMicros; ///< minimum µs between frames, used for capping frame rates. + uint32_t m_nPowerData; ///< max power use parameter + power_func m_pPowerFunc; ///< function for overriding brightness when using FastLED.show(); + +public: + CFastLED(); + + + /// Add a CLEDController instance to the world. Exposed to the public to allow people to implement their own + /// CLEDController objects or instances. There are two ways to call this method (as well as the other addLeds) + /// variations. The first is with 3 arguments, in which case the arguments are the controller, a pointer to + /// led data, and the number of leds used by this controller. The second is with 4 arguments, in which case + /// the first two arguments are the same, the third argument is an offset into the CRGB data where this controller's + /// CRGB data begins, and the fourth argument is the number of leds for this controller object. + /// @param pLed - the led controller being added + /// @param data - base point to an array of CRGB data structures + /// @param nLedsOrOffset - number of leds (3 argument version) or offset into the data array + /// @param nLedsIfOffset - number of leds (4 argument version) + /// @returns a reference to the added controller + static CLEDController &addLeds(CLEDController *pLed, struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0); + + /// @name Adding SPI based controllers + //@{ + /// Add an SPI based CLEDController instance to the world. + /// There are two ways to call this method (as well as the other addLeds) + /// variations. The first is with 2 arguments, in which case the arguments are a pointer to + /// led data, and the number of leds used by this controller. The second is with 3 arguments, in which case + /// the first argument is the same, the second argument is an offset into the CRGB data where this controller's + /// CRGB data begins, and the third argument is the number of leds for this controller object. + /// + /// This method also takes a 1 to 5 template parameters for identifying the specific chipset, data and clock pins, + /// RGB ordering, and SPI data rate + /// @param data - base point to an array of CRGB data structures + /// @param nLedsOrOffset - number of leds (3 argument version) or offset into the data array + /// @param nLedsIfOffset - number of leds (4 argument version) + /// @tparam CHIPSET - the chipset type + /// @tparam DATA_PIN - the optional data pin for the leds (if omitted, will default to the first hardware SPI MOSI pin) + /// @tparam CLOCK_PIN - the optional clock pin for the leds (if omitted, will default to the first hardware SPI clock pin) + /// @tparam RGB_ORDER - the rgb ordering for the leds (e.g. what order red, green, and blue data is written out in) + /// @tparam SPI_DATA_RATE - the data rate to drive the SPI clock at, defined using DATA_RATE_MHZ or DATA_RATE_KHZ macros + /// @returns a reference to the added controller + template CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + switch(CHIPSET) { + case LPD6803: { static LPD6803Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case LPD8806: { static LPD8806Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case WS2801: { static WS2801Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case WS2803: { static WS2803Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case SM16716: { static SM16716Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case P9813: { static P9813Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case DOTSTAR: + case APA102: { static APA102Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case SK9822: { static SK9822Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + } + } + + template static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + switch(CHIPSET) { + case LPD6803: { static LPD6803Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case LPD8806: { static LPD8806Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case WS2801: { static WS2801Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case WS2803: { static WS2803Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case SM16716: { static SM16716Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case P9813: { static P9813Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case DOTSTAR: + case APA102: { static APA102Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case SK9822: { static SK9822Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + } + } + + template static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + switch(CHIPSET) { + case LPD6803: { static LPD6803Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case LPD8806: { static LPD8806Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case WS2801: { static WS2801Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case WS2803: { static WS2803Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case SM16716: { static SM16716Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case P9813: { static P9813Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case DOTSTAR: + case APA102: { static APA102Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + case SK9822: { static SK9822Controller c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } + } + } + +#ifdef SPI_DATA + template static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + return addLeds(data, nLedsOrOffset, nLedsIfOffset); + } + + template static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + return addLeds(data, nLedsOrOffset, nLedsIfOffset); + } + + template static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + return addLeds(data, nLedsOrOffset, nLedsIfOffset); + } + +#endif + //@} + +#ifdef FASTLED_HAS_CLOCKLESS + /// @name Adding 3-wire led controllers + //@{ + /// Add a clockless (aka 3wire, also DMX) based CLEDController instance to the world. + /// There are two ways to call this method (as well as the other addLeds) + /// variations. The first is with 2 arguments, in which case the arguments are a pointer to + /// led data, and the number of leds used by this controller. The second is with 3 arguments, in which case + /// the first argument is the same, the second argument is an offset into the CRGB data where this controller's + /// CRGB data begins, and the third argument is the number of leds for this controller object. + /// + /// This method also takes a 2 to 3 template parameters for identifying the specific chipset, data pin, and rgb ordering + /// RGB ordering, and SPI data rate + /// @param data - base point to an array of CRGB data structures + /// @param nLedsOrOffset - number of leds (3 argument version) or offset into the data array + /// @param nLedsIfOffset - number of leds (4 argument version) + /// @tparam CHIPSET - the chipset type (required) + /// @tparam DATA_PIN - the optional data pin for the leds (required) + /// @tparam RGB_ORDER - the rgb ordering for the leds (e.g. what order red, green, and blue data is written out in) + /// @returns a reference to the added controller + template class CHIPSET, uint8_t DATA_PIN, EOrder RGB_ORDER> + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + static CHIPSET c; + return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); + } + + template class CHIPSET, uint8_t DATA_PIN> + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + static CHIPSET c; + return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); + } + + template class CHIPSET, uint8_t DATA_PIN> + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + static CHIPSET c; + return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); + } + +#if defined(__FASTLED_HAS_FIBCC) && (__FASTLED_HAS_FIBCC == 1) + template class CHIPSET, uint8_t DATA_PIN, EOrder RGB_ORDER=RGB> + static CLEDController &addLeds(struct CRGB *data, int nLeds) { + static __FIBCC c; + return addLeds(&c, data, nLeds); + } +#endif + + #ifdef FASTSPI_USE_DMX_SIMPLE + template + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) + { + switch(CHIPSET) { + case DMX: { static DMXController controller; return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); } + } + } + #endif + //@} +#endif + + /// @name Adding 3rd party library controllers + //@{ + /// Add a 3rd party library based CLEDController instance to the world. + /// There are two ways to call this method (as well as the other addLeds) + /// variations. The first is with 2 arguments, in which case the arguments are a pointer to + /// led data, and the number of leds used by this controller. The second is with 3 arguments, in which case + /// the first argument is the same, the second argument is an offset into the CRGB data where this controller's + /// CRGB data begins, and the third argument is the number of leds for this controller object. This class includes the SmartMatrix + /// and OctoWS2811 based controllers + /// + /// This method also takes a 1 to 2 template parameters for identifying the specific chipset and rgb ordering + /// RGB ordering, and SPI data rate + /// @param data - base point to an array of CRGB data structures + /// @param nLedsOrOffset - number of leds (3 argument version) or offset into the data array + /// @param nLedsIfOffset - number of leds (4 argument version) + /// @tparam CHIPSET - the chipset type (required) + /// @tparam RGB_ORDER - the rgb ordering for the leds (e.g. what order red, green, and blue data is written out in) + /// @returns a reference to the added controller + template class CHIPSET, EOrder RGB_ORDER> + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + static CHIPSET c; + return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); + } + + template class CHIPSET> + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + static CHIPSET c; + return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); + } + +#ifdef USE_OCTOWS2811 + template + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) + { + switch(CHIPSET) { + case OCTOWS2811: { static COctoWS2811Controller controller; return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); } + case OCTOWS2811_400: { static COctoWS2811Controller controller; return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); } +#ifdef WS2813_800kHz + case OCTOWS2813: { static COctoWS2811Controller controller; return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); } +#endif + } + } + + template + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) + { + return addLeds(data,nLedsOrOffset,nLedsIfOffset); + } + +#endif + +#ifdef USE_WS2812SERIAL + template + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) + { + static CWS2812SerialController controller; + return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); + } +#endif + +#ifdef SmartMatrix_h + template + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) + { + switch(CHIPSET) { + case SMART_MATRIX: { static CSmartMatrixController controller; return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); } + } + } +#endif + //@} + + +#ifdef FASTLED_HAS_BLOCKLESS + + /// @name adding parallel output controllers + //@{ + /// Add a block based CLEDController instance to the world. + /// There are two ways to call this method (as well as the other addLeds) + /// variations. The first is with 2 arguments, in which case the arguments are a pointer to + /// led data, and the number of leds used by this controller. The second is with 3 arguments, in which case + /// the first argument is the same, the second argument is an offset into the CRGB data where this controller's + /// CRGB data begins, and the third argument is the number of leds for this controller object. + /// + /// This method also takes a 2 to 3 template parameters for identifying the specific chipset and rgb ordering + /// RGB ordering, and SPI data rate + /// @param data - base point to an array of CRGB data structures + /// @param nLedsOrOffset - number of leds (3 argument version) or offset into the data array + /// @param nLedsIfOffset - number of leds (4 argument version) + /// @tparam CHIPSET - the chipset/port type (required) + /// @tparam NUM_LANES - how many parallel lanes of output to write + /// @tparam RGB_ORDER - the rgb ordering for the leds (e.g. what order red, green, and blue data is written out in) + /// @returns a reference to the added controller + template + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + switch(CHIPSET) { + #ifdef PORTA_FIRST_PIN + case WS2811_PORTA: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case WS2811_400_PORTA: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case WS2813_PORTA: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case TM1803_PORTA: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case UCS1903_PORTA: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + #endif + #ifdef PORTB_FIRST_PIN + case WS2811_PORTB: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case WS2811_400_PORTB: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case WS2813_PORTB: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case TM1803_PORTB: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case UCS1903_PORTB: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + #endif + #ifdef PORTC_FIRST_PIN + case WS2811_PORTC: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case WS2811_400_PORTC: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case WS2813_PORTC: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case TM1803_PORTC: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case UCS1903_PORTC: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + #endif + #ifdef PORTD_FIRST_PIN + case WS2811_PORTD: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case WS2811_400_PORTD: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case WS2813_PORTD: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case TM1803_PORTD: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case UCS1903_PORTD: return addLeds(new InlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + #endif + #ifdef HAS_PORTDC + case WS2811_PORTDC: return addLeds(new SixteenWayInlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case WS2811_400_PORTDC: return addLeds(new SixteenWayInlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case WS2813_PORTDC: return addLeds(new SixteenWayInlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case TM1803_PORTDC: return addLeds(new SixteenWayInlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + case UCS1903_PORTDC: return addLeds(new SixteenWayInlineBlockClocklessController(), data, nLedsOrOffset, nLedsIfOffset); + #endif + } + } + + template + static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { + return addLeds(data,nLedsOrOffset,nLedsIfOffset); + } + //@} +#endif + + /// Set the global brightness scaling + /// @param scale a 0-255 value for how much to scale all leds before writing them out + void setBrightness(uint8_t scale) { m_Scale = scale; } + + /// Get the current global brightness setting + /// @returns the current global brightness value + uint8_t getBrightness() { return m_Scale; } + + /// Set the maximum power to be used, given in volts and milliamps. + /// @param volts - how many volts the leds are being driven at (usually 5) + /// @param milliamps - the maximum milliamps of power draw you want + inline void setMaxPowerInVoltsAndMilliamps(uint8_t volts, uint32_t milliamps) { setMaxPowerInMilliWatts(volts * milliamps); } + + /// Set the maximum power to be used, given in milliwatts + /// @param milliwatts - the max power draw desired, in milliwatts + inline void setMaxPowerInMilliWatts(uint32_t milliwatts) { m_pPowerFunc = &calculate_max_brightness_for_power_mW; m_nPowerData = milliwatts; } + + /// Update all our controllers with the current led colors, using the passed in brightness + /// @param scale temporarily override the scale + void show(uint8_t scale); + + /// Update all our controllers with the current led colors + void show() { show(m_Scale); } + + /// clear the leds, wiping the local array of data, optionally black out the leds as well + /// @param writeData whether or not to write out to the leds as well + void clear(bool writeData = false); + + /// clear out the local data array + void clearData(); + + /// Set all leds on all controllers to the given color/scale + /// @param color what color to set the leds to + /// @param scale what brightness scale to show at + void showColor(const struct CRGB & color, uint8_t scale); + + /// Set all leds on all controllers to the given color + /// @param color what color to set the leds to + void showColor(const struct CRGB & color) { showColor(color, m_Scale); } + + /// Delay for the given number of milliseconds. Provided to allow the library to be used on platforms + /// that don't have a delay function (to allow code to be more portable). Note: this will call show + /// constantly to drive the dithering engine (and will call show at least once). + /// @param ms the number of milliseconds to pause for + void delay(unsigned long ms); + + /// Set a global color temperature. Sets the color temperature for all added led strips, overriding whatever + /// previous color temperature those controllers may have had + /// @param temp A CRGB structure describing the color temperature + void setTemperature(const struct CRGB & temp); + + /// Set a global color correction. Sets the color correction for all added led strips, + /// overriding whatever previous color correction those controllers may have had. + /// @param correction A CRGB structure describin the color correction. + void setCorrection(const struct CRGB & correction); + + /// Set the dithering mode. Sets the dithering mode for all added led strips, overriding + /// whatever previous dithering option those controllers may have had. + /// @param ditherMode - what type of dithering to use, either BINARY_DITHER or DISABLE_DITHER + void setDither(uint8_t ditherMode = BINARY_DITHER); + + /// Set the maximum refresh rate. This is global for all leds. Attempts to + /// call show faster than this rate will simply wait. Note that the refresh rate + /// defaults to the slowest refresh rate of all the leds added through addLeds. If + /// you wish to set/override this rate, be sure to call setMaxRefreshRate _after_ + /// adding all of your leds. + /// @param refresh - maximum refresh rate in hz + /// @param constrain - constrain refresh rate to the slowest speed yet set + void setMaxRefreshRate(uint16_t refresh, bool constrain=false); + + /// for debugging, will keep track of time between calls to countFPS, and every + /// nFrames calls, it will update an internal counter for the current FPS. + /// @todo make this a rolling counter + /// @param nFrames - how many frames to time for determining FPS + void countFPS(int nFrames=25); + + /// Get the number of frames/second being written out + /// @returns the most recently computed FPS value + uint16_t getFPS() { return m_nFPS; } + + /// Get how many controllers have been registered + /// @returns the number of controllers (strips) that have been added with addLeds + int count(); + + void isBusy(); + + /// Get a reference to a registered controller + /// @returns a reference to the Nth controller + CLEDController & operator[](int x); + + /// Get the number of leds in the first controller + /// @returns the number of LEDs in the first controller + int size() { return (*this)[0].size(); } + + /// Get a pointer to led data for the first controller + /// @returns pointer to the CRGB buffer for the first controller + CRGB *leds() { return (*this)[0].leds(); } +}; + +#define FastSPI_LED FastLED +#define FastSPI_LED2 FastLED +#ifndef LEDS +#define LEDS FastLED +#endif + +extern CFastLED FastLED; + +// Warnings for undefined things +#ifndef HAS_HARDWARE_PIN_SUPPORT +#warning "No pin/port mappings found, pin access will be slightly slower. See fastpin.h for info." +#define NO_HARDWARE_PIN_SUPPORT +#endif + + +FASTLED_NAMESPACE_END + +#endif diff --git a/Firmware/FastLED/WS2812Serial.cpp b/Firmware/FastLED/WS2812Serial.cpp new file mode 100644 index 0000000..8ee47b9 --- /dev/null +++ b/Firmware/FastLED/WS2812Serial.cpp @@ -0,0 +1,320 @@ +/* WS2812Serial - Non-blocking WS2812 LED Display Library + https://github.com/PaulStoffregen/WS2812Serial + Copyright (c) 2017 Paul Stoffregen, PJRC.COM, LLC + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#include "WS2812Serial.h" + +bool WS2812Serial::begin() +{ +#if defined(__IMXRT1062__) // Teensy 3.x + uint32_t hwtrigger; +#else + uint32_t divisor, portconfig, hwtrigger; + KINETISK_UART_t *uart; +#endif + switch (pin) { +#if defined(KINETISK) // Teensy 3.x + case 1: // Serial1 + case 5: + #if defined(__MK64FX512__) || defined(__MK66FX1M0__) + case 26: + #endif + uart = &KINETISK_UART0; + divisor = BAUD2DIV(4000000); + portconfig = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(3); + hwtrigger = DMAMUX_SOURCE_UART0_TX; + SIM_SCGC4 |= SIM_SCGC4_UART0; + break; + + case 10: // Serial2 + #if defined(__MK20DX128__) || defined(__MK20DX256__) + case 31: + #elif defined(__MK64FX512__) || defined(__MK66FX1M0__) + case 58: + #endif + uart = &KINETISK_UART1; + divisor = BAUD2DIV2(4000000); + portconfig = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(3); + hwtrigger = DMAMUX_SOURCE_UART1_TX; + SIM_SCGC4 |= SIM_SCGC4_UART1; + break; + + case 8: // Serial3 + uart = &KINETISK_UART2; + divisor = BAUD2DIV3(4000000); + portconfig = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(3); + hwtrigger = DMAMUX_SOURCE_UART2_TX; + SIM_SCGC4 |= SIM_SCGC4_UART2; + break; + + #if defined(__MK64FX512__) || defined(__MK66FX1M0__) + case 32: // Serial4 + case 62: + uart = &KINETISK_UART3; + divisor = BAUD2DIV3(4000000); + portconfig = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(3); + hwtrigger = DMAMUX_SOURCE_UART3_TX; + SIM_SCGC4 |= SIM_SCGC4_UART3; + break; + + case 33: // Serial5 + uart = &KINETISK_UART4; + divisor = BAUD2DIV3(4000000); + portconfig = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(3); + hwtrigger = DMAMUX_SOURCE_UART4_RXTX; + SIM_SCGC1 |= SIM_SCGC1_UART4; + break; + #endif + #if defined(__MK64FX512__) + case 48: // Serial6 + uart = &KINETISK_UART5; + divisor = BAUD2DIV3(4000000); + portconfig = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(3); + hwtrigger = DMAMUX_SOURCE_UART5_RXTX; + SIM_SCGC1 |= SIM_SCGC1_UART5; + break; + #endif + +#elif defined(KINETISL) // Teensy LC + case 1: // Serial1 + case 5: + // NOT SURE HOW THIS WORKS ON LC????? + uart = &KINETISK_UART0; + divisor = 1; + portconfig = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(3); + hwtrigger = DMAMUX_SOURCE_UART0_TX; + SIM_SCGC4 |= SIM_SCGC4_UART0; + break; + case 4: + uart = &KINETISK_UART0; + divisor = 1; + portconfig = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(2); + hwtrigger = DMAMUX_SOURCE_UART0_TX; + SIM_SCGC4 |= SIM_SCGC4_UART0; + break; + case 24: + uart = &KINETISK_UART0; + divisor = 1; + portconfig = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(4); + hwtrigger = DMAMUX_SOURCE_UART0_TX; + SIM_SCGC4 |= SIM_SCGC4_UART0; + break; + +#elif defined(__IMXRT1062__) + case 1: // Serial1 + uart = &IMXRT_LPUART6; + CCM_CCGR3 |= CCM_CCGR3_LPUART6(CCM_CCGR_ON); + hwtrigger = DMAMUX_SOURCE_LPUART6_TX; + break; + case 8: // Serial2 + uart = &IMXRT_LPUART4; + CCM_CCGR1 |= CCM_CCGR1_LPUART4(CCM_CCGR_ON); + hwtrigger = DMAMUX_SOURCE_LPUART4_TX; + break; + case 14: // Serial3 + uart = &IMXRT_LPUART2; + CCM_CCGR0 |= CCM_CCGR0_LPUART2(CCM_CCGR_ON); + hwtrigger = DMAMUX_SOURCE_LPUART2_TX; + break; + case 17: // Serial4 + uart = &IMXRT_LPUART3; + CCM_CCGR0 |= CCM_CCGR0_LPUART3(CCM_CCGR_ON); + hwtrigger = DMAMUX_SOURCE_LPUART3_TX; + break; + case 20: // Serial5 + case 39: // Serial5 alt + uart = &IMXRT_LPUART8; + CCM_CCGR6 |= CCM_CCGR6_LPUART8(CCM_CCGR_ON); + hwtrigger = DMAMUX_SOURCE_LPUART8_TX; + break; + case 24: // Serial6 + uart = &IMXRT_LPUART1; + CCM_CCGR5 |= CCM_CCGR5_LPUART1(CCM_CCGR_ON); + hwtrigger = DMAMUX_SOURCE_LPUART1_TX; + break; + case 29: // Serial7 + uart = &IMXRT_LPUART7; + CCM_CCGR5 |= CCM_CCGR5_LPUART7(CCM_CCGR_ON); + hwtrigger = DMAMUX_SOURCE_LPUART7_TX; + break; +#endif + default: + return false; // pin not supported + } + if (!dma) { + dma = new DMAChannel; + if (!dma) return false; // unable to allocate DMA channel + } +#if defined(__IMXRT1062__) + // Convert Baud + // Computed values for 4mhz + uart->CTRL = 0; // clear everything + uart->BAUD = LPUART_BAUD_OSR(5) | LPUART_BAUD_SBR(1) | LPUART_BAUD_TDMAE; // set baud configure for transfer DMA + uart->PINCFG = 0; + uint16_t tx_fifo_size = (((uart->FIFO >> 4) & 0x7) << 2); + uint8_t tx_water = (tx_fifo_size < 16) ? tx_fifo_size >> 1 : 7; +// uart->WATER = LPUART_WATER_TXWATER(1); // guessing here? +// uart->FIFO = 0; // disable the fifo. + uart->WATER = LPUART_WATER_TXWATER(tx_water); + uart->FIFO |= LPUART_FIFO_TXFE; + + uart->CTRL = (LPUART_CTRL_TE /*| LPUART_CTRL_TIE */ | LPUART_CTRL_TXINV); // enable transmitter and invert + // We need to configure the TX pin now. + *(portControlRegister(pin)) = IOMUXC_PAD_SRE | IOMUXC_PAD_DSE(3) | IOMUXC_PAD_SPEED(3); + *(portConfigRegister(pin)) = 2; // from hardware table for each one, but I think they are all 2... + + dma->destination((volatile uint8_t&)uart->DATA); + //Serial.printf("HWTrigger: %x\n", hwtrigger); +#else +#if defined(KINETISK) + if (divisor < 32) divisor = 32; + uart->BDH = (divisor >> 13) & 0x1F; + uart->BDL = (divisor >> 5) & 0xFF; + uart->C4 = divisor & 0x1F; +#elif defined(KINETISL) + uart->BDH = (divisor >> 8) & 0x1F; + uart->BDL = divisor & 0xFF; + uart->C4 = 11; +#endif + uart->C1 = 0; + uart->C2 = UART_C2_TE | UART_C2_TIE; + uart->C3 = UART_C3_TXINV; + uart->C5 = UART_C5_TDMAS; +#if defined(KINETISK) + uart->PFIFO = 0; // TODO: is this ok for Serial3-6? +#endif + *(portConfigRegister(pin)) = portconfig; + dma->destination(uart->D); +#endif + + dma->triggerAtHardwareEvent(hwtrigger); + memset(drawBuffer, 0, numled * 3); + return true; +} + +void WS2812Serial::busy() +{ + #if defined(KINETISK) + while ((DMA_ERQ & (1 << dma->channel))) { + yield(); + } +#elif defined(KINETISL) + while ((dma->CFG->DCR & DMA_DCR_ERQ)) { + yield(); + } +#elif defined(__IMXRT1062__) + //Serial.println("Show called"); + while ((DMA_ERQ & (1 << dma->channel))) { + yield(); + } + //Serial.println("After Yield"); + #endif +} + +void WS2812Serial::show() +{ + // wait if prior DMA still in progress +#if defined(KINETISK) + while ((DMA_ERQ & (1 << dma->channel))) { + yield(); + } +#elif defined(KINETISL) + while ((dma->CFG->DCR & DMA_DCR_ERQ)) { + yield(); + } +#elif defined(__IMXRT1062__) + //Serial.println("Show called"); + while ((DMA_ERQ & (1 << dma->channel))) { + yield(); + } + //Serial.println("After Yield"); +#endif + // copy drawing buffer to frame buffer + const uint8_t *p = drawBuffer; + const uint8_t *end = p + (numled * 3); + uint8_t *fb = frameBuffer; + while (p < end) { + uint8_t b = *p++; + uint8_t g = *p++; + uint8_t r = *p++; + uint32_t n=0; + switch (config) { + case WS2812_RGB: n = (r << 16) | (g << 8) | b; break; + case WS2812_RBG: n = (r << 16) | (b << 8) | g; break; + case WS2812_GRB: n = (g << 16) | (r << 8) | b; break; + case WS2812_GBR: n = (g << 16) | (b << 8) | r; break; + case WS2812_BRG: n = (b << 16) | (r << 8) | g; break; + case WS2812_BGR: n = (b << 16) | (g << 8) | r; break; + } + const uint8_t *stop = fb + 12; + do { + uint8_t x = 0x08; + if (!(n & 0x00800000)) x |= 0x07; + if (!(n & 0x00400000)) x |= 0xE0; + n <<= 2; + *fb++ = x; + } while (fb < stop); + } + // wait 300us WS2812 reset time + uint32_t min_elapsed = (numled * 30) + 300; + if (min_elapsed < 2500) min_elapsed = 2500; + uint32_t m; + while (1) { + m = micros(); + if ((m - prior_micros) > min_elapsed) break; + yield(); + } + prior_micros = m; + // start DMA transfer to update LEDs :-) +#if defined(KINETISK) + dma->sourceBuffer(frameBuffer, numled * 12); + dma->transferSize(1); + dma->transferCount(numled * 12); + dma->disableOnCompletion(); + dma->enable(); +#elif defined(KINETISL) + dma->CFG->SAR = frameBuffer; + dma->CFG->DSR_BCR = 0x01000000; + dma->CFG->DSR_BCR = numled * 12; + dma->CFG->DCR = DMA_DCR_ERQ | DMA_DCR_CS | DMA_DCR_SSIZE(1) | + DMA_DCR_SINC | DMA_DCR_DSIZE(1) | DMA_DCR_D_REQ; +#elif defined(__IMXRT1062__) + // See if we need to muck with DMA cache... + if ((uint32_t)frameBuffer >= 0x20200000u) arm_dcache_flush(frameBuffer, numled * 12); + + dma->sourceBuffer(frameBuffer, numled * 12); +// dma->transferSize(1); + dma->transferCount(numled * 12); + dma->disableOnCompletion(); + +/* Serial.printf("%x %x:", (uint32_t)dma, (uint32_t)dma->TCD); + + Serial.printf("SA:%x SO:%d AT:%x NB:%x SL:%d DA:%x DO: %d CI:%x DL:%x CS:%x BI:%x\n", (uint32_t)dma->TCD->SADDR, + dma->TCD->SOFF, dma->TCD->ATTR, dma->TCD->NBYTES, dma->TCD->SLAST, (uint32_t)dma->TCD->DADDR, + dma->TCD->DOFF, dma->TCD->CITER, dma->TCD->DLASTSGA, dma->TCD->CSR, dma->TCD->BITER); +*/ + uart->STAT = 0; // try clearing out the status + dma->enable(); + +#endif +} + diff --git a/Firmware/FastLED/WS2812Serial.h b/Firmware/FastLED/WS2812Serial.h new file mode 100644 index 0000000..dd08ec1 --- /dev/null +++ b/Firmware/FastLED/WS2812Serial.h @@ -0,0 +1,89 @@ +/* WS2812Serial - Non-blocking WS2812 LED Display Library + https://github.com/PaulStoffregen/WS2812Serial + Copyright (c) 2017 Paul Stoffregen, PJRC.COM, LLC + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef WS2812Serial_h_ +#define WS2812Serial_h_ + +#include +#include "DMAChannel.h" + +#define WS2812_RGB 0 // The WS2811 datasheet documents this way +#define WS2812_RBG 1 +#define WS2812_GRB 2 // Most LED strips are wired this way +#define WS2812_GBR 3 +#define WS2812_BRG 4 +#define WS2812_BGR 5 + +class WS2812Serial { +public: + constexpr WS2812Serial(uint16_t num, void *fb, void *db, uint8_t pin, uint8_t cfg) : + numled(num), pin(pin), config(cfg), + frameBuffer((uint8_t *)fb), drawBuffer((uint8_t *)db) { + } + bool begin(); + void setPixel(uint32_t num, int color) { + if (num >= numled) return; + num *= 3; + drawBuffer[num+0] = color & 255; + drawBuffer[num+1] = (color >> 8) & 255; + drawBuffer[num+2] = (color >> 16) & 255; + } + void setPixel(uint32_t num, uint8_t red, uint8_t green, uint8_t blue) { + if (num >= numled) return; + num *= 3; + drawBuffer[num+0] = blue; + drawBuffer[num+1] = green; + drawBuffer[num+2] = red; + } + void clear() { + memset(drawBuffer, 0, numled * 3); + } + void show(); + void busy(); + uint16_t numPixels() { + return numled; + } + // Functions for compatibility with Adafruit_NeoPixel + void setPixelColor(uint16_t num, uint32_t color) { + setPixel(num, color); + } + void setPixelColor(uint16_t num, uint8_t red, uint8_t green, uint8_t blue) { + setPixel(num, red, green, blue); + } + uint32_t Color(uint8_t red, uint8_t green, uint8_t blue) { + return (red << 16) | (green << 8) | blue; + } +private: + const uint16_t numled; + const uint8_t pin; + const uint8_t config; + uint8_t *frameBuffer; + uint8_t *drawBuffer; + DMAChannel *dma = nullptr; + uint32_t prior_micros = 0; + #if defined(__IMXRT1062__) // Teensy 3.x + IMXRT_LPUART_t *uart = nullptr; + #endif +}; + +#endif diff --git a/Firmware/OpeNITHM/AirSensor.cpp b/Firmware/OpeNITHM/AirSensor.cpp index ee6fb8c..9001c5a 100644 --- a/Firmware/OpeNITHM/AirSensor.cpp +++ b/Firmware/OpeNITHM/AirSensor.cpp @@ -81,20 +81,36 @@ void AirSensor::turnOffLight() pinMode(LED_2, INPUT); } -int AirSensor::getValue(int sensor, bool light) +void AirSensor::setHalfLEDs(CRGB color, int side) { - // Turn on light corresponding to read sensor - if (light) + for (int i = 0; i < 8; i++) { - changeLight(sensor); - } - else - { - turnOffLight(); +#ifndef KEY_DIVIDERS + leds[i] = (side == 0) ? color : CRGB::Black; +#else + leds[i * 2] = (side == 0) ? color : CRGB::Black; +#endif } + for (int i = 8; i < 16; i++) + { +#ifndef KEY_DIVIDERS + leds[i] = (side == 1) ? color : CRGB::Black; +#else + leds[i * 2] = (side == 1) ? color : CRGB::Black; +#endif + } + + FastLED.show(); +} + +int AirSensor::getValue(int sensor) +{ + // Turn on light corresponding to read sensor + changeLight(sensor); + // Delay required because the read may occur faster than the physical light turning on - delayMicroseconds(125); + delayMicroseconds(AIR_LED_DELAY); #ifdef IR_SENSOR_MULTIPLEXED // Set multiplexer to corresponding sensor @@ -130,49 +146,158 @@ AirSensor::AirSensor(int requiredSamples, int skippedSamples) : thresholds{ 1000 #ifndef IR_SENSOR_MULTIPLEXED pinMode(ir_sensor_pins[i], INPUT); #endif - calibrated[i] = getValue(i, true); + calibrated[i] = getValue(i); } } else { - - EEPROM.get(66, analogSensitivity); - - if (analogSensitivity == 0 || analogSensitivity >= 100) - setAnalogSensitivity(DEFAULT_SENSITIVITY); - analogCalibrate(); } +} - +void AirSensor::loadConfig() +{ + for (int i = 0; i < 6; i++) + { + EEPROM.get(74 + i, thresholds[i]); + } +} + +void AirSensor::saveConfig() +{ + for (int i = 0; i < 6; i++) + { + EEPROM.put(74 + i, thresholds[i]); + } + + EEPROM.put(66, (byte) CALIBRATION_FLAG); } void AirSensor::analogCalibrate() { #ifdef IR_SENSOR_ANALOG - for (int sensor = 0; sensor < 6; sensor++) + // we'll only calibrate if: + // * the user is holding the first 4 keys + // * the calibration flag is not set in EEPROM + bool needsCalibration = false; + + byte calibrationFlag; + EEPROM.get(66, calibrationFlag); + + // only check the first 4 keys if we've calibrated at least once + if (calibrationFlag == CALIBRATION_FLAG) + { + loadConfig(); + + int touched = 0; + touchboard->scan(); + + for (int i = 0; i < 4; i++) + { + if (touchboard->update(i) != UNPRESSED) touched++; + } + + if (touched == 4) needsCalibration = true; + } + else + { + needsCalibration = true; + } + + if (needsCalibration) { // first, skip samplesToSkip number of readings for (int i = 0; i < samplesToSkip; i++) { - getValue(sensor, true); - turnOffLight(); + for (int sensor = 0; sensor < 6; sensor++) + { + getValue(sensor); + turnOffLight(); + } } - // now gather the calibration samples for this sensor - for (int i = 0; i < samplesToAcquire; i++) + // Now gather the calibration samples for each sensor. We split the calibration + // into two parts -- left half of the slider and right half of the slider. We + // do this because the controllers' air space tends to be less sensitive on the + // side that contains the IR LEDs themselves, so we wanna take the 'max' of the + // overall calibration process for each sensor, between the two halves + int leftSideMins[6] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF }; + int rightSideMins[6] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF }; + int lastReadings[6] = { 0 }; + bool inputDetected = false; + + for (int side = 0; side < 2; side++) { - int value = getValue(sensor, true); - turnOffLight(); - - //keep the minimum value seen by the sensor - if (value < thresholds[sensor]) - thresholds[sensor] = value; + // first, set the correct half of the slider red, and wait for some air input + setHalfLEDs(CRGB::Red, side); + + // wait for air inputs before we begin calibration + while (!inputDetected) + { + for (int i = 0; i < 6; i++) + { + int value = getValue(i); + + if (value < (AIR_INPUT_DETECTION * lastReadings[i])) + inputDetected = true; + else + lastReadings[i] = value; + } + } + + // set the correct half of the slider yellow + setHalfLEDs(CRGB::Yellow, side); + + // begin calibration + for (int i = 0; i < samplesToAcquire; i++) + { + for (int sensor = 0; sensor < 6; sensor++) + { + int value = getValue(sensor); + turnOffLight(); + + // keep the minimum value seen by the sensor + if (side == 0) + { + if (value < leftSideMins[sensor]) + leftSideMins[sensor] = value; + } + else + { + if (value < rightSideMins[sensor]) + rightSideMins[sensor] = value; + } + } + + // after sweeping the LEDs, scan the touchboard to simulate the delay between + // IR sweeps during actual gameplay so we calibrate accurately + touchboard -> scan(); + } + + for (int i = 0; i < 6; i++) { + // consider the sensor calibrated, finalize calibration for this sensor. + calibrated[i] = true; + + // we'll take the threshold to be 40% (default) of the window between the baseline readings and the "threshold" readings + int bottom = max(leftSideMins[i], rightSideMins[i]); + thresholds[i] = bottom + ((lastReadings[i] - bottom) * AIR_INPUT_THRESHOLD); + } + + // set the correct half of the slider green + setHalfLEDs(CRGB::Green, side); + delay(3000); + inputDetected = false; + } + + saveConfig(); + } + else + { + for (int i = 0; i < 6; i++) + { + // just set the keys to calibrated + calibrated[i] = true; } - - // consider the sensor calibrated, finalize calibration for this sensor. - calibrated[sensor] = true; - thresholds[sensor] *= (analogSensitivity / 100.0f); } #endif } @@ -194,7 +319,7 @@ bool AirSensor::isCalibrated() bool AirSensor::getSensorState(int sensor) { // Flash the LED and read the IR sensor - int value = getValue(sensor, true); + int value = getValue(sensor); turnOffLight(); if (digitalMode) @@ -251,17 +376,6 @@ bool AirSensor::getSensorCalibrated(int i) return calibrated[i]; } -void AirSensor::setAnalogSensitivity(uint8_t analogSensitivity) -{ - this->analogSensitivity = analogSensitivity; - EEPROM.put(66, analogSensitivity); -} - -uint8_t AirSensor::getAnalogSensitivity() -{ - return analogSensitivity; -} - void AirSensor::recalibrate() { for (int i = 0; i < 6; i++) diff --git a/Firmware/OpeNITHM/AirSensor.h b/Firmware/OpeNITHM/AirSensor.h index 75a4e7e..4eaf250 100644 --- a/Firmware/OpeNITHM/AirSensor.h +++ b/Firmware/OpeNITHM/AirSensor.h @@ -9,16 +9,34 @@ #include "WProgram.h" #endif +#include "AutoTouchboard.h" +#include "Output.h" #include "PinConfig.h" #include -#define DEFAULT_SENSITIVITY 85 +#include +#define USE_WS2812SERIAL +#include + +#define AIR_LED_DELAY 125 +#define AIR_INPUT_DETECTION 0.85 +#define AIR_INPUT_THRESHOLD 0.40 +#define CALIBRATION_FLAG 0xF6 + +#ifndef KEY_DIVIDERS +extern CRGB leds[16]; +#else +extern CRGB leds[31]; +#endif + +extern AutoTouchboard *touchboard; class AirSensor { private: void changeLight(int light); void turnOffLight(); + void setHalfLEDs(CRGB color, int side); uint8_t analogSensitivity; int thresholds[6]; @@ -30,16 +48,16 @@ class AirSensor public: AirSensor(int requiredSamples, int skippedSamples); + void loadConfig(); + void saveConfig(); void analogCalibrate(); bool isCalibrated(); bool isDigital(); bool getSensorState(int sensor); - int getValue(int sensor, bool light); + int getValue(int sensor); float getHandPosition(); uint8_t getSensorReadings(); bool getSensorCalibrated(int i); - void setAnalogSensitivity(uint8_t analogSensitivity); - uint8_t getAnalogSensitivity(); void recalibrate(); }; diff --git a/Firmware/OpeNITHM/AutoTouchboard.cpp b/Firmware/OpeNITHM/AutoTouchboard.cpp index 882fa07..8bb5f4f 100644 --- a/Firmware/OpeNITHM/AutoTouchboard.cpp +++ b/Firmware/OpeNITHM/AutoTouchboard.cpp @@ -2,6 +2,8 @@ void AutoTouchboard::scan() { + FastLED.isBusy(); + // For each key, set multiplexers and poll both capacitive sensors simultaneously for (int i = 0; i < 8; i++) { @@ -75,6 +77,7 @@ void AutoTouchboard::calibrateKeys(bool forceCalibrate = false) if (needsCalibration) { uint16_t baselines[16]; + uint16_t maxReadings[16]; // Reset calibration data for all keys for (int i = 0; i < 16; i++) @@ -82,6 +85,7 @@ void AutoTouchboard::calibrateKeys(bool forceCalibrate = false) key_values[i] = 0; single_thresholds[i] = 0xFFFF; double_thresholds[i] = 0xFFFF; + maxReadings[i] = 0; } // Flash every key red a few times so they know to let go of the slider @@ -118,7 +122,6 @@ void AutoTouchboard::calibrateKeys(bool forceCalibrate = false) scan(); } - // figure out the baseline for each key for (int i = 0; i < 16; i++) { baselines[i] = key_values[i]; @@ -145,15 +148,16 @@ void AutoTouchboard::calibrateKeys(bool forceCalibrate = false) } #ifndef KEY_DIVIDERS - leds[i] = CRGB::Blue; + leds[i] = CRGB::Yellow; #else - leds[i*2] = CRGB::Blue; + leds[i*2] = CRGB::Yellow; #endif FastLED.show(); for (int j = 0; j < CALIBRATION_SAMPLES; j++) { scan(); + maxReadings[i] = max(maxReadings[i], key_values[i]); } #ifndef KEY_DIVIDERS @@ -163,7 +167,7 @@ void AutoTouchboard::calibrateKeys(bool forceCalibrate = false) #endif FastLED.show(); - uint16_t window = (key_values[i] - baselines[i]) * (sensitivity / 100.0f); + uint16_t window = (maxReadings[i] - baselines[i]) * TOUCH_INPUT_THRESHOLD; single_thresholds[i] = baselines[i] + window; double_thresholds[i] = baselines[i] + (2 * window); } @@ -200,17 +204,6 @@ uint16_t AutoTouchboard::getRawValue(int key) return key_values[key]; } -void AutoTouchboard::setSensitivity(uint8_t sensitivity) -{ - this->sensitivity = sensitivity; - EEPROM.put(65, sensitivity); -} - -uint8_t AutoTouchboard::getSensitivity() -{ - return sensitivity; -} - AutoTouchboard::AutoTouchboard() #ifndef TEENSY sensor(CapacitiveSensor(SEND, RECEIVE_1, RECEIVE_2)), @@ -220,10 +213,5 @@ AutoTouchboard::AutoTouchboard() pinMode(MUX_1, OUTPUT); pinMode(MUX_2, OUTPUT); - EEPROM.get(65, sensitivity); - - if (sensitivity == 0) - setSensitivity(DEFAULT_SENSITIVITY); - calibrateKeys(); } diff --git a/Firmware/OpeNITHM/AutoTouchboard.h b/Firmware/OpeNITHM/AutoTouchboard.h index eed939e..5a6476e 100644 --- a/Firmware/OpeNITHM/AutoTouchboard.h +++ b/Firmware/OpeNITHM/AutoTouchboard.h @@ -10,12 +10,15 @@ #include "CapacitiveSensor.h" #endif #include + +#include +#define USE_WS2812SERIAL #include -#define CALIBRATION_SAMPLES 25 -#define CALIBRATION_DETECTION_THRESHOLD 55 -#define CALIBRATION_FLAG 0xFF -#define DEFAULT_SENSITIVITY 76 +#define CALIBRATION_SAMPLES 200 +#define CALIBRATION_DETECTION_THRESHOLD 10 +#define CALIBRATION_FLAG 0xA2 +#define TOUCH_INPUT_THRESHOLD 0.85 #ifndef KEY_DIVIDERS extern CRGB leds[16]; @@ -29,7 +32,6 @@ class AutoTouchboard #ifndef TEENSY CapacitiveSensor sensor; #endif - uint8_t sensitivity; uint16_t key_values[16]; uint16_t single_thresholds[16]; uint16_t double_thresholds[16]; @@ -42,8 +44,6 @@ class AutoTouchboard KeyState update(int key); uint16_t getRawValue(int key); void calibrateKeys(bool forceCalibrate = false); - void setSensitivity(uint8_t sensitivity); - uint8_t getSensitivity(); }; #endif diff --git a/Firmware/OpeNITHM/Config.h b/Firmware/OpeNITHM/Config.h index 96bfcae..f9b489e 100644 --- a/Firmware/OpeNITHM/Config.h +++ b/Firmware/OpeNITHM/Config.h @@ -38,6 +38,8 @@ // Uncomment this if you wish to ignore a falsly calibrated air sensor //#define IGNORE_AIR_CALIBRATION +// Uncomment this if you have lighted separators between the keys in your controller +// #define KEY_DIVIDERS // *** DO NOT CHANGE BELOW THIS LINE *** diff --git a/Firmware/OpeNITHM/OpeNITHM.ino b/Firmware/OpeNITHM/OpeNITHM.ino index d47b853..273c551 100644 --- a/Firmware/OpeNITHM/OpeNITHM.ino +++ b/Firmware/OpeNITHM/OpeNITHM.ino @@ -11,6 +11,9 @@ #include "SerialLeds.h" #include "SerialProcessor.h" #include "HelperClass.h" + +#include +#define USE_WS2812SERIAL #include SerialProcessor serialProcessor; @@ -25,6 +28,10 @@ byte serialBuffer[200]; bool updateLeds = false; bool useSerialLeds = false; int serialLightsCounter; +long lastMillis = 0; +int pollCount = 0; +int maxPollCount = 0; +int minPollCount = 1000; CRGB led_on; CRGB led_off; @@ -45,13 +52,15 @@ void setup() { FastLED.addLeds(leds, 16); #else //Uncomment and tune this value if you're having power issues - //FastLED.setMaxPowerInVoltsAndMilliamps(5,5OO); + FastLED.setBrightness(170); FastLED.addLeds(leds, 31); #endif - initializeController(); // Uncomment this to clear EEPROM, flash once, then comment and re-flash //for(int i = 0; i < 128; i++) EEPROM.put(i, 0); + + initializeController(); + lastMillis = millis(); } void initializeController() { @@ -96,7 +105,7 @@ void initializeController() { // Initialize air sensor if (sensor != NULL) delete sensor; - sensor = new AirSensor(500, 50); + sensor = new AirSensor(2000, 200); // Display the number of air sensors that were calibrated for (CRGB& led : leds) @@ -132,11 +141,35 @@ void initializeController() { #endif } -void loop() { - // Check for serial messages - if (Serial.available() >= 200) +void checkPollRate() { + pollCount++; + + if ((millis() - lastMillis) > 1000) { - Serial.readBytes(serialBuffer, 200); + if (pollCount > maxPollCount) + maxPollCount = pollCount; + if (pollCount < minPollCount) + minPollCount = pollCount; + + Serial.print(pollCount); + Serial.print("\t"); + Serial.print(minPollCount); + Serial.print("\t"); + Serial.println(maxPollCount); + + pollCount = 0; + lastMillis = millis(); + } +} + +void loop() { + // Uncomment this code to see benchmark in serial (in Hz) + // checkPollRate(); + + // Check for serial messages + if (Serial.available() >= 100) + { + Serial.readBytes(serialBuffer, 100); serialProcessor.processBulk(serialBuffer); } else @@ -152,6 +185,15 @@ void loop() { if (serialLightsCounter > 300) useSerialLeds = false; + // Process air sensor hand position +#if !defined(SERIAL_PLOT) && defined(USB) +#ifdef IR_SENSOR_KEY + output->sendSensor(sensor->getSensorReadings()); +#else + output->sendSensorEvent(sensor->getHandPosition()); +#endif +#endif + // Scan touch keyboard and update lights touchboard->scan(); int index = 0; @@ -249,15 +291,6 @@ void loop() { } #endif - // Process air sensor hand position -#if !defined(SERIAL_PLOT) && defined(USB) -#ifdef IR_SENSOR_KEY - output->sendSensor(sensor->getSensorReadings()); -#else - output->sendSensorEvent(sensor->getHandPosition()); -#endif -#endif - // Send update #if !defined(SERIAL_PLOT) && defined(USB) output->sendUpdate(); diff --git a/Firmware/OpeNITHM/PinConfig.h b/Firmware/OpeNITHM/PinConfig.h index d94c4a0..52ca09b 100644 --- a/Firmware/OpeNITHM/PinConfig.h +++ b/Firmware/OpeNITHM/PinConfig.h @@ -83,13 +83,13 @@ #endif // Lighting pin settings -#define LED_TYPE WS2812B -#define LED_ORDER GRB +#define LED_TYPE WS2812SERIAL +#define LED_ORDER BRG #ifdef TEENSY // Teensy LC #if defined(TEENSY_V1_0) #define RGBPIN 4 #elif defined(TEENSY_V1_1) -#define RGBPIN 11 +#define RGBPIN 24 #endif #else #define RGBPIN 16 // Pro Micro diff --git a/Firmware/OpeNITHM/SerialLeds.h b/Firmware/OpeNITHM/SerialLeds.h index cc54c5e..a2bab3c 100644 --- a/Firmware/OpeNITHM/SerialLeds.h +++ b/Firmware/OpeNITHM/SerialLeds.h @@ -9,6 +9,9 @@ #include "Config.h" #include + +#include +#define USE_WS2812SERIAL #include #define LIGHTS_FLAG 0xFF diff --git a/Firmware/OpeNITHM/SerialProcessor.cpp b/Firmware/OpeNITHM/SerialProcessor.cpp index 7ed28d8..d3fc840 100644 --- a/Firmware/OpeNITHM/SerialProcessor.cpp +++ b/Firmware/OpeNITHM/SerialProcessor.cpp @@ -27,12 +27,6 @@ void SerialProcessor::processConfigCommand(uint8_t* buf) bytes[4] = led_off.r; bytes[5] = led_off.g; bytes[6] = led_off.b; - - // slider sensitivity - bytes[7] = touchboard->getSensitivity(); - - // air sensitivity - bytes[8] = sensor->getAnalogSensitivity(); Serial.write(bytes, 200); break; @@ -49,13 +43,10 @@ void SerialProcessor::processConfigCommand(uint8_t* buf) serialLeds->saveLights(); break; case CMD_CALIBRATE_SLIDER: - touchboard->setSensitivity(buf[3]); touchboard->calibrateKeys(true); break; case CMD_CALIBRATE_AIR_SENSORS: - sensor->setAnalogSensitivity(buf[3]); sensor->recalibrate(); - break; case CMD_FACTORY_RESET: // clear EEPROM and then reset the controller for (int i = 0 ; i < EEPROM.length() ; i++) diff --git a/Firmware/OpeNITHM/SerialProcessor.h b/Firmware/OpeNITHM/SerialProcessor.h index 38b3e16..d9820a9 100644 --- a/Firmware/OpeNITHM/SerialProcessor.h +++ b/Firmware/OpeNITHM/SerialProcessor.h @@ -8,6 +8,8 @@ #include "Config.h" #include "SerialLeds.h" +#include +#define USE_WS2812SERIAL #include // magic bytes we look for in the packet headers to identify whether it's LED updates or config commands diff --git a/Firmware/Teensy/teensy3/touch.c b/Firmware/Teensy/teensy3/touch.c new file mode 100644 index 0000000..17e20aa --- /dev/null +++ b/Firmware/Teensy/teensy3/touch.c @@ -0,0 +1,118 @@ +/* Teensyduino Core Library + * http://www.pjrc.com/teensy/ + * Copyright (c) 2017 PJRC.COM, LLC. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * 1. The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * 2. If the Software is incorporated into a build system that allows + * selection among a list of target devices, then similar target + * devices manufactured by PJRC.COM must be included in the list of + * target devices and selectable in the same manner. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "core_pins.h" +//#include "HardwareSerial.h" + +#if defined(HAS_KINETIS_TSI) || defined(HAS_KINETIS_TSI_LITE) + +#if defined(__MK20DX128__) || defined(__MK20DX256__) +// These settings give approx 0.02 pF sensitivity and 1200 pF range +// Lower current, higher number of scans, and higher prescaler +// increase sensitivity, but the trade-off is longer measurement +// time and decreased range. +#define CURRENT 9 // 0 to 15 - current to use, value is 2*(current+1) +#define NSCAN 9 // number of times to scan, 0 to 31, value is nscan+1 +#define PRESCALE 2 // prescaler, 0 to 7 - value is 2^(prescaler+1) +static const uint8_t pin2tsi[] = { +//0 1 2 3 4 5 6 7 8 9 + 9, 10, 255, 255, 255, 255, 255, 255, 255, 255, +255, 255, 255, 255, 255, 13, 0, 6, 8, 7, +255, 255, 14, 15, 255, 12, 255, 255, 255, 255, +255, 255, 11, 5 +}; + +#elif defined(__MK66FX1M0__) +#define NSCAN 9 +#define PRESCALE 2 +static const uint8_t pin2tsi[] = { +//0 1 2 3 4 5 6 7 8 9 + 9, 10, 255, 255, 255, 255, 255, 255, 255, 255, +255, 255, 255, 255, 255, 13, 0, 6, 8, 7, +255, 255, 14, 15, 255, 255, 255, 255, 255, 11, + 12, 255, 255, 255, 255, 255, 255, 255, 255, 255 +}; + +#elif defined(__MKL26Z64__) +#define NSCAN 16 +#define PRESCALE 3 +static const uint8_t pin2tsi[] = { +//0 1 2 3 4 5 6 7 8 9 + 9, 10, 255, 2, 3, 255, 255, 255, 255, 255, +255, 255, 255, 255, 255, 13, 0, 6, 8, 7, +255, 255, 14, 15, 255, 255, 255 +}; + +#endif + + +// output is approx pF * 50 +// time to measure 33 pF is approx 0.25 ms +// time to measure 1000 pF is approx 4.5 ms + +int touchRead(uint8_t pin) +{ + uint32_t ch; + + if (pin >= NUM_DIGITAL_PINS) return 0; + ch = pin2tsi[pin]; + if (ch == 255) return 0; + + *portConfigRegister(pin) = PORT_PCR_MUX(0); + SIM_SCGC5 |= SIM_SCGC5_TSI; +#if defined(HAS_KINETIS_TSI) + TSI0_GENCS = 0; + TSI0_PEN = (1 << ch); + TSI0_SCANC = TSI_SCANC_REFCHRG(3) | TSI_SCANC_EXTCHRG(CURRENT); + TSI0_GENCS = TSI_GENCS_NSCN(NSCAN) | TSI_GENCS_PS(PRESCALE) | TSI_GENCS_TSIEN | TSI_GENCS_SWTS; + delayMicroseconds(10); + while (TSI0_GENCS & TSI_GENCS_SCNIP) ; // wait + delayMicroseconds(1); + return *((volatile uint16_t *)(&TSI0_CNTR1) + ch); +#elif defined(HAS_KINETIS_TSI_LITE) + TSI0_GENCS = TSI_GENCS_REFCHRG(4) | TSI_GENCS_EXTCHRG(7) | TSI_GENCS_PS(PRESCALE) + | TSI_GENCS_NSCN(NSCAN) | TSI_GENCS_TSIEN | TSI_GENCS_EOSF; + TSI0_DATA = TSI_DATA_TSICH(ch) | TSI_DATA_SWTS; + delayMicroseconds(10); + while (TSI0_GENCS & TSI_GENCS_SCNIP) ; // wait + delayMicroseconds(1); + return TSI0_DATA & 0xFFFF; +#endif +} + +#else + +int touchRead(uint8_t pin) +{ + return 0; // no Touch sensing :( +} + +#endif + diff --git a/readme.md b/readme.md index ad2779c..117de0f 100644 --- a/readme.md +++ b/readme.md @@ -44,6 +44,9 @@ If you are going to solder your sensors directly to the PCB, it is not necessary [9]: https://www.ebay.com/itm/100pcs-5mm-IR-Infrared-LED-940nm-Lamp-High-Power-Wide-Angle-Long-Range/251565825589 [10]: https://www.ebay.com/itm/100pcs-5mm-940nm-IR-LED-Infrared-Beams-Detector-Sensor-Black-Phototransistor/251816201528 +## Note on wiring: + +Until a new PCB design is made (should be fairly soon), in order to take full advantage of the firmware (or use it at all), you'll need to manually bridge pins 17 and 24 on your Teensy LC. This will be addressed in a future PCB revision, but it maximizes RGB LED throughput. ## Installing on Teensy LC @@ -59,6 +62,10 @@ Copy `Firmware/Teensy/boards.txt` to `arduino\hardware\teensy\avr\` and overwrit Copy `Firmware/Teensy/teensy3` to `arduino\hardware\teensy\avr\cores\teensy3` and overwrite any conflicts. +Copy `Firmware/FastLED/WS2812Serial.cpp` and `Firmware/FastLED/WS2812Serial.h` to `arduino\hardware\teensy\avr\libraries\WS2812Serial` and overwrite the existing. + +Copy `Firmware/FastLED/FastLED.cpp` and `Firmware/FastLED/FastLED.h` to `[My Documents]\Arduino\libraries\FastLED\` and overwrite the existing. + #### I am applying the changes manually (It is easier to copy and paste from the files in `Firmware/Teensy` instead of through here, the below is just for reference.) @@ -341,42 +348,11 @@ Prior to compilation, review the (numerous) options available to the end user in #### Configuring -Before use, the controller will need a few parameters set. This can easily be done using the Arduino Serial Monitor. - -The exact settings will vary depending on your setup, but I would try these as a starting point: -``` -tt50 -td50 -ta0.05 -``` - -Use the command `g` to confirm your changes registered. - -**NOTE:** Serial configuration will not work with serial lights. Disable this feature to allow for configuration. - -Per WinEpic: - -The touch detection system uses an exponential moving average (EMA) to detect changes in the read value. You need to tune 3 values: deadzone, threshold and alpha. - -- **Deadzone** is the maximum value for which a key will be considered "untouched". If the read value ever falls below the deadzone value, the key will return to being untouched. The higher this value, the "harder" you need to push the key before it is considered an input, and the faster it will return to neutral once you start lifting your finger. -- **Threshold** is how large the different between the detected input and the EMA must be for a touch event to occur. It is used for single touches as a way to prevent accidental double inputs, and for double touches to detect them. Increasing it makes the controller less responsive and increases the risk of touches not registering. Decreasing it makes fake inputs more likely, and also makes it harder for the controller to detect multitouch. -- **Alpha** is how much weight the last readout has in the EMA. It is usually very close to 0. If it is too high, inputs won't register as they will be considered too similar to the moving average. If it is too low, the moving average won't update properly causing touches / double touches to not be detected properly. - -Threshold and Deadzone values are expressed relative to the calibration baseline. For example, If a key reads 80 untouched and 100 touched, you're gonna want to set your deadzone to something around 15-20. Start with Alpha at 0.001 and slowly go up from there. - -You can configure it using commands sent over the serial port. All changes, aside from recalibrating, apply immediately and persist after restarting. - -- `tt ` changes the threshold. -- `td ` changes the deadzone. -- `ta ` changes the alpha. -- `tc` forces the controller to recalibrate, if you moved it to a different environment or accidentally touched it during initial calibration. -- `g` prints out the current configuration values. - -When tuning, you want to increase alpha until it feels like you're missing inputs, then go back down. +To be revised. #### Power On -At startup, the LEDs will flash orange 3 times. Do not hold your hands near the touchboard at this time. When the touchboard turns red, calibration begins. After the touchboard turns blue, calibration has finished. +To be revised. #### Output