树莓派自动饮水机编程示例

一、准备物品

1. 树莓派ZeroWH(针脚焊接) (100元)

在这里插入图片描述在这里插入图片描述

2. DC电池盒(2节装)(1元)

在这里插入图片描述

3. 18650锂电池2节(10元)

在这里插入图片描述

4. 小水泵(3元)

在这里插入图片描述

5. 继电器(3元)

在这里插入图片描述

6. 红外避障传感器(2元)

在这里插入图片描述

7. 多路DC-DC电压转换模块电源 12V转3.3/5/12V(2元)

在这里插入图片描述

8. 杜邦线若干(10元)

在这里插入图片描述

9. 斐讯N1小LINUX服务器(100元) 在这里插入图片描述

二、总体设计

在这里插入图片描述

三、硬件接线

树莓派ZeroWH红外避障传感器继电器多路DC-DC电压转换模块电源
BCM18VIN
BCM23OUT
GNDGND
红外避障传感器多路DC-DC电压转换模块电源
V3.3V3.3
GNDGND
继电器多路DC-DC电压转换模块电源
V3.3V3.3
GNDGND
继电器水泵多路DC-DC电压转换模块电源
COM5V
NO5V
GNDGND

四、程序代码

4.1 服务器代码

CREATE TABLE IF NOT EXISTS `warter_log` (
`id` int(11) NOT NULL,
  `warter_time` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
const Koa    = require("koa");
const serve  = require("koa-static");
const router = require("koa-router")();

const app = new Koa();

var knex = require('knex')({
  client: 'mysql',
  connection: {
    host : 'xxx',
    port :  3360,
    user : 'root',
    password : 'xxx',
    database : 'cjy'
  },
  debug: true,
  pool: {
    min: 0,
    max: 3,
  },
  acquireConnectionTimeout: 10000,
});

app.use(serve(__dirname + "/webroot"));

router.get('/t', async (ctx, next) => {
    ctx.response.body = "hello world!";
})

//添加取水记录
router.get('/warter_count', async (ctx, next) => {
    try{
        itemList = await knex('warter_log').insert({})
        ctx.response.body = itemList;
    }catch(e){
        console.log(e);
    }
})

//获取取水时间记录列表
router.get('/warter_logs', async (ctx, next) => {
    try{
        let itemList = await knex.select('*').from('warter_log').orderBy([
            { column: 'id', order: 'desc' }
            ]);
        ctx.response.body = itemList;
    }catch(e){
        console.log(e);
    }
})

app.use(router.routes());
app.listen(6060);

4.2 树莓派ZeroWH代码

#!/usr/bin/python3
# encoding:utf-8
import RPi.GPIO as GPIO
import asyncio
import aiohttp

class cjy_automatic_water_dispenser:
    def __init__(self, loop=None):
        self._queue  = asyncio.Queue(loop=loop)
        self._future = asyncio.Future(loop=loop)
 
    #提交自动饮水时间记录
    async def upload_action(self):
        print("upload_action start")
        upload_url = 'http://cwn1.f3322.net:6060/warter_count'
        
        while True:
            try:
                r = await  asyncio.wait_for(self._queue.get(), timeout=1.0)
                async with aiohttp.ClientSession() as session:
                    async with session.get('http://python.org') as response:
                        print("Status:", response.status)
                        print("Content-type:", response.headers['content-type'])
                        html = await response.text()
                        print("Body:", html[:15], "...")
                # r = await self._queue.get()
                print('consumer value>>>>>>>>>>>>>>>>>>', r)
            except asyncio.TimeoutError as e1:
                print('get value timeout')
                continue
            except Exception as e2:
                print(e2)
                break
        print('quit')
    
    #自动饮水服务
    async def main(self):
        print("main start")

        #放水计数
        v = 0
        
        #接水位置最后一次水杯状态:1--存在水杯,0--不存在水杯
        zb_state = 0

        #树莓派ZeroWH采用BCM模式定义引脚
        GPIO.setmode(GPIO.BCM)

        #红外传感器检测是否有水杯的数字引脚
        pin_avoid_obstacle=23

        #连接水泵的继电器控制引脚
        pin_reply = 18
    
        #设置红外传感器连接引脚为上拉电阻,数字信号输入模式
        GPIO.setup(pin_avoid_obstacle, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

        #设置水泵继电器连接引脚,数字信号输出模式
        GPIO.setup(pin_reply, GPIO.OUT)

        #每隔0.5秒检测一次红外探头检测范围内是否放置了物体
        while True:
            status = GPIO.input(pin_avoid_obstacle)
            if status == 1:
                print('红外避障模组【没有检测到】障碍物纸杯')
                zb_state = 0
                #设置水泵处于关闭状态
                GPIO.output(pin_reply, GPIO.HIGH)
            else:
                print('红外避障模组【检测到】障碍物纸杯')
                if zb_state == 0:
                    zb_state = 1
                    print("自动出水【开始】")
                    #打开水泵,控制引脚低电平时打开
                    GPIO.output(pin_reply, GPIO.LOW)
                    #水泵放水0.5秒 
                    await asyncio.sleep(0.5)
                    #关闭水泵,控制引脚高电平时关闭
                    GPIO.output(pin_reply, GPIO.HIGH)
                    print("自动出水【结束】")
               
                    print('add value to queue:',str(v))
                    await self._queue.put(v)
                    v = v + 1
                else:
                    pass

            #休眠0.5秒
            await asyncio.sleep(0.5)

    async def run(self):
        asyncio.ensure_future(self.main())
        asyncio.ensure_future(self.upload_action())
 
if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    cawd = cjy_automatic_water_dispenser(loop=loop)

    #将自动饮水服务加入协程
    asyncio.ensure_future(cawd.run())

    #进入事件循环
    try:
        loop.run_forever()
    except KeyboardInterrupt as e:
        print(asyncio.Task.all_tasks())
        for task in asyncio.Task.all_tasks():
            print(task.cancel())
        loop.stop()
        loop.run_forever()
    finally:
        loop.close()
        #清除树莓派所有引脚状态
        GPIO.cleanup()

五、成果展示

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

六、关键技术小代码

6.1 协程入门(python3.7+)

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())

6.2 生产者消费者模型(python3.7+)

import asyncio

class Test(object):
    def __init__(self, loop=None):
        self._queue = asyncio.Queue(loop=loop)
        self._future = asyncio.Future(loop=loop)
 
    async def _producer(self, interval):
        v = 0
        while True:
            await asyncio.sleep(interval)
            print('add value to queue:',str(v))
            await self._queue.put(v)
            v = v + 1
 
    async def _consumer(self):
        while True:
            try:
                r =await  asyncio.wait_for(self._queue.get(), timeout=1.0)
                # r = await self._queue.get()
                print('consumer value>>>>>>>>>>>>>>>>>>', r)
            except asyncio.TimeoutError:
                print('get value timeout')
                continue
            except:
                break
        print('quit')
 
    async def run(self):
        asyncio.ensure_future(self._producer(2))
        asyncio.ensure_future(self._consumer())
 
if __name__ == '__main__': 
	loop = asyncio.get_event_loop()
	t = Test(loop=loop)
	asyncio.ensure_future(t.run())
	try:
    	loop.run_forever()
	except KeyboardInterrupt as e:
    	print(asyncio.Task.all_tasks())
    	for task in asyncio.Task.all_tasks():
        	print(task.cancel())
	    loop.stop()
    	loop.run_forever()
	finally:
    	loop.close()

6.3 水泵继电器代码(python3+)

import RPi.GPIO as GPIO
import time

if __name__ == '__main__': 
	GPIO.setmode(GPIO.BCM)

	pin_reply = 23
	GPIO.setup(pin_reply, GPIO.OUT)
	
	#水泵放水3秒
	GPIO.output(pin_reply, GPIO.HIGH)
	time.sleep(3)
	GPIO.output(pin_reply, GPIO.LOW)

	GPIO.cleanup()

6.4 红外障碍检测代码(python3+)

import RPi.GPIO as GPIO
import time

if __name__ == '__main__': 
	pin_avoid_obstacle=18
	GPIO.setmode(GPIO.BCM)
	GPIO.setup(pin_avoid_obstacle, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
	try:
    	while True:
        	status = GPIO.input(pin_avoid_obstacle)
        	if status == 1:
            	print('我是红外避障模组,没有检测到障碍物,一切正常!')
	        else:
    	        print('我是红外避障模组,检测到障碍物,注意停车')
    	    time.sleep(0.5)
	except KeyboradInterrupt:
    	GPIO.cleanup()

6.5 HTTP客户端请求

import aiohttp
import asyncio

async def main():

    async with aiohttp.ClientSession() as session:
        async with session.get('http://python.org') as response:

            print("Status:", response.status)
            print("Content-type:", response.headers['content-type'])

            html = await response.text()
            print("Body:", html[:15], "...")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值