ESP8266: option to use NMI for PWM
Hi,
I detected some instabilities in the PWM output of the ESP8266 when the controller is handling WiFi traffic. Of course, that's no surprise, since the PWM is done in software. However, I figured out, that the issues can be mostly mitigated by using the NMI interrupt for the PWM. I guess, that's not something we want to be default, but as an option it would be nice.
The issue can be replicated by setting up a PWM output with an LED at a duty cycle of 50%. Then a simple script is needed, that echoes data on a TCP socket. When lots of data is thrown at the ESP, the LED will begin to flicker visibly.
The issue easiest to reproduce with heavy network traffic, but it will also occur more sporadically in lighter traffic environments.
Further, I'd suggest to replace the gpio_output_set calls in the interrupt handler with direct writes to the W1TC / W1TC registers to reduce time wasted in the interrupt.
esp32: Bound PWM duty value.
I had a potential out-of-boundary bug on an esp8266 device when setting the PWM duty value to control fan speed (negative value or >1023). On esp8266 the machine.PWM bounds the duty value:
https://github.com/micropython/micropython/blob/203e1d2a65273db3f6ff063ba1124a89c3482c0f/ports/esp8266/esppwm.c#L230-L236
...so I didn't notice it. The PWM behaviour was normal, just bounded to 0 and 1023.
When I switched my code to an esp32, the fan behaviour was really strange, because the PWM duty value is only binary ANDed:
https://github.com/micropython/micropython/blob/4eaebc1988699db6ebfd35fbe56a3e8d4cd0b373/ports/esp32/machine_pwm.c#L270
Negative values may be higher and bigger values lower. Combined with issue https://github.com/micropython/micropython/issues/5737 I thought first about a hardware problem...
This PR solves the problem and makes the esp32 PWM to have the same behaviour as esp8266/stm32 (AFAIK), by bounding the duty value between 0 and max PWM resolution. My previous buggy code works again :)