Programming The ESP32 In C - The S3's RGB LED |
Written by Harry Fairhead | |||
Tuesday, 24 September 2024 | |||
Page 2 of 2
There are examples of driving the NeoPixel, but they use either assembler or the RMT peripheral, However, the ESP32 S3 is just fast enough to be able to create the pulse times within the specified range: #include "driver/gpio.h" #include "freertos/FreeRTOS.h" void writeGRB(int pin, int GRB) { int mask = 0x800000; volatile int duty = 0; for (int j = 0; j < 24; j++) { gpio_set_level(pin, 1); if ((GRB & mask)) { for (volatile int i = 0; i < 3; i++) { } duty = 0; duty = 0; gpio_set_level(pin, 0); duty++; duty = 0; duty = 0; duty = 0; } else { duty = 0; gpio_set_level(pin, 0); for (volatile int i = 0; i < 5; i++) { } } mask = mask >> 1; } vTaskDelay(60 / portTICK_PERIOD_MS); } void app_main(void) { int pin = 48; gpio_reset_pin(pin); gpio_set_direction(pin, GPIO_MODE_OUTPUT); gpio_set_level(pin, 0); vTaskDelay(10 / portTICK_PERIOD_MS); int color = 0x0000FF; writeGRB(pin, color); vTaskDelay(1000 / portTICK_PERIOD_MS); color = 0x00FF00; writeGRB(pin, color); vTaskDelay(1000 / portTICK_PERIOD_MS); color = 0xFF0000; writeGRB(pin, color); vTaskDelay(1000 / portTICK_PERIOD_MS); } All of the work is done by the writeGRB function which uses time-wasting instructions to set the pulse times as near as possible to the specification. Setting a variable to zero is usually the smallest time delay you can create and incrementing a variable takes longer. The code was manually tuned by sending the signal to another GPIO line and using a logic analyzer to adjust the timings. If you try this out then, on an ESP32 S3, the timings are 350ns, 720ns and 1.23μs for zero high time, one high time and the total time respectively. These are within the permitted error. The same approach works with an ESP32 with a NeoPixel connected to a GPIO line but as it is slightly slower the for loop’s timing has to be modified: for (int j = 0; j < 24; j++) { gpio_set_level(pin, 1); if ((GRB & mask)) { for (volatile int i = 0; i < 2; i++) { } duty = 0; gpio_set_level(pin, 0); duty = 0; duty = 0; duty = 0; duty = 0; } else { gpio_set_level(pin, 0); for (volatile int i = 0; i < 3; i++) { } duty = 0; } With these changes, the timings are 370ns, 690ns and 1.22μsfor a T0H, T1H and the total time respectively. These are within the permitted error.
Programming The ESP32 In C
|
|||
Last Updated ( Friday, 25 October 2024 ) |