# TLDR
>[!TLDR] TLDR
>Use `machine.Pin(pin_number, machine.Pin.IN)` to read and `machine.Pin(pin_number, machine.Pin.OUT)` to write to digital pins on an [[ESP32]] using [[MicroPython]]. `pin.value()` reads, `pin.value(1)`/`pin.on()` sets high, and `pin.value(0)`/`pin.off()` sets low. Remember to consult the pinout diagram for your specific [[ESP32]] board.
# Information
Using digital pins on an [[ESP32]] with [[MicroPython]] is straightforward. Here's a breakdown of how to read and write digital values:
**1. Importing the `machine` module:**
```python
import machine # or
from machine import Pin
```
This module provides the necessary classes for interacting with hardware peripherals, including GPIO pins.
**2. Defining the pin:**
```python
pin = machine.Pin(pin_number, machine.Pin.IN) # For input
pin = machine.Pin(pin_number, machine.Pin.OUT) # For output
```
Replace `pin_number` with the actual GPIO pin number you want to use (e.g., 2, 4, 5, 12, etc.). Refer to the [[ESP32]] pinout diagram for your specific board to identify the GPIO numbers.
* `machine.Pin.IN` configures the pin for input.
* `machine.Pin.OUT` configures the pin for output.
**3. Optional: Setting pull-up/pull-down [[Resistores]] (for input pins):**
```python
pin = machine.Pin(pin_number, machine.Pin.IN, machine.Pin.PULL_UP) # Input with pull-up
pin = machine.Pin(pin_number, machine.Pin.IN, machine.Pin.PULL_DOWN) # Input with pull-down
```
Pull-up and pull-down [[Resistores]] are crucial for ensuring stable readings when the input isn't actively driven. A pull-up resistor weakly pulls the pin high, while a pull-down resistor weakly pulls it low.
**4. Reading a digital input:**
```python
value = pin.value()
```
This reads the current state of the pin. `value` will be 1 (high) or 0 (low).
**5. Writing a digital output:**
```python
pin.value(1) # Set the pin high (3.3V)
pin.value(0) # Set the pin low (0V)
# Alternatively, using the on() and off() methods:
pin.on() # Set the pin high
pin.off() # Set the pin low
```
**Key Considerations:**
* **Pinout:** Always consult the pinout diagram for your specific [[ESP32]] board. Pin numbers can vary.
* **Internal Pull-ups/Pull-downs:** The [[ESP32]] has internal pull-up [[Resistores]]. If you use `machine.Pin.IN` without specifying `PULL_UP` or `PULL_DOWN`, the internal pull-up will be enabled by default. However, it's good practice to explicitly define the pull-up/down behavior for clarity.
* **Debouncing:** Buttons can exhibit "bounce," where a single press registers as multiple presses. Debouncing techniques (like the short delay in the button example) are essential to prevent this.
* **Current Limitations:** [[ESP32]] GPIO pins have current limitations. Be mindful of the current draw of connected components and use appropriate current-limiting [[Resistores]] when necessary (especially with LEDs).