Edge Computing in Practice: Developing IoT Devices with MicroPython

(Ahem) Hello, everyone! Today I’m going to share something practical with you, talking about how to use MicroPython on IoT devices, ensuring that even your little broken sensors can come to life! This is not some theoretical course just bragging; we are tightening our belts and getting hands-on right away! (Clank – sound of dropping a thermos)

1. Let’s Chat: What is Edge Computing and MicroPython?

Nowadays, IoT devices are floating to the cloud like dumplings during the New Year, and once there’s a network outage, it’s game over! It’s like needing to go to the bathroom but having to report to the old locust tree at the village entrance, “I need to take a dump” before you can squat—how ridiculous is that?

At this moment, we need to bring out edge computing—allowing devices to understand things on their own, for example:

If a smart door lock suddenly encounters a masked man, it can immediately scream for helpIf a factory machine starts to smoke, it can directly cut the power without hesitationIf a sensor in the field detects a greedy wild boar, it can immediately set off firecrackers to scare it away

MicroPython is like our screwdriver; compared to traditional C language development, it’s like using a rolling pin to poke an ant hole:

Code can be immediately debugged without the hassle of compilation and flashingIt comes with ready-made libraries, making networking and reading sensors as easy as pieIt supports REPL interactive mode, debugging feels like chatting on the kang (a traditional heated bed)

2. Equipment List: Just These Three Items

1.ESP32 Development Board (no need for high-end versions, a 9.9 yuan one from Taobao will do)2.DHT11 Temperature and Humidity Sensor (borrowing one from the sweet potato stall is fine)3.MicroUSB Data Cable (be careful not to use an Android charging cable; 8 out of 10 don’t transmit data)

The wiring is simpler than your nephew playing with building blocks:

Connect the sensor VCC to the development board 3.3VConnect GND to GNDConnect DATA to any GPIO pin (I prefer using Pin 4)

When you plug it into the computer, pay attention—you need to hold down the BOOT button on the board while powering it on to enter download mode! This is like scrubbing in a Northeast bathhouse; you must follow the steps.

3. Step-by-Step: From Lighting an LED to Connecting Everything

Round One: Powering Up the Board

from machine import Pin
import time
led = Pin(2, Pin.OUT)  # Most ESP32 boards have the onboard LED on Pin 2
while True:    led.value(1)       # Light on!    time.sleep(0.5)      led.value(0)       # Light off!    time.sleep(0.5)

After uploading the code, check it out; if the LED is blinking like it’s jumping rope, my friend, you’ve succeeded halfway!

Round Two: Let’s Get Serious—Connecting to the Internet!

import network
import time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
def connect_wifi(ssid, password):    if not wlan.isconnected():        print('Currently chatting with the router...')        wlan.connect(ssid, password)        wait_for_connection = 0        while not wlan.isconnected():            time.sleep(1)            wait_for_connection += 1            if wait_for_connection > 20:                print('Oh no, maybe the WiFi password is wrong!')                return False    print('Connected successfully! IP address:', wlan.ifconfig()[0])    return True
connect_wifi('Wang's WiFi', 'wang12345')  # It is recommended to use your own router

Round Three: Bringing the Sensor to Life!

from machine import Pin
import dht
import time
sensor = dht.DHT11(Pin(4))
while True:    try:        sensor.measure()        temperature = sensor.temperature()        humidity = sensor.humidity()        print(f"Current temperature {temperature}℃, humidity {humidity}%")         if temperature > 30:            print("Oh no, it's getting hot!")    except:        print("This broken sensor is acting up again!")    time.sleep(2)

4. Tips: Wisdom from Relatives

1.

Power-Saving Secrets: Use <span>machine.deepsleep()</span> to let the device sleep, just like a bear hibernating, waking up only at critical moments. Set a timer or use an external interrupt to wake up; it’s better than staying up late!

2.

Cold-Resistance Guide: If working in Northeast temperatures of -30 degrees, pay attention:

Dress the development board in thermal pants (wrap it in insulating cotton)Apply Vaseline to the power section to prevent frostAdd a waterproof cover to the sensor

3.

Emergency Trio:

import micropython
micropython.alloc_emergency_exception_buf(100)  # Emergency buffer
import gc
gc.collect()  # Clean up garbage

4.

Network Reconnection Method:

def reconnect():    if not wlan.isconnected():        print("Oh no, disconnected!")        wlan.disconnect()        wlan.connect(ssid, password)

5. Real-World Application: Boiler Room Monitoring

Last year, I worked on a heating system renovation case for a relative:

Used DS18B20 to measure the temperature of the radiatorWhen the temperature falls below 45℃, send a WeChat alertRegularly store data in InfluxDBStill store data on SD card when offline

Key code snippet:

import onewire
import ds18x20
from machine import Pin
ow = onewire.OneWire(Pin(16))  # Temperature sensor connected to GPIO16
ds = ds18x20.DS18X20(ow)
rom = ds.scan()
while True:    ds.convert_temp()    time.sleep_ms(750)    temp = ds.read_temp(rom[0])    if temp < 45:        send_wechat("Auntie! Your radiator is about to cool down!")

6. Common Pitfalls

1.

Program Running Issues::

Insufficient power—USB cable too long like noodlesMemory leaks—quickly delete used variablesAvoid complex operations in interrupt service

2.

Sensor Readings Jumping::

Connect a 104 capacitor for voltage stabilizationUse shielded cablesImplement a sliding filter algorithm on the software side

3.

OTA Upgrade Failures::

import uos
uos.rename('main_new.py', 'main.py')  # Atomic operation for safety

After all this talking, let me share some heartfelt words: Playing with MicroPython is like eating pork and vermicelli; the more home-style the recipe, the more flavorful it is. Don’t get hung up on fancy frameworks; mastering the basic libraries is enough to set up a smart greenhouse for heating in this area!

(Sound of tools being packed) By the way, if you have any confusion, bring a bottle of Erguotou (a strong liquor) and come find me to chat; there will always be a seat for fellow enthusiasts at my kang!

Leave a Comment