【室内温度+树莓派性能监控】树莓派+DS18B20温度传感器+0.96寸OLED显示屏使用及安装经验分享

以下内容为本人原创
原文链接:https://blog.csdn.net/Yhen1/article/details/113760948
作者:@Yhen
发布网站:CSDN
未经本人同意禁止转载,如需转载请说明此出处,违者必究

大噶好!我是Yhen.
最近在捣鼓我吃灰许久的树莓派
买了一些传感器回来玩玩
跟着网上的教程实现了一些功能.

然后我也会把它们分享给大家,同时也是给自己的一个记录吧!

以下是本文中会用到的物品清单
1.树莓派(我用的是树莓派zero w【已焊排针版本】)
2.DS18B20温度传感器
3.ssd1306 0.96寸OLED显示屏
4.彩虹排线
5.T型拓展版
6.7根公对母杜邦线
7.面包板

我们先来预览一下效果
在这里插入图片描述

前面五行是树莓派的一些基本信息,最后一行是当前的室内温度
其中显示ip地址还是挺有必要的,特别对于我这种没有配显示屏的用户来说。

比如前几天,我在vnc中控制树莓派,一时手快将树莓派的wifi切换到了我的手机热点
顿时,vnc就掉线了(因为我电脑也是连的家里的wifi,所以两台设备不在同一个局域网中了)

完蛋,我还不知道pi连接手机时的ip啊…

然后我望向显示屏,显示IP的位置变成了 IP:

再两秒后,变成了IP:192.168.43.8

然后我连忙将电脑也连上了热点,最后成功通过这个ip地址连接上了Pi

看,这多香啊

要是像以前的话,我又要拔掉电源,带上我的Pi和mini-html转html线,USB-HUB,键鼠一起迁徙到客厅,把电视当做树莓派的显示屏,再来连接上wifi

唉,多麻烦呀

所以吧…我觉得这个项目还是挺有实用性的

嗯,那么下面开始演示

一.接线

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

首先看下这个OLED屏幕
共有4个引脚
分别是SCL,SDA,VCC,GND
分别接在树莓派的pin5,pin3,pin2,pin9
在这里插入图片描述

DS18B20有三个引脚:VCC,DQ,GND
分别接在Pin17,Pin7,Pin39
在这里插入图片描述

在这里插入图片描述

二.0.96寸屏安装

开启i2c

sudo apt-get install -y python-smbus
sudo apt-get install -y i2c-tools
sudo raspi-config

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
然后重启

sudo reboot

使用以下命令看是否能识别到屏幕

sudo i2cdetect -y 1

在这里插入图片描述

接着下载屏幕的驱动

git clone https://gitee.com/Yhen_CN/luma.oled.git

这个驱动是我导入GitHub大佬的到gitee中去的,GitHub下载太慢了…

下载Adafruit-SSD1306库

sudo pip install Adafruit-SSD1306

安装PIL库

sudo apt-get install python-pil python3-pil

下载示例文件

git clone https://github.com/adafruit/Adafruit_Python_SSD1306.git

安装好以后
就可以运行示例文件测试一下了

cd Adafruit_Python_SSD1306/
cd examples/
python3 stats.py

如果显示屏中显示这样
那恭喜你 成功点亮了
在这里插入图片描述
但是你会发现这些信息前面怎么会有个b’ 啊,IP后面怎么会有个\n
太碍眼了吧…

那是因为获取到了这些信息是Bytes格式的,而Python中默认是str
所以我们只需要将这些信息转换成str就好了
然后替换掉原来的数据即可
在这里插入图片描述
修改之后 就能够正常显示了
在这里插入图片描述
显示屏弄好了,接下来来点亮DS18B20测温模块

三.DS18B20测温模块的使用

sudo raspi-config

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
然后重启

sudo reboot

接着进入 /sys/bus/w1/devices/

cd /sys/bus/w1/devices/
ls

如果看到这个28-xxx则表示连接成功了
每个人都不一样的,但是貌似都是28开头的
在这里插入图片描述
进入这个文件中

cd 28-01202913b0f4
cat w1_slave

可以看到t=24687
这个数除以1000即是当前温度的摄氏度了
在这里插入图片描述
在python中获取温度
记得将28-01202913b0f4替换成自己的设备号

tfile = open("/sys/bus/w1/devices/28-01202913b0f4/w1_slave")
text =  tfile.read()
tfile.close()
secondline=text.split("\n")[1]
temperaturedata = secondline.split(" ")[9]
temperature = float(temperaturedata[2:])
temperature =round( temperature / 1000,2)

四.获取树莓派CPU的温度值

cat /sys/class/thermal/thermal_zone0/temp

在python中获取

path='/sys/class/thermal/thermal_zone0/temp'
ctemfile=open(path)
text2=ctemfile.read()
ctemfile.close()
cpu_tem=float(text2 )/1000

五.代码整合

接下来要将cpu的温度和室内的温度显示到显示屏中

sudo nano stats.py

将122-125行的内容删掉
在这里插入图片描述
然后插入以下代码
记得将28-01202913b0f4替换成自己的设备号

tfile = open("/sys/bus/w1/devices/28-01202913b0f4/w1_slave")
text =  tfile.read()
tfile.close()
secondline=text.split("\n")[1]
temperaturedata = secondline.split(" ")[9]
temperature = float(temperaturedata[2:])
temperature =round( temperature / 1000,2)

path='/sys/class/thermal/thermal_zone0/temp'
ctemfile=open(path)
text2=ctemfile.read()
ctemfile.close()
cpu_tem=float(text2 )/1000

# Write two lines of text.
ip2=str(IP,encoding='utf8')
CPU2=str(CPU,encoding='utf8')
MemUsage2=str(MemUsage,encoding='utf8')
Disk2=str(Disk,encoding='utf8')
draw.text((x, top),"IP: " +ip2,  font=font, fill=255)
draw.text((x, top+8),str(CPU2), font=font, fill=255)
draw.text((x, top+16),str(MemUsage2),  font=font, fill=200)
draw.text((x, top+25),str(Disk2),  font=font, fill=255)
draw.text((x, top + 35), 'Cpu_Tem:' + str(cpu_tem), font=font, fill=255)
draw.text((x, top + 45),'Environment_Tem:'+ str(temperature), font=font, fill=255)

保存退出以后
运行代码
就可以成功显示啦

python3 stats.py &

在这里插入图片描述

刚刚将程序放在了后台运行
要将程序放到前台运行只需输入命令

fg

以下是关闭的步骤
输入命令 jobs -l 查看任务的PID
在这里插入图片描述
然后通过kill + PID号结束进程

kill 30858

要注意的是,即使你关闭了进程,显示屏也不会变黑
会一直显示着最后的画面

六.完整代码

stats.py

# Copyright (c) 2017 Adafruit Industries
# Author: Tony DiCola & James DeVito
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import time

import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import subprocess

# Raspberry Pi pin configuration:
RST = None     # on the PiOLED this pin isnt used
# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

# Beaglebone Black pin configuration:
# RST = 'P9_12'
# Note the following are only used with SPI:
# DC = 'P9_15'
# SPI_PORT = 1
# SPI_DEVICE = 0

# 128x32 display with hardware I2C:
+disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)

# 128x64 display with hardware I2C:
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

# Note you can change the I2C address by passing an i2c_address parameter like:
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)

# Alternatively you can specify an explicit I2C bus number, for example
# with the 128x32 display you would use:
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_bus=2)

# 128x32 display with hardware SPI:
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))

# 128x64 display with hardware SPI:
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))

# Alternatively you can specify a software SPI implementation by providing
# digital GPIO pin numbers for all the required display pins.  For example
# on a Raspberry Pi with the 128x32 display you might use:
# disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, sclk=18, din=25, cs=22)

# Initialize library.
disp.begin()

# Clear display.
disp.clear()
disp.display()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))

# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)

# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)

# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height-padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0


# Load default font.
font = ImageFont.load_default()

# Alternatively load a TTF font.  Make sure the .ttf font file is in the same directory as the python script!
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
# font = ImageFont.truetype('Minecraftia.ttf', 8)

while True:

    # Draw a black filled box to clear the image.
    draw.rectangle((0,0,width,height), outline=0, fill=0)

    # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load
    cmd = "hostname -I | cut -d\' \' -f1"
    IP = subprocess.check_output(cmd, shell = True )
    cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'"
    CPU = subprocess.check_output(cmd, shell = True )
    cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'"
    MemUsage = subprocess.check_output(cmd, shell = True )
    cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'"
    Disk = subprocess.check_output(cmd, shell = True )

    # Write two lines of text.

    draw.text((x, top),       "IP: " + str(IP),  font=font, fill=255)
    draw.text((x, top+8),     str(CPU), font=font, fill=255)
    draw.text((x, top+16),    str(MemUsage),  font=font, fill=255)
    draw.text((x, top+25),    str(Disk),  font=font, fill=255)

    # Display image.
    disp.image(image)
    disp.display()
    time.sleep(.1)

接触树莓派的时间不长
可能有写不好或者错误的地方
请大佬们多多指教
如果觉得对你有帮助的话 不妨一键三连一下哦
谢谢了

那么下期再见
886

关注我的公众号“Yhen杂文铺”获取更多精彩内容哦~
在这里插入图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值