Exploring TTGO with MicroPython

TTGO is a popular series of development boards that offer a wide range of features and capabilities, including Wi - Fi, Bluetooth, and various sensors. MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimized to run on microcontrollers. Combining TTGO boards with MicroPython provides a powerful and user - friendly platform for developing IoT (Internet of Things) applications, robotics projects, and other embedded systems. In this blog, we will explore the fundamental concepts, usage methods, common practices, and best practices of using TTGO with MicroPython.

Table of Contents#

  1. Fundamental Concepts
  2. Usage Methods
  3. Common Practices
  4. Best Practices
  5. Conclusion
  6. References

1. Fundamental Concepts#

TTGO Boards#

TTGO boards are based on different microcontroller chips, such as the ESP32. They come with built - in components like LCD screens, SD card readers, and sensors like accelerometers or temperature sensors. The ESP32, which is commonly used in TTGO boards, has dual - core processors, Wi - Fi, and Bluetooth capabilities, making it suitable for a wide range of applications.

MicroPython#

MicroPython allows you to write Python code directly on the microcontroller. It provides a high - level programming interface, which means you can use familiar Python syntax and constructs to interact with the hardware. MicroPython has built - in libraries for handling GPIO (General - Purpose Input/Output) pins, communication protocols (e.g., UART, I2C, SPI), and network connectivity.

2. Usage Methods#

Setting up the Environment#

  1. Install Thonny IDE: Thonny is a simple and beginner - friendly Python IDE. You can download it from the official website (https://thonny.org/).
  2. Flash MicroPython onto the TTGO Board:
    • Download the appropriate MicroPython firmware for your TTGO board from the official MicroPython website.
    • Use a tool like esptool.py to flash the firmware onto the board. Here is an example command:
esptool.py --chip esp32 --port /dev/ttyUSB0 erase_flash
esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 460800 write_flash -z 0x1000 esp32 - idf3 - 20210202 - v1.14.bin
  1. Connect to the Board in Thonny:
    • Open Thonny and go to Tools > Options > Interpreter. Select MicroPython (ESP32) and the appropriate serial port for your TTGO board.

Blinking an LED#

import machine
import time
 
# Define the pin connected to the LED
led = machine.Pin(2, machine.Pin.OUT)
 
while True:
    led.on()
    time.sleep(1)
    led.off()
    time.sleep(1)
 

In this code, we first import the machine module, which provides low - level hardware access, and the time module for adding delays. We then define a Pin object for the LED pin and set it as an output pin. In the infinite loop, we turn the LED on, wait for 1 second, turn it off, and wait for another second.

Connecting to Wi - Fi#

import network
import time
 
# Set up Wi - Fi credentials
ssid = 'Your_WiFi_SSID'
password = 'Your_WiFi_Password'
 
# Create a Wi - Fi station interface
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
 
# Wait for the connection
while not wlan.isconnected():
    time.sleep(1)
    print('Connecting...')
 
print('Connected! Network config:', wlan.ifconfig())
 

This code creates a Wi - Fi station interface, activates it, and attempts to connect to the specified Wi - Fi network. It waits until the connection is established and then prints the network configuration.

3. Common Practices#

Reading Sensor Data#

Most TTGO boards come with sensors. For example, to read data from a temperature sensor using the I2C protocol:

import machine
import ubinascii
 
# Initialize I2C
i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21))
 
# Scan for I2C devices
devices = i2c.scan()
if len(devices) == 0:
    print("No I2C devices found")
else:
    print('I2C devices found:', len(devices))
    for device in devices:
        print("Decimal address: ", device, " | Hex address: ", ubinascii.hexlify(bytearray([device])))
 

This code initializes the I2C interface and scans for connected I2C devices. It then prints the addresses of the detected devices.

Storing Data on an SD Card#

import os
import machine
import sdcard
 
# Initialize SD card
sd = sdcard.SDCard(machine.SPI(2), machine.Pin(5))
os.mount(sd, "/sd")
 
# Write data to a file on the SD card
with open("/sd/test.txt", "w") as f:
    f.write("Hello, SD card!")
 
# Read data from the file
with open("/sd/test.txt", "r") as f:
    data = f.read()
    print(data)
 
# Unmount the SD card
os.umount("/sd")
 

This code initializes the SD card using the SPI interface, mounts it, writes a text file to the SD card, reads the file, and then unmounts the SD card.

4. Best Practices#

Error Handling#

When working with hardware and network connections, errors can occur. It's important to use try - except blocks to handle exceptions gracefully. For example, when connecting to Wi - Fi:

import network
import time
 
ssid = 'Your_WiFi_SSID'
password = 'Your_WiFi_Password'
 
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
 
try:
    wlan.connect(ssid, password)
    for i in range(10):
        if wlan.isconnected():
            print('Connected! Network config:', wlan.ifconfig())
            break
        time.sleep(1)
    else:
        print('Failed to connect to Wi - Fi')
except Exception as e:
    print('Error:', e)
 

This code attempts to connect to Wi - Fi and waits for up to 10 seconds. If the connection fails, it prints an error message. It also catches any exceptions that may occur during the connection process.

Code Optimization#

MicroPython has limited resources, so it's important to optimize your code. Avoid using large data structures or complex algorithms. Use local variables instead of global variables whenever possible, as global variables consume more memory.

5. Conclusion#

TTGO boards combined with MicroPython offer a powerful and accessible platform for developing embedded systems. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can efficiently develop a wide range of applications, from simple LED blinkers to complex IoT devices. With the ease of Python programming and the rich features of TTGO boards, the possibilities are endless.

6. References#