首先让esp8266连接网络
写在boot就可以了
# # This file is executed on every boot (including wake-boot from deepsleep)
# #import esp
# #esp.osdebug(None)
# import uos, machine
# #uos.dupterm(None, 1) # disable REPL on UART(0)
# import gc
# #import webrepl
# #webrepl.start()
# gc.collect()
import network,time
sta = network.WLAN(network.STA_IF)
sta.active(True)
if not sta.isconnected():
print("网络连接......")
sta.connect('gl123', '17720556214')
print("加入gl123")
time.sleep(2)
while not sta.isconnected():
pass
print(sta.ifconfig())
print("wifi成功接入网络")
print(sta.status())
print("================")
然后建立main.py
# 导入网络模块
import network
# 导入httpclient
import urequests
# 导入ure库
import ure
import ujson
import time
#别人的key'https://api.seniverse.com/v3/weather/now.json?key=SBBRd0X8fidhmnBv2&location=guangzhou&language=zh-Hans&unit=c'
# 请求武汉天气情况
resp = urequests.get('https://api.seniverse.com/v3/weather/now.json?key=SBBRd0X8fidhmnBv2&location=jiangxia&language=zh-Hans&unit=c')
# # 打印请求结果
print(type(resp.text),resp.text)
# json字符串转为python列表类型
json_str1 = ujson.loads(resp.text)
print(json_str1['results'][0]['location']['name'])
print(json_str1['results'][0]['now']['text'])
print(json_str1['results'][0]['now']['temperature'])
print(json_str1['results'][0]['last_update'])
这里直接在知心天气建立一个免费项目就可以了,免费用户只返回天气现象文字、代码和气温 3 项数据。API秘钥就是代码里的key,某些版本的esp8266的固件编译报错找不到urequests模块,则需要自己去Thonny下载。
这是返回结果说明
{
"results": [
{
"location": {
"id": "C23NB62W20TF",
"name": "西雅图",
"country": "US",
"path": "西雅图,华盛顿州,美国",
"timezone": "America/Los_Angeles",
"timezone_offset": "-07:00"
},
"now": {
"text": "多云", //天气现象文字
"code": "4", //天气现象代码
"temperature": "14", //温度,单位为c摄氏度或f华氏度
"feels_like": "14", //体感温度,单位为c摄氏度或f华氏度
"pressure": "1018", //气压,单位为mb百帕或in英寸
"humidity": "76", //相对湿度,0~100,单位为百分比
"visibility": "16.09", //能见度,单位为km公里或mi英里
"wind_direction": "西北", //风向文字
"wind_direction_degree": "340", //风向角度,范围0~360,0为正北,90为正东,180为正南,270为正西
"wind_speed": "8.05", //风速,单位为km/h公里每小时或mph英里每小时
"wind_scale": "2", //风力等级,请参考:http://baike.baidu.com/view/465076.htm
"clouds": "90", //云量,单位%,范围0~100,天空被云覆盖的百分比 #目前不支持中国城市#
"dew_point": "-12" //露点温度,请参考:http://baike.baidu.com/view/118348.htm #目前不支持中国城市#
},
"last_update": "2015-09-25T22:45:00-07:00" //数据更新时间(该城市的本地时间)
}
]
}