import machine
import utime
# === Addresses from RP2040 datasheet ===
RESETS_BASE = 0x4000C000
RESETS_RESET = RESETS_BASE + 0x0
RESETS_DONE = RESETS_BASE + 0x8
IO_BANK0_BASE = 0x40014000
SIO_BASE = 0xD0000000
PADS_BANK0_BASE = 0x4001C000
# GPIO 0 registers
GPIO0_CTRL = IO_BANK0_BASE + 0x004
GPIO0_PAD = PADS_BANK0_BASE + 0x004
GPIO_FUNC_SIO = 5
# === Enable IO_BANK0, SIO and PADS_BANK0 peripherals ===
mask = (1 << 5) | (1 << 1) | (1 << 8) # bit 5=IO_BANK0, bit 1=SIO, bit 8=PADS_BANK0
machine.mem32[RESETS_RESET] &= ~mask
while (machine.mem32[RESETS_DONE] & mask) != mask:
pass
# === Configure GPIO 0 pad with pull-up ===
# Clear the register first, then set pull-up
machine.mem32[GPIO0_PAD] = 0x00000000 # Clear all
machine.mem32[GPIO0_PAD] = (1 << 3) | (1 << 1) | (1 << 6) | (1 << 7) # PUE + SCHMITT + IE + OD
# === Set GPIO 0 function to SIO ===
machine.mem32[GPIO0_CTRL] = GPIO_FUNC_SIO
# === Ensure GPIO 0 is input ===
SIO_GPIO_OE = SIO_BASE + 0x024
machine.mem32[SIO_GPIO_OE] &= ~(1 << 0)
# === GPIO reading ===
SIO_GPIO_IN = SIO_BASE + 0x004
def read_gpio(pin):
value = (machine.mem32[SIO_GPIO_IN] >> pin) & 1
print(f"GPIO{pin} = {value}")
return value
# Test - should show 1 when button not pressed, 0 when pressed
while True:
read_gpio(0)
utime.sleep(0.2)