【Digi-Key Follow me Issue 2】Task 2: Wi-Fi Networking
[Copy link]
Wi-Fi
In fact, CircuitPython networking is very simple, just add relevant configuration in the setting.toml configuration.
# 配置wifi的ID名称
CIRCUITPY_WIFI_SSID = "你家的wifiid"
# 配置wifi密码,把你的wifi密码填到里面
CIRCUITPY_WIFI_PASSWORD = "你家的wifi密码"
# 配置网页工作流密码,这个千万不要改,除非你懂了
CIRCUITPY_WEB_API_PASSWORD = "ilfree"
# 配置网页工作流端口
CIRCUITPY_WEB_API_PORT = 80
# 到上一行就可以了,这一行无所谓,反正是注释
Yes, you can connect to the Internet by simply configuring this file. You can also use the network workflow to edit and debug the code. For detailed tutorials, please refer to the tutorial link below.
After configuration and restart, you can see that the IP address is normally displayed on the board, as shown in the figure below.
In this state, you can connect to the network without explicitly calling the wifi.connect function.
import os
import time
import ssl
import wifi
import socketpool
import microcontroller
import adafruit_requests
# adafruit quotes URL
quotes_url = "https://www.bing.com"
# connect to SSID
#wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))
pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
while True:
try:
# pings adafruit quotes
print("Fetching text from %s" % quotes_url)
# gets the quote from adafruit quotes
response = requests.get(quotes_url)
print("-" * 40)
# prints the response to the REPL
print("Text Response: ", response.text)
print("-" * 40)
response.close()
# delays for 1 minute
time.sleep(60)
# pylint: disable=broad-except
except Exception as e:
print("Error:\n", str(e))
print("Resetting microcontroller in 10 seconds")
time.sleep(10)
microcontroller.reset()
As you can see, the wifi connection part has been commented out in the above code, but it can still run and get resources from bing.com. The result is as shown in the figure below.
Create a WiFi hotspot
The following code can be used to easily create a hotspot named cpy_wifi with a password of temppasswd. After connecting, the IP address can be obtained, but the Internet cannot be connected.
import os
import time
import ssl
import wifi
import socketpool
import microcontroller
import adafruit_requests
wifi.radio.start_ap("cpy_wifi", "temppasswd")
print(f"SSID: cpy_wifi")
print(f"PASSWORD: temppasswd")
while True:
pass
|