SunFounder ESP32 Starter Kit
Note:
• Open the 6.2_flowing_led.py file located in the esp32-starter-kit-main\micropython\codes path,
or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.
• Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.
from machine import Pin
import neopixel
import time
import random
# Set the number of pixels for the running light
num_pixels = 8
# Set the data pin for the RGB LED strip
data_pin = Pin(14, Pin.OUT)
# Initialize the RGB LED strip object
pixels = neopixel.NeoPixel(data_pin, num_pixels)
# Initialize the avoid sensor
avoid = Pin(25, Pin.IN)
# Initialize the direction variable
direction_forward = True
# Initialize the reverse direction flag
reverse_direction = False
# Continuously loop the running light
while True:
# Read the input from the infrared sensor
avoid_value = avoid.value()
# Generate a random color for the current pixel
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# If no obstacle is detected
if avoid_value:
for i in range(num_pixels):
# Turn on the current pixel with the random color
pixels[i] = color
# Update the RGB LED strip display
pixels.write()
# Turn off the current pixel
pixels[i] = (0, 0, 0)
time.sleep_ms(100)
(continues on next page)
414 Chapter 3. For MicroPython User