拿到手第一件事就是想玩玩板载蓝牙,可惜搞了半天都没有找到参考资料,有也是乱糟糟的感觉,碰巧把WIFI给搞出来了。
前提
- 注册天气接口账号:
https://www.tianqiapi.com/
CODE
- 注意WIFI和接口信息换成自己的就行
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
#import webrepl
#webrepl.start()
import socket
import network
from machine import Pin, I2C
import time
led1=Pin(12,Pin.OUT)
led2=Pin(13,Pin.OUT)
def led_random():
led1.on()
time.sleep(0.1)
led1.off()
led2.on()
time.sleep(0.1)
led2.off()
def http_get(url):
_, _, host, path = url.split('/', 3)
addr = socket.getaddrinfo(host, 80)[0][-1]
s = socket.socket()
s.connect(addr)
s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
while True:
data = s.recv(200)
if data:
print(data.decode('utf-8'), end='')
else:
led_random()
break
s.close()
led1.on()
led2.on()
def do_connect():
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect('WifiName', 'WifiPassword')
while not sta_if.isconnected():
led_random()
pass
print('network config:', sta_if.ifconfig())
# 注意替换成自己的接口信息
http_get("http://www.tianqiapi.com/api?version=v9&appid=YourAppId&appsecret=YourSecret&city=%E5%8C%97%E4%BA%AC")
try:
do_connect()
except Exception as e:
print(e)