一.唠嗑

大三下学期在跟材料学院的一个老师做项目,说是要完成自动检测实验室环境情况,包括温湿度、火焰以及厌恶等,最终目标是制作出一个可以在实验室全自动行驶的检测机器人,整个项目组就我一个计算机的成员…
结果就是我只完成了树莓派的传感器检测模块。

二.传感器

2.1 DHT22温湿度传感器

这个传感器比DHT11传感器更好,精确度达到了97左右,二DHT11只有92左右。价格的话都很便宜的,我记得我的导师100块钱买了30个不同的传感器,我大概全部连接了六七个传感器吧。

DHT22代码:

#!/usr/bin/python
import sys
import Adafruit_DHT
import time
import json,os

def jsonWrite(data,tdate,name):
    pathfile = "web/data/"+ name + "/" + tdate +".json"
    if os.path.exists(pathfile):
      file =open(pathfile,"rb+")
      file.seek(-1,os.SEEK_END)
      file.truncate()
      file.write(",")
      json.dump(data,file)
      file.write("]")
      file.close()
    else:
      file =open(pathfile,"w")
      file.write("[")
      json.dump(data,file)
      file.write("]")
      file.close()
timecount = 0
while True:
    sensor = Adafruit_DHT.DHT22
    humidity, temperature = Adafruit_DHT.read_retry(sensor, 26)
    if humidity is not None and temperature is not None:
        todaytime = time.strftime('%Y-%m-%d',time.localtime(time.time()))
        msg =  time.strftime('%Y-%m-%d %H:%M',time.localtime(time.time())) + '\n' + str(format(temperature,".1f")) + ' C  ' + str(format(humidity,".1f")) + '%'
        i = {"time":time.strftime('%H:%M',time.localtime(time.time())),"tmp":format(temperature,".1f"),"hmt":format(humidity,".1f")}
        jsonWrite(i,todaytime,"min")
        print(msg)
    if(timecount >=60):
        timecount = 0
        jsonWrite(i,todaytime,"hour")
    time.sleep(60)
timecount = timecount +1

2.2 烟雾传感器

直接上代码:

#! /usr/bin/env python3
import RPi.GPIO as GPIO # 导入库,并进行别名的设置
import time

CHANNEL=36 # 确定引脚口。按照真实的位置确定
GPIO.setmode(GPIO.BOARD) # 选择引脚系统,这里我们选择了BOARD
GPIO.setup(CHANNEL,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
#初始化引脚,将36号引脚设置为输入下拉电阻,因为在初始化的时候不确定的的引电平,因此这样设置是用来保证精准,(但是也可以不写“pull_up_down=GPIO.PUD_DOWN”)

# 带有异常处理的主程序
try:
         while True: # 执行一个while死循环
          status=GPIO.input(CHANNEL) # 检测36号引脚口的输入高低电平状态
          #print(status) # 实时打印此时的电平状态
          if status == True: # 如果为高电平,说明MQ-2正常,并打印“OK”
                        print ( ‘ 正常 ‘ )      
           else:    # 如果为低电平,说明MQ-2检测到有害气体,并打印“dangerous”
                        print ( ‘ 检测到危险气体 ! ! ! ‘ )
           time.sleep(0.1) # 睡眠0.1秒,以后再执行while循环
except KeyboardInterrupt: # 异常处理,当检测按下键盘的Ctrl+C,就会退出这个>脚本
            GPIO.cleanup() # 清理运行完成后的残余

2.3 声音传感器:

import RPi.GPIO as GPIO 
import time
CHANNEL=7 
GPIO.setmode(GPIO.BOARD) 
GPIO.setup(CHANNEL,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
try:
    while True:
        status=GPIO.input(CHANNEL) 
        #print(status) 
        if status == True: 
            print ("No Sound...")
        else: 
            print ("Having Sound!!!")
        time.sleep(2)
except KeyboardInterrupt:
    GPIO.cleanup()

2.4 红外避障传感器

import RPi.GPIO as GPIO 
import time
from twilio.rest import TwilioRestClient

CHANNEL=7 
GPIO.setmode(GPIO.BOARD) 
GPIO.setup(CHANNEL,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
try:
    while True:
        status=GPIO.input(CHANNEL) 
        #print(status) 
        if status == True: 
            print ("No Obstacle...")
        else: 
            print ("Having Obstacle!!!")
        time.sleep(2)
except KeyboardInterrupt:
    GPIO.cleanup()

2.5 人体红外传感器:

# -*- coding: utf-8 -*-
import time
import RPi.GPIO as GPIO

BODY_GPIO = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(BODY_GPIO, GPIO.IN)

def body_detect():
    signal = GPIO.input(BODY_GPIO)
    if signal == 1:
        print "DETECT BODY!"
    else:
        print "NO BODY!"

if __name__ == "__main__":
    count = 0
    while True:
        body_detect()
        time.sleep(6)
        count += 1
        if count == 20:
            break
    GPIO.cleanup()

2.6 用twilio免费打电话以及发短信

发短信:

#填写你在twilio的账号
account = "ACXXXXXXXXXXXXXXXXX"
#填入你在twilio的app token
token = "YYYYYYYYYYYYYYYYYY"
#填入你申请的号码
twilioNumber = "00000000"
#填入你验证的手机号
myNumber = "111111111"

client = TwilioRestClient(account, token)
message=client.messages.create(to=myNumber, from_=twilioNumber, body="Fire!!!")
print(message.sid)

打电话:

#填写你在twilio的账号
account = "ACXXXXXXXXXXXXXXXXX"
#填入你在twilio的app token
token = "YYYYYYYYYYYYYYYYYY"
#填入你申请的号码
twilioNumber = "00000000"
#填入你验证的手机号
myNumber = "111111111"

client = TwilioRestClient(account, token)
#url所对应的文件是制定的,是twilio官网的一个示例文件,可以通过构建自己的文件
client.calls.create(url='https://demo.twilio.com/welcome/voice/', to=myNumber , from_=twilioNumber)

print(call.sid)