案例为了解决晚上起床找不到灯的问题。当你从床上起来时,雷达感应传感器检测到你的活动后自动打开电灯。省去了寻找电灯开关的麻烦。
本案例需要的硬件
器材 | 数量 |
---|---|
HaaS506 - M601/M320 | 1 |
5.8G雷达感应传感器模块 | 1 |
220v电灯泡 | 1 |
高电平触发继电器 | 1 |
杜邦线 | 若干 |
PIN | 功能 | 备注 |
---|---|---|
VCC | 供电 | 2.7-4.8V |
GND | 接地 | - |
OUT | 信号输出 | 输出高低电平(0/2.2V) |
P2 | GPIO2 | 接收增益档位选择(悬空/拉低选择) |
P3 | GPIO3 | 延时时间档为选择(悬空/拉低) |
main.py
from driver import GPIO
import utime as time
from bodyDetect import BD
import _thread#初始化时间
begin_time = 0
now_time = time.time()
value1 = 0# 初始化人体传感器
radar=GPIO()
radar.open('radar')
def bd_thread():global valuewhile True:bd = BD(radar)value = bd.irDetect()time.sleep_ms(1)def detection():global value,now_time,begin_timenow_time = time.time()if value == 1:begin_time = time.time()if p18.read() !=1:p18.write(1)if value == 0:if (now_time - begin_time >10):if p18.read() != 0:p18.write(0)if __name__ == '__main__':p18=GPIO()p18.open('p18')p18.write(0)_thread.start_new_thread(bd_thread, ())while True:time.sleep_ms(1)detection() #控制开关等#传感器状态改变是打印logif value1 != value:print('change:',value)value1 = value
bodyDetect.py
from driver import GPIOclass BD(object):def __init__(self, gpioObj):self.gpioObj = Noneif not isinstance(gpioObj, GPIO):raise ValueError("parameter is not a GPIO object")self.gpioObj = gpioObjdef irDetect(self):if self.gpioObj is None:raise ValueError("invalid GPIO object")value = self.gpioObj.read()return value
board.json
{"name": "haas506","version": "2.0.0","io": {"p18": {"type": "GPIO","port": 18,"dir": "output","pull": "pullup"},"radar":{"type":"GPIO","port": 3,"dir": "input","pull":"pullup"} },"debugLevel": "ERROR","repl": "enable","replPort": 0
}
每次人体运动状态改变时会打印一次change,有人体活动为1,没有活动物体时为0。持续10s没有检测到人体活动,电灯自动关闭。
[17:21:36.804]收←◆\0
[17:21:38.808]收←◆POWERONREASON:0x0003,parse:,powerkey,pinReset.[17:21:40.646]收←◆change: 1[17:21:42.686]收←◆change: 0[17:21:43.987]收←◆change: 1[17:21:46.026]收←◆change: 0[17:21:50.706]收←◆change: 1[17:21:52.746]收←◆change: 0[17:21:54.767]收←◆change: 1