Http Request in ESP32 With MicroPython
ESP32 has WIFI connectivity support, in this exercise we will test how to send http request.
Connect to WIFI
There is a file named with boot.py, it is executed on every boot, so we can put WIFI connection related code here
def do_connect():
import network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('<wifi sid>', '<wifi password>')
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
do_connect()
Send http request
Once the WIFI is connected successfully, we can try to send request to RANDOM USER GENERATOR with code below, it will print a random user name every 5 seconds
- Install urequests - Download urequests.py, and save it the board with same file name.
- Code in main.py
import urequests
import json
import time
while True:
response = urequests.get('https://randomuser.me/api/')
# res = json.loads(response.text)
res = response.json()
print("StatusCode: ",response.status_code)
print(" userName: ",res['results'][0]['login']['username'])
time.sleep(5)