Skip to content

Rewrite of fastpin_esp32.h -- take 2 - #625

Merged
focalintent merged 39 commits into
FastLED:masterfrom
samguyer:master
Aug 26, 2018
Merged

focalintent merged 39 commits into
FastLED:masterfrom
samguyer:master

Conversation

@samguyer

@samguyer samguyer commented Jul 9, 2018

Copy link
Copy Markdown
Contributor

I just fixed the code formatting, which was ugly.

samguyer and others added 30 commits August 5, 2017 13:27
Credit to Rina Shkrabova for the first cut.
I think there was actually an error in the interrupt enabling/disabling, but I also cleaned it up so that it is more clear how interrupts are handled.
Not fully portable yet, though. The timing numbers are hard-wired for WS2812, and the RMT channel is also hard-wired.
Timing is now computed from T1, T2, amd T3 instead of being hard-wired.
The RMT signal is sent in 10-pixel chunks, using double-buffering to hide the latency when possible. Also: assign RMT channels sequentially.
We were not doing the conversion from ESP32 cycles to RMT cycles correctly. Now it all works!
On ESP platforms the dev kit provides the function __cxa_pure_virtual, so there is no need to define it.
for chipsets that need it (for example TM1829)
Suggested by @h3ndrik : allocated the interrupt once at the initialization and then just turn it on and off. This is the strategy that the ESP32 core uses also.
Two major changes to the RMT driver. First, I realized that we can have only one interrupt handler attached to the RMT peripheral, so it needs to be able to handle all of the attached strips. To accomplish this, I store each ClocklessController in an array indexed by its RMT channel. The interrupt handler can then take the channel that triggered it and index into the array to get the right controller.

The second major change is that I replaced all of the explicit bit twiddling of the RMT configurartion with calls to the proper functions in ESP32 core. That should make the code more stable if the core changes.
Since the interrupt handler is global for all channels, we need to store not just the controller, but also the buffer refill function for each strip.
This version of DemoReel100 spins off a separate task on core 0 that just performs the FastLED.show() operations. Regular code running on core 1 (the default for Arduino) signals this task to request a show().
Replaced a 500ms delay in the show task with MAX_DELAY. There's really no point in timing out (and crashing the program) just because the application hasn't called show.
Reworked the code again in order to support parallel output, which is now the default mode. You can also now ask it to use the built-in RMT driver if you have other parts of your code that need the RMT peripheral.

Two #defines control choices -- put either or both of these before including FastLED.h:

#define FASTLED_RMT_CORE_DRIVER

Uses the ESP core RMT driver. To do this, though, it allocates a big buffer to hold all of the pixel bits, so there is a memory and compute cost.

#define FASTLED_RMT_SERIAL_OUTPUT

Force serial output of each strip.
Describing the implementation and the compile-time switches
The previous checkin had bugs in the syncronization that caused problems in parallel mode when strips are different lengths.
Made the code bullet-proof in a few ways, but most importantly fixed a terrible integer underflow bug in the code that fills the RMT buffer.
The big change in this version is the ability to support more than 8 controllers. Instead of assigning RMT channels to controllers in a fixed mapping, channels are assigned on the fly, allowing the driver to reuse channels as they become available.
Didn't mean to check these in.
Fixed the code so that it works with the built-in RMT driver. There's nothing special to do to enable it -- just #define FASTLED_RMT_BUILTIN_DRIVER true
Fixing some documentation and configuration stuff
samguyer added 2 commits July 8, 2018 19:54
I've been needing to rewrite fastpin_esp32.h for the ESP32 ports and masks. This file also makes sure we don't use pins that won't work, even with clockless chips like the WS2812.
Which were making the code ugly.
Comment thread FastLED.cpp
{
#ifndef ESP8266
#if !defined(ESP8266) && !defined(ESP32)
extern "C" void __cxa_pure_virtual (void) {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you know, it dawns on me that I could probably make this a weak symbol...

Comment thread fastled_delay.h

// ESP32 core has it's own definition of NOP, so undef it first
#ifdef ESP32
#undef NOP

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gyah -- there's a reason why, with the CRGBW/CRGB16 re-write I'm re-doing all the macros to be prefaced with FASTLED_ or FL_ ...

@focalintent focalintent left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a few notes/change requests

Comment thread platforms/esp/32/fastpin_esp32.h Outdated
// inline static void hi() __attribute__ ((always_inline)) { gpio_set_level((gpio_num_t)PIN, HIGH); }
inline static void hi() __attribute__ ((always_inline)) {
if (PIN < 32) GPIO.out_w1ts = MASK;
else if(PIN < 34) GPIO.out1_w1ts.val = MASK;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you make this >= 32? This way if an esp32 board comes out that exposes more pins on the secondary controller, this will still work. Ditto for the other set below

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No problem. I copied that log directly from the ESP-IDF core, though. I think the reason they write it like that is that there are pins 35-39, but they are input only.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Espressif's internal headers seem to indicate that 35-39 could also be for out - from https://github.com/espressif/esp-idf/blob/master/components/soc/esp32/include/soc/gpio_struct.h --

    union {
        struct {
            uint32_t data:       8;                 /*GPIO32~39 output value*/
            uint32_t reserved8: 24;
        };
        uint32_t val;
    } out1;
    union {
        struct {
            uint32_t data:       8;                 /*GPIO32~39 output value write 1 to set*/
            uint32_t reserved8: 24;
        };
        uint32_t val;
    } out1_w1ts;
    union {
        struct {
            uint32_t data:       8;                 /*GPIO32~39 output value write 1 to clear*/
            uint32_t reserved8: 24;
        };
        uint32_t val;
    } out1_w1tc;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Totally up to you. I'm using the Espressif implementations of the various pin functions as my guide (e.g., their version of digitalWrite) -- it seemed like the most likely to work. I can try something different, but I'll have to do some testing to make sure it works.

Comment thread platforms/esp/32/fastpin_esp32.h Outdated
inline static void strobe() __attribute__ ((always_inline)) { toggle(); toggle(); }

inline static void toggle() __attribute__ ((always_inline)) { if (PIN < OUTPUT_PIN_LIMIT){ _GPB0._GPO = MASK; } }
inline static void toggle() __attribute__ ((always_inline)) { }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs an implementation - e.g. something like:

  GPIO_OUT_REG ^= MASK;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need to think about this one.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is where you would use the GPIO.out register - honestly I'm disappointed that Espressif didn't also add a toggle gpio register - but their gpio architecture seems a little hacky at times. Anyway - this would literally just be:

  if(PIN < 32) { GPIO.out ^= MASK; } else { GPIO.out1.val ^=MASK; }

Comment thread platforms/esp/32/fastpin_esp32.h Outdated
inline static port_ptr_t port() __attribute__ ((always_inline)) { if(PIN<OUTPUT_PIN_LIMIT) { return &_GPB0._GPO; }}
inline static port_ptr_t sport() __attribute__ ((always_inline)) { if (PIN<OUTPUT_PIN_LIMIT) {return &_GPB0._GPOS; }}
inline static port_ptr_t cport() __attribute__ ((always_inline)) { if (PIN<OUTPUT_PIN_LIMIT) {return &_GPB0._GPOC; }}
inline static port_t hival() __attribute__ ((always_inline)) { return MASK; }

@focalintent focalintent Jul 9, 2018 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hival/loval are used as an optimization in bitbang'd spi output - to avoid a few rounds of bitwise operators. hival is the "write this value to the I/o register to make this pin high" while loval is the "write this value to the I/o register to make the pin low" -- so the value that's returned is the full state of the I/o register, adjusted for whether we want this pin to be high or low - for example:

	inline static port_t hival() __attribute__ ((always_inline)) { return ((PIN<32) ? GPIO.out : GPIO.out1.val) | _MASK; }
	inline static port_t loval() __attribute__ ((always_inline)) { return ((PIN<32) ? GPIO.out : GPIO.out1.val)  & ~_MASK; }

Meanwhile port returns the register itself - as in a pointer to the register:

    inline static port_ptr_t port() ((always_inline)) { return (PIN < 32) ? &GPIO.out : &GPIO.out1); }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The way it seems to work on the ESP32 is that you use the same mask regardless of whether you want to set a pin high or low -- the difference is which register you write that mask to. That is, hival and lowval are the same, the difference is sport vs cport. The port() method will never work for this reason.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - most higher end arm/32 bit cores have all three types of register - a 32-bit register that gives the current hi/lo values for all 32 pins on that port, a 32-bit register that, when you write to it turns on any pin that has a corresponding 1 bit in the written value, and a 32-bit register that, when you write to it, turns off any pin that has a corresponding 1 bit in the written value. - for the ESP32 there's GPIO.out - which is the port register - which, if I understand correctly you can use to read the state of an output only pin (whether it is hi or low) - as well as bulk set the value (both hi and low) of multiple pins at the same time. This is along side the out_w1tc which is the "write 1's to clear pins" and the out_w1ts "write 1's to set pins" (the c and s suffixes on those make it clear which one they are)- so, if you use GPIO.out then hival/lowval and port will in fact work the way that the rest of the library is expecting it to.

From the gpio_struct header file:

    uint32_t out;                                   /*GPIO0~31 output value*/
    uint32_t out_w1ts;                              /*GPIO0~31 output value write 1 to set*/
    uint32_t out_w1tc;                              /*GPIO0~31 output value write 1 to clear*/

There are also a variety of other possible port options. Some arm platforms have a toggle register, where any bit in the 32-bit value that you write that has a 1 will flip the state of the associated pin (hi to low or low to high). Then there's also yet another register writing technique called "bit-banding" - where a virtual address space is exploded out so that each pin has 4 32-bit memory locations - an out, a set, a clear, and a toggle - and writing any value will do the appropriate action with the pin - the nice thing about this is any non-zero value triggers the action (setting the value, setting the pin hi, setting it low, toggling it) - which is a nice way to short circuit the whole "if (someValue != 0) GPIO.set = MASK; else GPIO.clear = MASK;" - you can just do bitband[pin].val = someValue;

So - yes, port, hival, and lowval can work the way it does for other platforms. The GPIO.out register is how, among other things, you would ask "Is pin 24 hi or low right now?" (the w1tc and w1ts registers are effectively write only, there's nothing meaningful to read from them).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading up on this question: it is definitely possible to implement all the functions by accessing the GPIO.out register. The only downside I see (which is very minor) is that it is slower because it requires three instructions: read, bit-op, write. Using the GPIO.out_wtx registers requires only a write.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right - which is why hi should use the out_w1ts and lo should use the out_w1tc - but port/hival/lowval specifically work with the out register. There's other code in FastLED (and other private code I have that uses FastPin) that makes use of this - and again, something low level like FastPin I want to work reliably the same way across all the platforms, which is why i'm being a stickler about this.

// _DEFPIN_ESP32(16,11);

#endif
_DEFPIN_32_33_ESP32(32);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that according to https://github.com/espressif/esp-idf/blob/master/components/soc/esp32/include/soc/gpio_struct.h - this can go up to pin 39 - even if no boards are exposing anything above 32/33 yet.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pins 34-39 are input only.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For now : )

@focalintent

Copy link
Copy Markdown
Contributor

Also - what's a bit strange is that this diff appears to be happening against an older version of master - which may be the reason for the conflicts that are identified by GitHub.

@samguyer

Copy link
Copy Markdown
Contributor Author

I resolved the conflicts, but I need to decide what to do about the issues you cite above.

Added proper definitions for port() and toggle() to use the GPIO.out register. Changed the pin number test to avoid unnecessary conditions.
@samguyer

Copy link
Copy Markdown
Contributor Author

OK, take a look now. The only minor issue I see is that there is an implicit constraint that the values returned by hival() and loval() should only be used with the register returned by port(), not the ones return by sport() and cport().

I'm also not sure if fastset() will work properly, since it doesn't read the register state and mask in only the bits that should be changed.

Comment thread platforms/esp/32/fastpin_esp32.h Outdated

#ifdef FASTLED_ESP32_RAW_PIN_ORDER
_DEFPIN_ESP32(0);
// _DEFPIN_ESP32(1); Using TX causes flashiness when uploading

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't block the use of these pins -- yes rx/tx are used if you're flashing via USB - but not if you're flashing wirelessly - also, a deployed device will spend far more of it's life running than being flashed.


// -- Store the GPIO pin
gpio_num_t mPin;
<<<<<<< HEAD

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure if you meant to leave this checked in as part of the PR - especially in a conflicted state?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see that in my branch. Maybe I checked in the orig file by accident.

@focalintent

Copy link
Copy Markdown
Contributor

The whole point of fastset is pre-computing the hi/lo register values to write to the out register before pushing out a set of led data so that you weren't doing the the read/bit-operation/write cycle of writing using the out register - plus it works on platforms where there is only one out register (and no dedicated set/clear registers).

The other point of fastset is allowing the setting of multiple pins simultaneously in one cycle (or two if the underlying hardware is two cycle writes to i/o registers) vs. one (or two) per pin that you want to set the state of - and using fastset you don't need to be setting the pins to the same value (e.g. you can set a few high while setting others low).

sport/cport are there for a combination of completness, but also because there can also be value in bulk setting/clearing pins, and wanted a standard way for that in FastPin.

@samguyer

Copy link
Copy Markdown
Contributor Author

I'm not sure I understand your logic about avoiding the read/bit-op/write cycle. Given that there are a lot of pins, you don't want to change the state of pins that are not doing any FastLED stuff (other sensors and actuators). So, to change a single pin using just the GPIO.out register you have to read its current value, combine that with the new value, then write it back. Seems like more operations than just writing to the set/clear registers. I totally get the consistency argument, but I don't see the performance argument.

It might be worth noting in the code that the values provided by hival and loval will not necessarily work with the registers returned by sport and cport.

@focalintent

Copy link
Copy Markdown
Contributor

I'm not sure I understand your logic about avoiding the read/bit-op/write cycle.

Again - this is an optimization that I use in some cases cases where I know for sure nothing else will be modifying the pins during the output. I read the state of the port register - pre-compute the values that I want for the various pin states that will happen as I do the output - and then write those pre-computed values out to the port register while writing out the data - so outside of that pre-computing, it's just a series of writes. And again, I want the FastPin class's functionality to be consistent across platforms even if you don't see an immediate use for it.

I can add a comment to the code that the hival/loval values are meant to be used with just the port register - but I know how port/sport/cport are supposed to work along with hival/loval (which is why I keep asking you to make them work that way) - i've used the sport/cport values in the past to determine whether or not two pins are on the same port, and then combine masks appropriately when setting values to do it in a single write operation.

The other reason for having these methods is because I can then get that value and store it in a register - for example on arm systems, port operations end up being writes to known memory addresses - gcc often represents these as "constant load to register ; write mask to register2 ; write register2 to the address in register;" - and then re-uses register, so the next port write ends up getting an extra 2 cycles attached to it loading the constant. When I can pre-compute/pre-cache values I can keep them in registers and replace a 2 cycle read, a 1 cycle constant load, and a 2 cycle write with just a single 2 cycle write.

This should be the right set of definitions -- consistent with the other platforms.
@samguyer

Copy link
Copy Markdown
Contributor Author

OK, I think I finally got it. The definitions of hival() and loval() now do the proper read of the register first, then add in the new bits, so that set() will work properly. I also fixed a few other small things. See what you think now...

Do not merge this code
@focalintent

Copy link
Copy Markdown
Contributor

@samguyer, I can't selectively merge only some commits from this PR with Github's UI - is it ok to take in the experimental change as well? As for why that change fixes things - it is likely because the pixel data structure is large enough that the constant allocating/deleting of it was fragmenting the hell out of the esp32's memory until eventually you got to the point where there wasn't any memory left. Dynamic allocation is the devil on these MCUs - I tend to prefer not using it at all, and if I have to, finding ways to use it once.

@samguyer

samguyer commented Jul 20, 2018 via email

Copy link
Copy Markdown
Contributor Author

@focalintent

Copy link
Copy Markdown
Contributor

memory usage is the price paid for using a mechanism like this - the OctoWS2811 driver has to make a similar tradeoff. The alternative would be blocking on returning from showPixels until the frame data is fully written out - then you can just use a reference to the PixelController object that's passed in instead of allocating/deallocating a copy.

@samguyer

samguyer commented Jul 21, 2018 via email

Copy link
Copy Markdown
Contributor Author

The previous version of this code saved a copy of the PixelController every time show() is called. It appears that this causes massive memory fragmentation, eventually locking up the processor. This new version saves the pixel data is a separate buffer that is allocated only one time.
@samguyer

Copy link
Copy Markdown
Contributor Author

@focalintent I just pushed a new version that saves the pixel data in a separate buffer. I tested it myself, and there is one other user who can vouch for it.

Nothing major here. Added comments and put the functions is a better order. Added some defensive programming.
@focalintent
focalintent merged commit de4594b into FastLED:master Aug 26, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants