【Digi-Key Follow me Issue 3】Task 4: Connect to WiFi network
[Copy link]
Connecting to WiFi is one of the strengths of the ESP series. MicroPython directly provides a simple connection library: network
First, simply make sure you can connect to the Internet, get the IP assigned by the router, and display the signal strength. The SSID and password are stored in a separate file for easy modification.
import network
import time
from settings import SSID, PASSWORD
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
max_wait_sec = 15
for wait_sec in range(max_wait_sec):
if wlan.isconnected():
break
print('Waiting for connection...')
time.sleep(1)
if not wlan.isconnected():
raise RuntimeError('Could not connect to network')
print('Connected')
status = wlan.ifconfig()
rssi = wlan.status('rssi')
print(f'ip: {status[0]}')
print(f'rssi: {rssi}')
I didn't capture the first Internet connection picture, but after the reset, the Internet connection speed was very fast.
Directly use the built-in requests library of MicroPython to initiate the request. Use the display-related code of the previous task to display the result on the screen. First display the request, and then display the content after getting the response.
Since the entire webpage is very long, only the first 1500 bytes are read here, and then the webpage title is extracted and displayed. However, since there is no Chinese character library, the Chinese characters have to be removed and only English characters are displayed.
import requests
url = 'https://www.digikey.cn/'
oled.text(f'HTTP/1.0 GET', 0, 0)
oled.text(f'{url}', 0, 10)
oled.show()
resp = requests.get(url)
status_code = resp.status_code
content = resp.raw.read(1500)
text = content.decode('utf-8')
start = text.find('<title>')
end = text.find('</title>')
title = text[start + 7:end].strip()
print(title)
en_title = ''.join([char for char in title if char <= '\u4e00'])
print(en_title)
resp.close()
oled.text(str(status_code), 0, 30)
oled.text(en_title, 0, 40)
oled.show()
Actual effect: (To demonstrate the effect, clear the display and wait for a few seconds)
You can see that the request still took some time.
In the REPL window, you can see the full title of the web page obtained and the text that can be displayed.
|