XIAO-ESP32C6 : reading gpio input register

In case helpful to others, below is C code I wrote to read a single GPIO pin on the XIAO-ESP32C6 module.

// Code to read xiao-esp32c6 pin (D3) using register gpio operationd and mask out bit 21

#include <Arduino.h>
#include <stdint.h>
#include <LibPrintf.h>

#define GPIO_IN_REG 0x6009103C    // ESP32C6 GPIO_IN_REG address
#define GPIO_PIN_D3 21

volatile uint32_t* gpio_in_reg = (volatile uint32_t*) GPIO_IN_REG;
uint32_t mask = (1 << GPIO_PIN_D3);  // Extract the 21st bit - i.e., 2^21
uint32_t result;

void setup() {
  pinMode(GPIO_PIN_D3, INPUT);  // Sets the IO_MUX correctly
  Serial.begin(115200);
  delay(100); // Add delay to give library time to initialize
}

void loop() {
  printf("Pin D3 state = %ld\n",*gpio_in_reg);
  //printf("mask = %ld\n",mask);
  result = *gpio_in_reg&mask;
  result = (result >> GPIO_PIN_D3);
  printf("Bit21 = %ld\n\n",result);
  delay(5000);
}
1 Like