Programming The ESP32 In C - Phased Pulses |
Written by Harry Fairhead | |||
Tuesday, 25 February 2025 | |||
Page 2 of 2
Setting Multiple GPIO LinesThere is no way of using supplied SDK methods to change multiple GPIO lines at the same time, even though the hardware makes it possible. To do the job you need to write some code that accesses the hardware directly, see Chapter 19 for more details. In this chapter we simply present and make use of the function explained there: #include "soc/gpio_reg.h" void gpio_set(int32_t value,int32_t mask){ int32_t *OutAdd=(int32_t*) GPIO_OUT_REG; *OutAdd= (*OutAdd & ~mask) | (value & mask); } This works by directly accessing the GPIO registers. The function gpio_set uses a mask to determine which lines will be set and a value that gives the states to set them to. Any bits not set in the mask leave the corresponding GPIO line unchanged. It is easy to create a mask for any GPIO lines. For example, if you want to modify only lines GPIOn and GPIOm then the mask is: mask = 1<<n | 1<<m and so on if you have more lines to modify. The value can be constructed in the same way. If you want to set the lines to a and b then value is: value = a<<n | b<<m Notice that if the corresponding bit isn’t set in mask then the bit in value has no effect. That is, mask determines which bits you are going to modify and value determines what those bits are set to. Making use of this we can write the previous program without lags as when value and mask are used to update the GPIO register all of the lines change at once: #include <stdio.h> #include "driver/gpio.h" #include "freertos/FreeRTOS.h" #include "esp_rom_sys.h" #include "soc/gpio_reg.h" void gpio_set(int32_t value,int32_t mask){ int32_t *OutAdd=(int32_t*) GPIO_OUT_REG; *OutAdd= (*OutAdd & ~mask) | (value & mask); } void app_main(void) { gpio_reset_pin(2); gpio_set_direction(2, GPIO_MODE_OUTPUT); gpio_reset_pin(4); gpio_set_direction(4, GPIO_MODE_OUTPUT); int32_t mask = 1<<2 | 1<<4; int32_t value1= 0<<2| 1<<4; int32_t value2= 1<<2| 0<<4; while (1) { gpio_set(value1, mask); gpio_set(value2, mask); } } As we are changing the same pins each time, we only need a single mask. The value, however, changes each time. If you run this program you will see an almost perfect pair of out-of-phase 0.2µs pulses:
Summary
Programming The ESP32 In C
|
|||
Last Updated ( Tuesday, 25 February 2025 ) |