MicroPython:Socket应用
搞得这个MicroPython啊,亦可赛艇。
经过上一篇文章,已经配置好了WiFi连接和Webrepl,下面我们来尝试与ESP8266来通信,在GPIO2上我接入了一个DS18x20温度传感器,通过访问ESP8266的8267端口,来获得ESP8266上传感器的数值。
main.py:
(在ESP8266上的socket库叫usocket,json库叫ujson)
from ds18020 import DS18020
import usocket
import ujson
import esp
host = '0.0.0.0'
port = 8267
ds = DS18020(2)
ds_addr = ds.getaddr()
s = usocket.socket()
s.bind((host,port))
s.listen(6)
while True:
client,addr = s.accept()
print('Client IP:',addr[0])
info = {}
info['flash_size'] = str(esp.flash_size())
info['flash_free'] = str(esp.freemem())
info['flash_id'] = str(esp.flash_id())
info['ds18x20_temp'] = str(ds.gettemp(ds_addr[0]))
print(info)
client.send(ujson.dumps(info))
info = {}
client.close()
ds18020.py
(很惭愧,只做了一点的微小工作)
import onewire
import ds18x20
import time
from machine import Pin
class DS18020:
def __init__(self,pin):
self.pin = Pin(pin)
def getaddr(self):
ow = onewire.OneWire(self.pin)
self.ds = ds18x20.DS18X20(ow)
roms = self.ds.scan()
return roms
def gettemp(self,addr):
self.ds.convert_temp()
time.sleep_ms(450)
return self.ds.read_temp(addr)
效果:
今天还是挺冷的。