前言
手上有一台树莓派,平时在运行一些服务,现在天气热了导致树莓派严重发烫,使用python实现温度过高时播报当前温度,还可以通过树莓派的gpio引脚自动启动风扇进行散热等玩法。
环境安装
首先pyttsx3是基于python3以及pip3,正常树莓派自带(pip3没有自带),没有则手动搜索引擎安装
安装pip3可以参照
安装espeak
先安装语音转换引擎(重要)
sudo apt-get install espeak
安装pyttsx3
sudo pip3 install pyttsx3
问题
如果失败则更新下pip3
sudo pip3 install --upgrade pip
继续失败则尝试降低下版本
sudo pip3 install pyttsx3==2.71
代码
import os
import time
import pyttsx3
# Return CPU temperature as a character string
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
return(res.replace("temp=","").replace("'C ","").replace(".","")[0:2])
if __name__ == '__main__':
# CPU informatiom
CPU_temp = getCPUtemperature()
# 判断温度大于50度
if(int(CPU_temp) > 50):
print('CPU Temperature = '+CPU_temp)
engine = pyttsx3.init() # 创建对象
rate = engine.getProperty('rate') # 获取当前语速(默认值)
#print (rate) # 打印当前语速(默认值)
engine.setProperty('rate', 135) # 设置一个新的语速
volume = engine.getProperty('volume') # 获取当前的音量 (默认值)(min=0 and max=1)
#print (volume) # 打印当前音量(默认值)
engine.setProperty('volume',1.0) # 设置一个新的音量(0 < volume < 1)
voices = engine.getProperty('voices') # 获取当前的音色信息
engine.setProperty('voice', voices[0].id) # 改变中括号中的值,0为男性,1为女性
engine.setProperty('voice','zh') #将音色中修改音色的语句替换
engine.say("警告 温度:"+CPU_temp)
engine.runAndWait()
保存文件为temp.py
执行
python3 temp.py
定时任务
定时后台监控温度播报,这里使用linux自带的定时任务crontab
crontab -e
* * * * * python3 /home/pi/python/temp.py
以上一分钟检测一次
本文由 SAn 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2020/10/16 16:22