import machine
import time
import network
import ssd1306
# Configuration
CONNECTION_TIMEOUT = 15 # Time to wait for Wi-Fi connection in seconds
BLE_LED = machine.Pin(21, machine.Pin.OUT)
i2c_1 = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(23))
i2c_2 = machine.I2C(0, scl=machine.Pin(34), sda=machine.Pin(35))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_1)
oled_2 = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_2)
# OLED display main function
def msg_oled(msg):
oled.fill(0) # Clears the display (if fill(1), fullfills the display)
if len(msg) >= 15:
msg_list = msg.split(' ') # if number of characters in message > 15, splits
else: # at existing spaces and returns a list
msg_list = [msg] # else returns the list single element
for i, message in enumerate(msg_list):
oled.text(message, 0, i*10) # writes message with 10 pixel space between rows.
oled.show() # (0,0)=top-left corner of display
# Print a test message
def print_test_message():
start_message = "ESP32 MicroPython Test"
print(start_message)
msg_oled(start_message) # Display message in OLED
time.sleep(2)
def chronometer(start_time):
current_time = time.time()
elapsed_time = int(current_time - start_time) # Get the elapsed time in seconds
return elapsed_time
# Wi-Fi connection function with timeout
def connect_wifi(ssid, password, timeout):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
aps = wlan.scan() # scan for available networks in range
print("APS:", aps)
wlan.connect(ssid, password)
msg_oled("Connecting to WIFI")
print("Connecting to Wi-Fi...")
start_time = time.time()
while not wlan.isconnected():
elapsed_time = chronometer(start_time)
msg_oled(f"Connecting: {elapsed_time}s")
if elapsed_time > timeout:
print("Failed to connect to Wi-Fi within the timeout period.")
msg_oled('Connection Failed')
return False
msg_oled('Connection Successfull')
print("Connected to Wi-Fi")
print("IP Address:", wlan.ifconfig()[0])
return True
# Example usage
print_test_message()
# Attempt to connect to Wi-Fi
if connect_wifi('Wokwi-GUEST', '', CONNECTION_TIMEOUT):
# Start blinking the LED if Wi-Fi is connected successfully
BLE_LED.on()
else:
# If Wi-Fi connection fails, turn off the LED
BLE_LED.off()