Welcome to the Wokwi ESP32 MicroPython Wi-Fi Connection Guide!
We'll write a simple MicroPython script to connect to a simulated Wi-Fi network named 'Wokwi-GUEST'.
Here's a breakdown of the code Connecting from MicroPython:
network
for networking functionality, and time
for pausing the script.Type the following MicroPython code directly into the Wokwi editor:
import network
import time
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
Once connected to Wi-Fi, you can access web pages and retrieve data.
Here is a simple example using the `urequests` library to send an HTTP GET request to a webpage:
import requests
# URL of the CSV file
url = "https://data.moenv.gov.tw/api/v2/aqx_p_432?\
api_key=e8dd42e6-9b8b-43f8-991e-b3dee723a52d&format=CSV"
# Send an HTTP GET request to the URL
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Get the content of the response
response_text = response.text
# Print the content of the CSV data
print(response_text)
else:
print(f"Failed to download CSV data. Status code: {response.status_code}")
res = response_text.split("\n")
cols = res[2].split(',')
print(f"cols {cols}")
#print(cols.index('aqi'))
#get hualien data_type
for info in res:
if '花蓮' in info:
#print(info)
print(info.split(',')[cols.index('aqi')])
urequests
and umqtt
.Now you've learned the basics of setting up a Wi-Fi connection on an ESP32 using MicroPython in Wokwi, and how to access web page data. Keep experimenting and happy coding!
RTC
module in MicroPython is used for real-time clock functionality.datetime
method can be used both to set and get the date and time.datetime
method returns an 8-tuple when called without arguments.subseconds
is hardware-dependent.datetime
.from machine import RTC
# Create an RTC object
rtc = RTC()
# Set the date and time
rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0))
# Retrieve the current date and time
current_datetime = rtc.datetime()
print(f"current_datetime : {current_datetime}")
time
module provides functions to work with time.localtime([secs])
converts time in seconds since the Epoch to an 8-tuple.secs
is not provided, the current time is used.gmtime()
returns UTC time, while localtime()
returns local time.year
includes the century (e.g., 2014).month
is 1-12mday
is 1-31.hour
is 0-23; minute
and second
are 0-59.weekday
is 0-6 for Monday to Sundayyearday
is 1-366.import time
# Get the current time in seconds since the Epoch (Unix time)
current_time_seconds = time.time()
# Convert seconds since Epoch to a time tuple in local time
local_time_tuple = time.localtime(current_time_seconds)
# Format the time tuple into a human-readable date and time string
# The format is Year-Month-Day Hour:Minute:Second
formatted_time = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
local_time_tuple[0], # Year
local_time_tuple[1], # Month
local_time_tuple[2], # Day
local_time_tuple[3], # Hour
local_time_tuple[4], # Minute
local_time_tuple[5] # Second
)
print("Current Local Time:", formatted_time)
ntptime
module is used to synchronize the RTC with an NTP server.ntptime.settime()
to update the RTC.import network, time, import ntptime
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
ntptime.host = 'tock.stdtime.gov.tw'
ntptime.timeout = 10
ntptime.settime()
# Convert seconds since Epoch to a time tuple in local time
local_time_tuple = time.localtime()
# Format the time tuple into a human-readable date and time string
# The format is Year-Month-Day Hour:Minute:Second
formatted_time = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
local_time_tuple[0], # Year
local_time_tuple[1], # Month
local_time_tuple[2], # Day
local_time_tuple[3], # Hour
local_time_tuple[4], # Minute
local_time_tuple[5] # Second
)
print("Current Local Time:", formatted_time)
import network, time
ap = network.WLAN(network.AP_IF) # Initializes the access point interface
ap.active(False) # Deactivates the first AP interface
time.sleep(0.1) # Waits for 0.1 seconds to ensure the interface is properly deactivated
ap.active(True) # Reactivates the first AP interface
ap.config(ssid='MyESP32AP') # Sets the SSID and password of the AP
print('AP IP:', ap.ifconfig()[0]) # Displays the IP address of the ESP32 in AP mode
Access the internet
interact with web services
communicate with other network devices.
Enables ESP32 to become part of a larger network, such as home automation.
import network, time
wlan = network.WLAN(network.STA_IF) # Initializes the station interface
wlan.active(True) # Activates the WLAN interface
ssid = 'CSIE_C306'
passwd = '@ndhuc306'
connected = wlan.isconnected() # Check if the connection was successful
if not connected: # if it is not connected
print(f'Trying to connect to {ssid}') # Display a message indicating an attempt to connect
wlan.connect(ssid, passwd) # Attempt to connect to the Wi-Fi network again
for _ in range(100): # Try to connect 100 times, waiting 0.1 seconds each time
connected = wlan.isconnected() # Check if the connection was successful
if connected:
break # Break out of the loop if connected
time.sleep(0.1) # Wait for 0.1 seconds before checking again
print('.', end='') # Print progress dots to indicate ongoing connection attempts
if connected: # If connected successfully
# Display successful connection and network configuration
print(f'\nConnected to ssid {ssid}. Network config: {wlan.ifconfig()}')
else: # If the connection failed
print(f'\nFailed. Not Connected to: {ssid}') # Display a failure message
import urequests
# URL of the CSV file
url = "https://data.moenv.gov.tw/api/v2/aqx_p_432?\
api_key=e8dd42e6-9b8b-43f8-991e-b3dee723a52d&limit=1000&sort=ImportDate%20desc&format=CSV"
# Send an HTTP GET request to the URL
response = urequests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Get the content of the response
response_text = response.text
# Print the content of the CSV data
print(response_text)
else:
print(f"Failed to download CSV data. Status code: {response.status_code}")
res = response_text.split("\n")
cols = res[2].split(',')
print(f"cols {cols}")
#print(cols.index('aqi'))
#get hualien data_type
for info in res:
if '花蓮' in info:
#print(info)
aqi = info.split(',')[cols.index('aqi')]
print(f"花蓮 AQI : {aqi}")
花蓮
AQI : 19