#include <Arduino.h>
#define led_pin 2 // Define 2 as led_pin
// --- DIRECCIONES DE REGISTROS PARA ESP32-C3 ---
// Referencia: ESP32-C3 Technical Reference Manual (Capítulo GPIO)
// Base del GPIO: 0x60004000
// Registro para Habilitar salida (Enable Write 1 To Set) - Offset 0x0024
#define C3_GPIO_ENABLE_W1TS_REG 0x60004024
// Registro para poner Salida en ALTO (Output Write 1 To Set) - Offset 0x0008
#define C3_GPIO_OUT_W1TS_REG 0x60004008
// Registro para poner Salida en BAJO (Output Write 1 To Clear) - Offset 0x000C
#define C3_GPIO_OUT_W1TC_REG 0x6000400C
// Creación de punteros a direcciones de memoria
// Usamos 'volatile' para que el compilador no optimice ni elimine estas líneas
volatile uint32_t *gpio_enable_w1ts = (volatile uint32_t *)C3_GPIO_ENABLE_W1TS_REG;
volatile uint32_t *gpio_out_w1ts = (volatile uint32_t *)C3_GPIO_OUT_W1TS_REG;
volatile uint32_t *gpio_out_w1tc = (volatile uint32_t *)C3_GPIO_OUT_W1TC_REG;
extern "C" {
void asm_setup_gpio();
void asm_led_on();
void asm_led_off();
}
// ------------------------------------------------------------
// Función genérica para escribir en registro usando Assembler Inline (RISC-V)
// ------------------------------------------------------------
void asm_write_register(uint32_t address, uint32_t value) {
asm volatile (
"sw %0, 0(%1)\n" // Instrucción RISC-V: Store Word.
// Guarda el contenido de %0 en la dirección de memoria contenida en %1 con offset 0.
// Equivalente a: *(uint32_t*)address = value;
: // Salidas: ninguna
: "r"(value), // Entrada %0: El valor (máscara de bits) se carga en un registro cualquiera
"r"(address) // Entrada %1: La dirección se carga en otro registro cualquiera
: "memory" // Clobber: Avisamos al compilador que hemos modificado la memoria
);
}
void setup() {
Serial.begin(9600);
//pinMode(led_pin, OUTPUT); //Setting led_pin as output
// 1. Configuración usando registros directos:
//*gpio_enable_w1ts = (1 << led_pin);
//asm_setup_gpio();
asm_write_register( C3_GPIO_ENABLE_W1TS_REG , 1 << led_pin );
}
void loop() {
//digitalWrite(led_pin, HIGH); // Switch the led_pin on
//*gpio_out_w1ts = (1 << led_pin);
//asm_led_on();
asm_write_register(C3_GPIO_OUT_W1TS_REG, 1 << led_pin);
delay(1000); // Wait for a second
//digitalWrite(led_pin, LOW); // Switch the led_pin off
//*gpio_out_w1tc = (1 << led_pin);
//asm_led_off();
asm_write_register(C3_GPIO_OUT_W1TC_REG, 1 << led_pin);
delay(1000); // Wait for a second
}