该篇用于存储 初学代码。
初学代码
红外对管
两个接口,一个接黑红高电平输出,一个接黑红白接收Pin数据,0/1
from machine import Pin,Signal
IS = 0
while True:
pin = Pin(13,Pin.IN)
sig = Signal(pin,invert = True)
if((sig.value() == 1) & (IS == 0)):
print("signal on!")
IS = 1
if((sig.value() == 0) & (IS == 1)):
print("signal off!")
IS = 0
DHT11
# 导入 dht 内构库
import dht
import machine
# 这里使用 D8 (IO15)接口来收取数据
d = dht.DHT11(machine.Pin(15))
# 测量一次数据
d.measure()
# 读取温度数据,并赋值给 temp 变量
temp = d.temperature()
# 读取湿度数据,并赋值给 humi 变量
humi = d.humidity()
print('temp: {}, humi: {}'.format(temp, humi))
# 输出结果
# temp: 25, humi: 80
接正常IO15,黑红对齐,可读取数据。
执行文件
with open("MQTT.py") as f:
=== exec(f.read(), globals())
OLED
# 导入I2C和Pin类
from machine import I2C, Pin
# 导入frogmaker提供的ssd1306屏幕库
import SSD1306_I2C
# C1接口对应的SCL=IO5, SDA=IO4
i2c = I2C(scl=Pin(5), sda=Pin(4))
# 扫描一下,看下是否能找到连接的OLED屏幕
i2c.scan()
# 输出结果
# [60]
# 导入I2C和Pin类
from machine import I2C, Pin
# 导入frogmaker提供的ssd1306屏幕库
import SSD1306_I2C
# C1接口对应的SCL=IO5, SDA=IO4
i2c = I2C(scl=Pin(5), sda=Pin(4))
# 创建OLED对象,宽度:72,高度:40,使用外部供电
oled = SSD1306_I2C(72, 40, i2c, external_vcc=True)
# 在屏幕(0, 20)坐标上显示文字“Hello World”
oled.text('Hello World', 0, 20)
# 刷新屏幕
oled.show()
剩余空间
import ubinascii
import os
statvfs_fields = ['bsize','frsize','blocks','bfree','bavail','files','ffree',]
dict(zip(statvfs_fields, os.statvfs('/')))
import gc
gc.mem_free()
MQTT 用于 EMQ 测试
from machine import Pin, I2C
import dht
import time
import network
from umqtt import simple as mqtt
import ujson
import uasyncio
import dht
import SSD1306_I2C
def recvMessage(topic,msg):
parsed=ujson.loads(msg)
state = parsed["op"]
if state == 1:
led.value(1)
print("led on!")
if state == 0:
led.value(0)
print("led off!")
async def DHT():
print("DHT init!")
while True:
d.measure()
print("temp:{},humi:{}".format(d.temperature(),d.humidity()))
oled.fill(0)
oled.show()
oled.text('temp:{}'.format(d.temperature()),0,10)
oled.text('humi:{}'.format(d.humidity()),0,20)
oled.show()
send_mseg={"params":{"Temperature":d.temperature(),"Humidity":d.humidity()},"method":"thing.service.property.set"}
client.publish(topic="Temp",msg=str(send_mseg),qos=1,retain=False)
print("Temp published!")
time.sleep(0.5)
async def recvmsg():
print("recv func init!")
while True:
client.wait_msg()
async def main():
print("main function init!")
uasyncio.create_task(DHT())
uasyncio.create_task(recvmsg())
await uasyncio.sleep_ms(10_000)
SERVER = ""
PORT=1883
client = mqtt.MQTTClient(client_id="agrinJPG", server=SERVER, port=PORT, user="agrinJPG", password="", keepalive=60)
led=Pin(2,Pin.OUT,value=0)
d=dht.DHT11(Pin(13))
i2c = I2C(scl=Pin(5), sda=Pin(4))
oled = SSD1306_I2C(72, 40, i2c, external_vcc=True)
client.connect()
client.set_callback(recvMessage)#设置回调函数
client.subscribe("Switch")#订阅主题
uasyncio.run(main()) #多线程