因家里装修,自制了一个甲醛测试仪,在此记录下主要过程。
1.材料:
- 1.树莓派Zero W
- 2.ZE08-CH2O传感器(UART接口)
- 3.ssd1306 128*64 I2C接口
其中,CH2O传感器是核心部件,主要用来采集甲醛含量。树莓派用来读取传感器上的数据,ssd1306用来显示数据。
最终效果如下图:
2.接线方式
一、 树莓派Zero W引脚:
二、 ZE08引脚
ze08接树莓派:
ZE08 | RpiGPIO |
---|---|
Pin4(5V) | Pin2(5V) |
Pin3(GND) | Pin6(GND) |
Pin6(UART-TxD) | Pin10(UART-RxD) |
三、 ssd1306 引脚
ssd1306接树莓派(IIC协议):
OLED | RpiGPIO |
---|---|
VCC | Pin1(3.3V) |
SDA | Pin3(SDA) |
SCL | Pin5(SCL) |
GND | Pin9(GND) |
3.代码
代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65import serial
import time
from time import sleep
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import subprocess
ser=serial.Serial("/dev/serial0",9600)
#init display
disp = Adafruit_SSD1306.SSD1306_128_64(rst=None)
disp.begin()
disp.clear()
disp.display()
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
draw.rectangle((0,0,width,height), outline=0, fill=0)
padding = 2
top = padding
bottom = height-padding
x = 0
font = ImageFont.load_default()
font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf",15)
cmd = "hostname -I | cut -d\' \' -f1"
IP = subprocess.check_output(cmd, shell = True )
def save(data):
today = time.strftime("%Y-%m-%d", time.localtime())
f = open(today,'a')
f.write(data)
f.write("\n")
f.close()
while True :
r_data = ser.read()
sleep(0.3)
data_left = ser.inWaiting()
r_data += ser.read(data_left)
if 9 != len(r_data):
print 'error length: %d'%len(r_data)
continue
else:
n=ord(r_data[4])*256+ord(r_data[5])
ppm = str(n/1000.0)
#print("CH2O:"+ppm) # ppm = n/1000.0
save(ppm)
draw.rectangle((0,0,width,height), outline=0, fill=0)
draw.text((x, top), "IP: " + str(IP), font=font, fill=255)
draw.text((x, top+15), str(time.strftime("%Y%m%d %H:%M:%S", time.localtime())), font=font, fill=255)
draw.text((x, top+35), str("CH2O: "+ppm), font=font, fill=255)
disp.image(image)
disp.display()
利用crontab实现监控1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#!/bin/sh
v_num=`ps -ef|grep "read.py"|grep -v grep |wc -l`
if [ $v_num -lt 1 ]
then
date
echo "read process die"
ps -ef|grep "read.py"|grep -v grep |awk '{ print $2 }'|xargs kill -9
cd /home/pi/m4bln
python read.py &
sleep 20
v_num=`ps -ef|grep "read.py"|grep -v grep |wc -l`
if [ $v_num -eq 1 ]
then
date
echo "reopen read process"
fi
else
date
echo "everything is OK :)"
fi
参考资料:
- 树莓派串口配置 https://www.abelectronics.co.uk/kb/article/1035/raspberry-pi-3--4-and-zero-w-serial-port-usage
- https://www.raspberrypi.org/documentation/configuration/uart.md
- ZE08-CH2O模组文档 http://style.winsensor.com/pro_pdf/ZE08-CH2O.pdf
- http://shumeipai.nxez.com/2017/09/13/raspberry-pi-network-configuration-before-boot.html 无屏幕和键盘配置树莓派WiFi和SSH