I2C
Examples using both SoftI2C and hardware I2C.
SoftI2C
from machine import Pin, SoftI2C
i2c = SoftI2C(scl=Pin(4), sda=Pin(5), freq=100000)
i2c.scan() # scan for devices
Hardware I2C
from machine import Pin, I2C
i2c = I2C(scl=Pin(4), sda=Pin(5), freq=400000)
devices = i2c.scan()
print("I2C devices found:", [hex(addr) for addr in devices])
SD Card
Examples for standard SPI SD as well as 1-bit and 4-bit MMC modes.
Standard SPI SD
import machine, os, vfs
sd = machine.SDCard(slot=3, sck=36, miso=37, mosi=35, cs=34)
vfs.mount(sd, '/sd') # mount
os.listdir('/sd') # list directory contents
vfs.umount('/sd') # eject
1-bit MMC
import machine, os, vfs
sd = machine.SDCard(slot=1, width=1, sck=36, cmd=35, data=(37,))
vfs.mount(sd, '/sd') # mount
os.listdir('/sd') # list directory contents
vfs.umount('/sd') # eject
4-bit MMC (Gold only)
import machine, os, vfs
sd = machine.SDCard(slot=1, width=4, sck=36, cmd=35, data=(37, 16, 15, 34))
vfs.mount(sd, '/sd') # mount
os.listdir('/sd') # list directory contents
vfs.umount('/sd') # eject
NeoPixel
Control the onboard NeoPixel.
from machine import Pin
from neopixel import NeoPixel
from time import sleep
pin = Pin(39, Pin.OUT)
np = NeoPixel(pin, 1)
np[0] = (255, 255, 255) # white
np.write()
r, g, b = np[0]
sleep(1)
np[0] = (0, 0, 0)
np.write()
LED
Basic digital output control for the LED.
from machine import Pin
from time import sleep
led = Pin(40, Pin.OUT)
led.on()
sleep(1)
led.off()
sleep(1)
led.value(1)
sleep(1)
led.value(0)
Touch
Touch inputs for A, B, and Logo.
from machine import TouchPad, Pin
t = TouchPad(Pin(11)) # A
# t = TouchPad(Pin(12)) # B
# t = TouchPad(Pin(13)) # Logo
t.read()
OLED
Using an SSD1306 OLED display with MicroPython.
• Download: github.com/stechiez/esp32-upython
• Copy
ssd1306.py to your mu_code folder
• In Mu Editor, copy
ssd1306.py to the Springbot
from machine import I2C
from machine import Pin
import ssd1306
i2c = I2C(scl=Pin(4), sda=Pin(5), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
oled.fill(0)
oled.text('SPRINGBOT', 0, 0)
oled.text(' ', 0, 10)
oled.text('OLED using', 0, 20)
oled.text('micropython', 0, 30)
oled.show()
Play ▶ Button
Read the play ▶ button state with pull-up enabled.
from machine import Pin
play = Pin(0, Pin.IN, Pin.PULL_UP)
print(play.value())
Buzzer
Simple PWM example for the buzzer.
from machine import Pin, PWM
from time import sleep
buz = PWM(Pin(33), freq=4000)
sleep(1)
buz.deinit()
Phototransistor / Lux
Read the analog light level.
from machine import ADC, Pin
phototransistor = ADC(Pin(7))
phototransistor.atten(3) # Full range: 0-3.6V
print("Phototransistor Value:", phototransistor.read())
5×5 LED Matrix on Green
Test all LEDs on the 5×5 matrix.
from machine import Pin
import time
# Define GPIO pin numbers
colPins = [Pin(i, Pin.OUT) for i in (3, 2, 14, 15, 16)]
rowPins = [Pin(i, Pin.OUT) for i in (8, 17, 10, 38, 6)]
def clear():
for c in colPins:
c.value(1) # columns are active-low
for r in rowPins:
r.value(0) # rows are active-high
def test_leds(delay=0.1):
clear()
for r in range(5):
for c in range(5):
clear()
colPins[c].value(0) # select column
rowPins[r].value(1) # select row
time.sleep(delay)
clear()
while True:
test_leds()
Wi-Fi and Real Time
Connect to Wi-Fi, synchronize time via NTP, and print the current local time.
import network
import ntptime
import time
SSID = "your_wifi_ssid"
PASSWORD = "your_wifi_password"
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to Wi-Fi...")
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(0.5)
print("Connected. IP:", wlan.ifconfig()[0])
def sync_time():
ntptime.settime()
print("Time synchronized with NTP.")
def print_local_time():
t = time.localtime()
print("Current time: {:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
t[0], t[1], t[2], t[3], t[4], t[5]
))
connect_wifi()
sync_time()
print_local_time()
IMU
KX022-1020 on address 0x1F / 31.
from machine import I2C, Pin
import time
i2c = I2C(0, scl=Pin(4), sda=Pin(5), freq=400_000)
KX022 = 0x1F
# Registers
CNTL1 = 0x18
CNTL2 = 0x19
CNTL3 = 0x1A
TILT_TIMER = 0x22
TILT_ANGLE_LL = 0x32
TILT_ANGLE_HL = 0x33
HYST_SET = 0x34
TSCP = 0x10
INS2 = 0x13
XOUT_L = 0x06 # accel output starts here
def r8(reg):
return i2c.readfrom_mem(KX022, reg, 1)[0]
def w8(reg, v):
i2c.writeto_mem(KX022, reg, bytes([v]))
def s16(lo, hi):
v = (hi << 8) | lo
return v - 65536 if v & 0x8000 else v
# Configure Tilt Position
w8(CNTL1, 0x00) # standby
w8(CNTL1, 0x41) # standby + high-res + +/-2g + TPE enable
w8(CNTL2, 0x3F) # enable +/- x,y,z for tilt
w8(CNTL3, 0x98) # tilt position ODR = 12.5Hz
w8(TILT_TIMER, 0x01) # ~80ms stability
# Permissive thresholds
w8(TILT_ANGLE_LL, 0x04)
w8(TILT_ANGLE_HL, 0x08)
w8(HYST_SET, 0x04)
w8(CNTL1, 0xC1) # operating + TPE
time.sleep_ms(100)
print("CNTL1=", hex(r8(CNTL1)), "CNTL2=", hex(r8(CNTL2)), "CNTL3=", hex(r8(CNTL3)))
print("TILT_TIMER=", hex(r8(TILT_TIMER)), "LL=", hex(r8(TILT_ANGLE_LL)),
"HL=", hex(r8(TILT_ANGLE_HL)), "HYST=", hex(r8(HYST_SET)))
while True:
tscp = r8(TSCP)
ins2 = r8(INS2)
a = i2c.readfrom_mem(KX022, XOUT_L, 6)
x = s16(a[0], a[1])
y = s16(a[2], a[3])
z = s16(a[4], a[5])
print("xyz=%d,%d,%d" % (x, y, z))
time.sleep_ms(200)
Temperature / Humidity
AHT20 / AHT21 on 0x38.
from machine import I2C, Pin
import time
i2c = I2C(0, scl=Pin(4), sda=Pin(5), freq=400_000)
AHT21_ADDR = 0x38
# Trigger measurement
i2c.writeto(AHT21_ADDR, bytes([0xAC, 0x33, 0x00]))
time.sleep_ms(80)
# Read 6 bytes
data = i2c.readfrom(AHT21_ADDR, 6)
raw_hum = ((data[1] << 16) | (data[2] << 8) | data[3]) >> 4
raw_tmp = ((data[3] & 0x0F) << 16) | (data[4] << 8) | data[5]
humidity = (raw_hum * 100) / 1048576
temperature = (raw_tmp * 200) / 1048576 - 50
print("Temp:", temperature, "°C")
print("Hum :", humidity, "%")
NFC
Read the NFC UID from the system address. (Gold only)
from machine import I2C, Pin
i2c = I2C(0, scl=Pin(4), sda=Pin(5), freq=400_000)
SYS = 0x57
UID_ADDR = 0x0018
UID_LEN = 8
uid = i2c.readfrom_mem(SYS, UID_ADDR, UID_LEN, addrsize=16)
print("UID (MSB->LSB, app):", bytes(reversed(uid)).hex().upper())