Skip to content

Commit a25513a

Browse files
committed
Example of using ESP32 pins as GPIO
1 parent f523b23 commit a25513a

File tree

2 files changed

+266
-0
lines changed

2 files changed

+266
-0
lines changed

examples/gpio/esp32spi_gpio.py

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
import board
2+
import busio
3+
import time
4+
import random
5+
from digitalio import DigitalInOut, Direction
6+
from analogio import AnalogIn
7+
import pulseio
8+
from adafruit_esp32spi import adafruit_esp32spi
9+
10+
11+
"""
12+
ESP32SPI Digital and Analog Pin Reads & Writes
13+
14+
This example targets a Feather M4 or ItsyBitsy M4 as the CircuitPython processor,
15+
along with either an ESP32 Feather or ESP32 Breakout as Wi-Fi co-processor.
16+
You may need to choose different pins for other targets.
17+
"""
18+
19+
20+
def esp_reset_all():
21+
esp_reset()
22+
esp_debug()
23+
esp_init_pin_modes(ESP_D_R_PIN, ESP_D_W_PIN)
24+
25+
def esp_reset(wait=1):
26+
"""
27+
CAUTION this will re-initialize the ESP32 pin modes and debug level
28+
"""
29+
esp.reset()
30+
time.sleep(wait)
31+
32+
def esp_debug(local=0, remote=True):
33+
# ESP32SPI CircuitPython library serial debug on M4 TX
34+
esp._debug = local # 0, 1, 2, 3
35+
36+
# NINA serial debug on ESP32 TX
37+
esp.set_esp_debug(remote) # False, True
38+
39+
def esp_init_pin_modes(din, dout):
40+
# ESP32 Digital Input
41+
esp.set_pin_mode(din, 0x0)
42+
43+
# ESP32 Digital Output (no output on pins 34-39)
44+
esp.set_pin_mode(dout, 0x1) # Red LED on ESP32 Feather and ESP32 Breakout
45+
46+
def esp_status_text(n):
47+
t = {0: 'WL_IDLE_STATUS',
48+
1: 'WL_NO_SSID_AVAIL',
49+
2: 'WL_SCAN_COMPLETED',
50+
3: 'WL_CONNECTED',
51+
4: 'WL_CONNECT_FAILED',
52+
5: 'WL_CONNECTION_LOST',
53+
6: 'WL_DISCONNECTED',
54+
7: 'WL_AP_LISTENING',
55+
8: 'WL_AP_CONNECTED',
56+
9: 'WL_AP_FAILED',
57+
10: 'WL_NO_SHIELD', }
58+
if n in t:
59+
return t[n]
60+
else:
61+
return 'WL_UNDEFINED'
62+
63+
64+
# M4 R/W Pin Assignments
65+
M4_D_W_PIN = DigitalInOut(board.A1) # digital write to ESP_D_R_PIN
66+
M4_D_W_PIN.direction = Direction.OUTPUT
67+
M4_A_R_PIN = pulseio.PulseIn(board.A0, maxlen=64) # PWM read from ESP_A_W_PIN
68+
M4_A_R_PIN.pause()
69+
70+
# ESP32 R/W Pin assignments
71+
ESP_D_R_PIN = 12 # digital read from M4_D_W_PIN
72+
ESP_D_W_PIN = 13 # digital write to Red LED on Feather ESP32 and ESP32 Breakout
73+
# ESP32 Analog Input using ADC1
74+
# esp.set_pin_mode(36, 0x0) # Hall Effect Sensor
75+
# esp.set_pin_mode(37, 0x0) # Not Exposed
76+
# esp.set_pin_mode(38, 0x0) # Not Exposed
77+
# esp.set_pin_mode(39, 0x0) # Hall Effect Sensor
78+
# esp.set_pin_mode(32, 0x0) # INPUT OK
79+
# esp.set_pin_mode(33, 0x0) # DO NOT USE: ESP32SPI Busy/!Rdy
80+
# esp.set_pin_mode(34, 0x0) # INPUT OK
81+
# esp.set_pin_mode(35, 0x0) # INPUT OK (1/2 of Battery on ESP32 Feather)
82+
ESP_A_R_PIN = 32 # analog read from 10k potentiometer
83+
# ESP32 Analog (PWM/LEDC) Output (no output on pins 34-39)
84+
ESP_A_W_PIN = 27 # analog (PWM) write to M4_A_R_PIN
85+
86+
spi = board.SPI()
87+
# Airlift FeatherWing & Bitsy Add-On compatible
88+
esp32_cs = DigitalInOut(board.D13) # M4 Red LED
89+
esp32_ready = DigitalInOut(board.D11)
90+
esp32_reset = DigitalInOut(board.D12)
91+
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
92+
93+
esp_reset_all()
94+
95+
espfirmware = ''
96+
for _ in esp.firmware_version:
97+
if _ == 0:
98+
break
99+
else:
100+
espfirmware += "{:c}".format(_)
101+
print('ESP32 Firmware:', espfirmware)
102+
103+
esp_MAC_address = esp.MAC_address
104+
print("ESP32 MAC: {5:02X}:{4:02X}:{3:02X}:{2:02X}:{1:02X}:{0:02X}".format(*esp_MAC_address))
105+
106+
print('ESP32 Status: ', esp.status, esp_status_text(esp.status), 'Connected?', esp.is_connected)
107+
108+
# initial digital write values
109+
m4_d_w_val = False
110+
esp_d_w_val = False
111+
112+
while True:
113+
print()
114+
print('ESP32 DIGITAL:')
115+
116+
# ESP32 digital read
117+
try:
118+
M4_D_W_PIN.value = m4_d_w_val
119+
print('M4 wrote:', m4_d_w_val, end=' ')
120+
# b/c ESP32 might have reset out from under us
121+
esp_init_pin_modes(ESP_D_R_PIN, ESP_D_W_PIN)
122+
esp_d_r_val = esp.set_digital_read(ESP_D_R_PIN)
123+
print('--> ESP read:', esp_d_r_val)
124+
except (RuntimeError, AssertionError) as e:
125+
print('ESP32 Error', e)
126+
esp_reset_all()
127+
128+
# ESP32 digital write
129+
try:
130+
# b/c ESP32 might have reset out from under us
131+
esp_init_pin_modes(ESP_D_R_PIN, ESP_D_W_PIN)
132+
esp.set_digital_write(ESP_D_W_PIN, esp_d_w_val)
133+
print('ESP wrote:', esp_d_w_val, '--> Red LED')
134+
except (RuntimeError) as e:
135+
print('ESP32 Error', e)
136+
esp_reset_all()
137+
138+
print('ESP32 ANALOG:')
139+
140+
# ESP32 analog read
141+
try:
142+
esp_a_r_val = esp.set_analog_read(ESP_A_R_PIN)
143+
print('Potentiometer --> ESP read: ', esp_a_r_val,
144+
' (', '{:1.1f}'.format(esp_a_r_val*3.3/65536), 'v)', sep='')
145+
except (RuntimeError, AssertionError) as e:
146+
print('ESP32 Error', e)
147+
esp_reset_all()
148+
149+
# ESP32 analog write
150+
try:
151+
# don't set the low end to 0 or the M4's pulseio read will stall
152+
esp_a_w_val = random.uniform(0.1, .9)
153+
esp.set_analog_write(ESP_A_W_PIN, esp_a_w_val)
154+
print('ESP wrote: ', '{:1.2f}'.format(esp_a_w_val),
155+
' (', '{:d}'.format(int(esp_a_w_val*65536)), ')',
156+
' (', '{:1.1f}'.format(esp_a_w_val*3.3), 'v)',
157+
sep='', end=' ')
158+
159+
# ESP32 "analog" write is a 1000Hz PWM
160+
# use pulseio to extract the duty cycle
161+
M4_A_R_PIN.clear()
162+
M4_A_R_PIN.resume()
163+
while len(M4_A_R_PIN) < 2:
164+
pass
165+
M4_A_R_PIN.pause()
166+
duty = M4_A_R_PIN[0] / (M4_A_R_PIN[0] + M4_A_R_PIN[1])
167+
print('--> M4 read: ', '{:1.2f}'.format(duty),
168+
' (', '{:d}'.format(int(duty*65536)), ')',
169+
' (', '{:1.1f}'.format(duty*3.3), 'v)',
170+
' [len=', len(M4_A_R_PIN), ']', sep='')
171+
172+
except (RuntimeError) as e:
173+
print('ESP32 Error', e)
174+
esp_reset_all()
175+
176+
# toggle digital write values
177+
m4_d_w_val = not m4_d_w_val
178+
esp_d_w_val = not esp_d_w_val
179+
180+
time.sleep(5)

examples/gpio/gpio.md

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Using ESP32 co-processor GPIO pins with CircuitPython ESP32SPI
2+
3+
As of NINA firmware version 1.3.1, the ESP32SPI library can be used to write digital values to many of the ESP32 GPIO pins using CircuitPython. It can also write "analog" signals using a float between 0 and 1 as the duty cycle (which is converted to an 8-bit integer for use by the NINA firmware). Keep in mind that these are 1000Hz PWM signals using the ESP32 LED Control peripheral, not true analog signals using an on-chip DAC. More information can be found here:
4+
<https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/ledc.html>
5+
6+
As of NINA firmware version 1.5.0, the ESP32SPI library can be used to read digital signals from many of the ESP32 GPIO pins using CircuitPython. It can also read analog signals using ESP32 on-chip ADC1. The ESP32 can theoretically be set to use between 8 and 12 bits of resolution for analog reads. For our purposes, it is a 12-bit read within the NINA firmware, but the CircuitPython library converts it to a 16-bit integer consistent with CircuitPython `analogio` `AnalogIn`. There's an optional keyword argument in the `set_analog_read(self, pin, atten=ADC_ATTEN_DB_11)` function that changes the attenuation of the analog read, and therefore also changes the effective voltage range of the read. With the default 11dB attenuation, Espressif recommends keeping input voltages between 150mV to 2450mV for best results. More information can be found here:
7+
<https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/adc.html>
8+
9+
## GPIO Pins available to ESP32SPI
10+
11+
```
12+
# ESP32_GPIO_PINS:
13+
# https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/blob/master/adafruit_esp32spi/digitalio.py
14+
# 0, 1, 2, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 32, 33, 34, 35, 36, 39
15+
#
16+
# Pins Used for ESP32SPI
17+
# 5, 14, 18, 23, 33
18+
19+
# Avialable ESP32SPI Outputs (digital or 'analog' PWM) with NINA FW >= 1.3.1
20+
#
21+
# Adafruit ESP32 Breakout
22+
# *, 2, 4, 12, R, 15, 16, 17, 19, 21, 22, 25, 26, 27, 32
23+
# Adafruit ESP32 Feather
24+
# 4, 12, R, 15, 16, 17, 19, 21, 22, 25, 26, 27, 32
25+
# TinyPICO
26+
# 4, 15, 19, 21, 22, 25, 26, 27, 32
27+
# Adafruit ESP32 Airlift Breakout†
28+
# G, R, B
29+
# Adafruit ESP32 Airlift Feather†
30+
# G, R, B
31+
# Adafruit ESP32 Airlift Bitsy Add-On†
32+
# G, R, B
33+
34+
# Avialable† ESP32SPI Digital Inputs with NINA FW >= 1.5.0
35+
#
36+
# Adafruit ESP32 Breakout
37+
# *, 2, 4, 12, R, 15, 16, 17, 19, 21, 22, 25, 26, 27, 32, 34, 35, 36, 39
38+
# Adafruit ESP32 Feather
39+
# 4, 12, R, 15, 16, 17, 19, 21, 22, 25, 26, 27, 32, 34, 36, 39
40+
# TinyPICO
41+
# 4, 15, 19, 21, 22, 25, 26, 27, 32 CH
42+
43+
# Avialable ESP32SPI Analog Inputs (ADC1) with NINA FW >= 1.5.0
44+
#
45+
# Adafruit ESP32 Breakout
46+
# *, 32, 34, 35, HE, HE
47+
# Adafruit ESP32 Feather
48+
# *, 32, 34, BA, HE, HE
49+
# TinyPICO
50+
# 32, BA
51+
52+
Notes:
53+
* Used for bootloading
54+
G Green LED
55+
R Red LED
56+
B Blue LED
57+
BA On-board connection to battery via 50:50 voltage divider
58+
CH Battery charging state (digital pin)
59+
HE Hall Effect sensor
60+
```
61+
62+
Note that on the Airlift FeatherWing and the Airlift Bitsy Add-On, the ESP32 SPI Chip Select (CS) pin aligns with M4's D13 Red LED pin:
63+
```
64+
esp32_cs = DigitalInOut(board.D13) # M4 Red LED
65+
esp32_ready = DigitalInOut(board.D11)
66+
esp32_reset = DigitalInOut(board.D12)
67+
```
68+
So the Red LED on the main Feather processor will almost always appear to be ON or slightly flickering when ESP32SPI is active.
69+
70+
## ESP32 Reset
71+
72+
Because the ESP32 may reset without indication to the CircuitPython code, putting ESP32 GPIO pins into input mode, `esp.set_digital_write(pin, val)` should be preceded by `esp.set_pin_mode(pin, 0x1)`, with appropriate error handling. Other non-default `esp` states (e.g., `esp.set_esp_debug()`) will also get re-initialized to default settings upon ESP32 reset, so CircuitPython code should anticipate this.
73+
74+
## GPIO on Airlift add-on boards
75+
76+
It should also be possible to do ESP32SPI reads and writes on the Airlift add-on boards, but other than the SPI pins and the green, blue, and red LEDs, the only pins available are RX (GPIO3), TX (GPIO1), and GPIO0, so function is extremely limited. Analog input is ruled out since none of those pins are on ADC1.
77+
78+
The Airlift Breakout has level-shifting on RX and GPIO0, so those could be digital inputs only. TX could be used as a digital input or as a digital or analog (PWM) output.
79+
80+
The Airlift FeatherWing and Bitsy Add-On have no level-shifting since they're designed to be stacked onto their associated M4 microcontrollers, so theoretically RX, TX, and GPIO0 could be used as digital inputs, or as digital or analog (PWM) outputs. It's hard to find a use case for doing this when stacked since RX, TX, and GPIO0 will be connected to M4 GPIO pins.
81+
82+
The Airlift [Metro / Arduino] Shield has level-shifting on RX and GPIO0, with stacking issues similar to the wings.
83+
84+
The RX, TX, and GPIO0 pins are used for updating the NINA firmware, and have specific behaviors immediately following reboot that need to be considered if reusing them as GPIO. On the Airlift FeatherWing and Bitsy Add-On, there are pads that need to be soldered to connect the pins. NINA does output messages to TX when connected, depending on the esp debug level set.
85+
86+
Ultimately it makes the most sense by far to use a non-stacked full-pinout ESP32 as co-processor for ESP32SPI pin read and write features.

0 commit comments

Comments
 (0)