Fix MicroPython “ValueError: invalid pin”
That GPIO number does not exist on this chip, or it is reserved for flash. Use the GPIO number (not the D-label or header pin number) of a pin that is broken out.
Community draft — report a mistake
What you see
MicroPython v1.24.1 on 2024-11-29; Generic ESP32 module with ESP32
>>> from machine import Pin
>>> relay = Pin(6, Pin.OUT)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid pinMicroPython v1.24.1 on 2024-11-29; Generic ESP32 module with ESP32 >>> from machine import Pin >>> relay = Pin(6, Pin.OUT) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid pin
ValueError: invalid pin is raised when you create a Pin with a number the firmware’s pin table does not contain. The fix is almost always to look up the GPIO number in the board pinout instead of using the label printed next to the header.
from machine import Pin
led = Pin(2, Pin.OUT) # NodeMCU D4 / ESP32 DevKit on-board LED
btn = Pin(34, Pin.IN) # ESP32 input-only pin: fine as an inputQuick fix — try in order
- 1
Use the GPIO number
MicroPython wants the chip’s GPIO number. NodeMCU “D4” is GPIO2 →
Pin(2); Pico physical pin 20 is GP15 →Pin(15). - 2
Avoid flash pins on the ESP32
GPIO 6–11 connect to the SPI flash and are rejected or crash the board. ESP32 GPIOs 20, 24 and 28–31 do not exist at all.
- 3
Input-only pins can’t be outputs
ESP32 GPIO 34–39 have no output driver —
Pin(34, Pin.OUT)fails (pin can only be input). Use them for buttons, sensors and ADC. - 4
Check the chip, not the board shape
ESP32-C3 has GPIO0–21 only; ESP32-S3 has no GPIO 22–25. Copying ESP32 pin numbers to a C3 SuperMini is a common source of this error.
Why it happens
Why does the same pin work in Arduino?
Arduino’s NodeMCU board package translates D-labels to GPIO numbers for you. MicroPython does not, so Pin(4) is GPIO4 = D2, not D4.
Pico W: the LED pin
On the Pico W the LED is on the Wi-Fi chip, so use Pin('LED', Pin.OUT). Pin(25) does not error, but the LED stays dark because GP25 is used by the radio.
Variant: “ValueError: invalid pin for I2C/UART/SPI”
The pin exists, but that peripheral cannot use it on the chosen bus. On the Pico see bad SCL pin.
Board-specific notes
ESP32: Safe general-purpose outputs: 4, 13, 16–19, 21–23, 25–27, 32, 33. Pin map on ESP32 DevKit V1.
ESP8266: D0=16, D1=5, D2=4, D3=0, D4=2, D5=14, D6=12, D7=13, D8=15 — see NodeMCU pinout.
ESP32-C3: See the C3 SuperMini pinout; GPIO 18/19 are the USB pins.
Did this fix it?
Thanks — that helps us keep this page right.