语言控制功能:
#coding:utf-8
from aip import AipSpeech
from aip import AipFace
import os
import RPi.GPIO as GPIO
import time
import threading
from picamera import PiCamera
import urllib.request
import base64
delay=2.4#窗帘步进电机演延时2.4ms
#引脚号
R,G,B = 14,15,18#灯光引脚
In=22#按键引脚
lock=6#锁的控制引脚
#步进电机控制器引脚
pin_4 = 4
pin_17 = 17
pin_23 = 23
pin_24 = 24
#编码方式
GPIO.setmode(GPIO.BCM)
"""引脚输入输出方式"""
#RGB灯引脚设置为输出
GPIO.setup(R,GPIO.OUT)
GPIO.setup(G,GPIO.OUT)
GPIO.setup(B,GPIO.OUT)
#按键引脚设置为输入
GPIO.setup(In,GPIO.IN,pull_up_down=GPIO.PUD_UP)
#锁为输出
GPIO.setup(lock,GPIO.OUT)
GPIO.output(lock,GPIO.LOW)
"""PWM调光"""
pwmR = GPIO.PWM(R,70)
pwmG = GPIO.PWM(G,70)
pwmB = GPIO.PWM(B,70)
pwmR.start(0)
pwmG.start(0)
pwmB.start(0)
"""百度人脸识别API账号信息"""
APP_ID_Face = '15050553'
API_KEY_Face = 'rlRrtRL5oRdXGh71jgg1OmyN'
SECRET_KEY_Face ='dK5TpuTAZn2nw5eVpspZLmF5Qs1Uu8A1'
client_Face = AipFace(APP_ID_Face, API_KEY_Face, SECRET_KEY_Face)
"""百度语音的账号信息"""
APP_ID = '14992590'
API_KEY = 'sMz9feVUT9DkdemD0iwsVlD8'
SECRET_KEY = 'EIKmYpTP71oKuBWuauIOZfGwwbTiRUOC'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
#图像编码方式
IMAGE_TYPE='BASE64'
camera = PiCamera()#定义一个摄像头对象
#人脸识别用户组
GROUP = 'lihuaqiang'
#获取图像
def getimage():
camera.start_preview()
time.sleep(1)
camera.capture('faceimage.jpg')
time.sleep(1)
#对图片的格式进行转换
def transimage():
f = open('faceimage.jpg','rb')
img = base64.b64encode(f.read())
return img
#上传到百度api进行人脸检测
def go_api(image):
result = client_Face.search(str(image, 'utf-8'), IMAGE_TYPE, GROUP)
if result['error_msg'] == 'SUCCESS':
name = result['result']['user_list'][0]['user_id']
score = result['result']['user_list'][0]['score']
#对当前人脸进行打分,如果大于80分就认为是人脸库中的
if score > 50:
"""对人脸进行匹配,看是哪个用户"""
if name == '_01lihuaqiang':
GPIO.output(lock,GPIO.HIGH)
os.system("sudo mplayer 声音/欢迎李华强.mp3")
time.sleep(3)
GPIO.output(lock,GPIO.LOW)
if name == '_01jishiershi':
GPIO.output(lock,GPIO.LOW)
os.system("sudo mplayer 声音/欢迎吉石.mp3")
if name == "_01quhao":
GPIO.output(lock,GPIO.LOW)
os.system("sudo mplayer 声音/欢迎屈浩.mp3")
if name == "_helaoshi":
GPIO.output(lock,GPIO.HIGH)
os.system("sudo mplayer 声音/欢迎老师.mp3")
time.sleep(2)
GPIO.output(lock,GPIO.LOW)
"""不匹配人脸库中的人脸"""
if score<=30:
os.system("sudo mplayer 声音/不认识.mp3")
name = 'Unknow'
return 0
#获取当前时间
curren_time = time.asctime(time.localtime(time.time()))
#将开门记录保存下来
f = open('Log.txt','a')
f.write("Person: " + name + " " + "Time:" + str(curren_time)+'\n')
f.close()
return 1
else:
return 0
#播放音乐
def playmusic():
os.system("sudo mplayer music.mp3")
# 读取文件
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
#步进电机初始化函数
def init():
GPIO.setwarnings(False)
GPIO.setup(pin_4, GPIO.OUT)
GPIO.setup(pin_17, GPIO.OUT)
GPIO.setup(pin_23, GPIO.OUT)
GPIO.setup(pin_24, GPIO.OUT)
#步进电机正转函数
def forward(delay):
setStep(1, 0, 0, 0)
time.sleep(delay)
setStep(0, 1, 0, 0)
time.sleep(delay)
setStep(0, 0, 1, 0)
time.sleep(delay)
setStep(0, 0, 0, 1)
time.sleep(delay)
#步进电机反转函数
def backward(delay):
setStep(0, 0, 0, 1)
time.sleep(delay)
setStep(0, 0, 1, 0)
time.sleep(delay)
setStep(0, 1, 0, 0)
time.sleep(delay)
setStep(1, 0, 0, 0)
time.sleep(delay)
#步进电机脉冲输出控制函数
def setStep(w1, w2, w3, w4):
GPIO.output(pin_4, w1)
GPIO.output(pin_17, w2)
GPIO.output(pin_23, w3)
GPIO.output(pin_24, w4)
#给出提示信息
os.system("sudo mplayer 声音/语音控制.mp3")
#输出灯光模式总类让用户知道
os.system("sudo mplayer 声音/灯光模式.mp3")
#初始化步进电机
init()
#主程序
while True:
time.sleep(0.5)
#检测是否需要进行控制
if GPIO.input(In)==GPIO.LOW:
while GPIO.input(In) == GPIO.LOW:
pass
#需要控制就给出提示
os.system("sudo mplayer 声音/开始.mp3")
#获取控制命令
os.system('arecord -D "plughw:1" -f S16_LE -r 16000 -d 4 test.pcm')
#识别本地文件
a = client.asr(get_file_content('test.pcm'), 'pcm', 16000 , {'dev_pid': 1536,})
voice_str=str(a['result'])#将识别内容转化为字符串
#two_word = voice_str[2:4]
#three_word = voice_str[2:5]
control=voice_str[2:-2]#取出控制命令
#print(two_word,three_word)
print(control)
"""根据不同的控制命令进行不同的动作"""
if control==str("开灯"):
pwmR.ChangeDutyCycle(100)
pwmG.ChangeDutyCycle(100)
pwmB.ChangeDutyCycle(100)
os.system("sudo mplayer 声音/开灯.mp3")
if control==str("关灯"):
pwmR.ChangeDutyCycle(0)
pwmG.ChangeDutyCycle(0)
pwmB.ChangeDutyCycle(0)
os.system("sudo mplayer 声音/关灯.mp3")
if control==str("红光模式"):
pwmR.ChangeDutyCycle(100)
pwmG.ChangeDutyCycle(0)
pwmB.ChangeDutyCycle(0)
os.system("sudo mplayer 声音/红光.mp3")
if control==str("绿光模式"):
pwmR.ChangeDutyCycle(0)
pwmG.ChangeDutyCycle(100)
pwmB.ChangeDutyCycle(0)
os.system("sudo mplayer 声音/绿光.mp3")
if control==str("蓝光模式"):
pwmR.ChangeDutyCycle(0)
pwmG.ChangeDutyCycle(0)
pwmB.ChangeDutyCycle(100)
os.system("sudo mplayer 声音/蓝光.mp3")
if control==str("浪漫模式"):
pwmR.ChangeDutyCycle(100)
pwmG.ChangeDutyCycle(0)
pwmB.ChangeDutyCycle(100)
os.system("sudo mplayer 声音/浪漫.mp3")
if control==str("睡眠模式"):
os.system("sudo mplayer 声音/睡眠.mp3")
for i in range(0,101):
pwmR.ChangeDutyCycle(100-i)
pwmG.ChangeDutyCycle(100-i)
time.sleep(0.2)
if control==str("暖色调"):
pwmR.ChangeDutyCycle(100)
pwmG.ChangeDutyCycle(60)
pwmB.ChangeDutyCycle(3)
os.system("sudo mplayer 声音/暖色调.mp3")
if control==str("冷色调"):
pwmR.ChangeDutyCycle(50)
pwmG.ChangeDutyCycle(85)
pwmB.ChangeDutyCycle(100)
os.system("sudo mplayer 声音/冷色调.mp3")
if control==str("KTV模式"):
os.system("sudo mplayer 声音/KTV.mp3")
thread = threading.Thread(target=playmusic)
thread.start()
for i in range(5):
for r in range(0,101,10):
pwmR.ChangeDutyCycle(r)
for g in range(0,101,10):
pwmG.ChangeDutyCycle(g)
for b in range(0,101,10):
pwmB.ChangeDutyCycle(3)
time.sleep(0.03)
if control==str("开窗"):
for i in range(1800):
forward(int(delay)/1000.0)
os.system("sudo mplayer 声音/开窗.mp3")
if control==str("关窗"):
for i in range(1800):
backward(int(delay)/1000.0)
os.system("sudo mplayer 声音/关窗.mp3")
if control==str("开门"):
os.system("sudo mplayer 声音/开门.mp3")
getimage()
img = transimage()
res = go_api(img)
if res ==1:
print("门已打开")
else:
print("门无法打开")
time.sleep(1)
camera.stop_preview()
温湿度上传显示功能:
信息采集程序:
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
channel =2
data = []
j = 0
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
time.sleep(1)
GPIO.setup(channel, GPIO.OUT)
GPIO.output(channel, GPIO.LOW)
time.sleep(0.02)
GPIO.output(channel, GPIO.HIGH)
GPIO.setup(channel, GPIO.IN)
while GPIO.input(channel) == GPIO.LOW:
continue
while GPIO.input(channel) == GPIO.HIGH:
continue
while j < 40:
k = 0
while GPIO.input(channel) == GPIO.LOW:
continue
while GPIO.input(channel) == GPIO.HIGH:
k += 1
if k > 100:
break
if k < 8:
data.append(0)
else:
data.append(1)
j += 1
print("sensor is working.")
print(data)
humidity_bit = data[0:8]
humidity_point_bit = data[8:16]
temperature_bit = data[16:24]
temperature_point_bit = data[24:32]
check_bit = data[32:40]
humidity = 0
humidity_point = 0
temperature = 0
temperature_point = 0
check = 0
for i in range(8):
humidity += humidity_bit[i] * 2 ** (7-i)
humidity_point += humidity_point_bit[i] * 2 ** (7-i)
temperature += temperature_bit[i] * 2 ** (7-i)
temperature_point += temperature_point_bit[i] * 2 ** (7-i)
check += check_bit[i] * 2 ** (7-i)
tmp = humidity + humidity_point + temperature + temperature_point
if check == tmp:
print "temperature :", temperature, "*C, humidity :", humidity, "%"
else:
print "wrong"
print "temperature :", temperature, "*C, humidity :", humidity, "% check :", check, ", tmp :", tmp
mytemp = '%f' %temperature
myhumi = '%f' %humidity
tmp_output = open('/home/pi/dht11/tmp_data.txt', 'w')
hud_output = open('/home/pi/dht11/hum_data.txt', 'w')
tmp_output.write(mytemp)
hud_output.write(myhumi)
tmp_output.close
hud_output.close
GPIO.cleanup()
上传温度程序:
import urllib2
import json
import time
import datetime
APIKEY = 'VfI2evG7h1=H2jGSz9=sz98ijM0= '
def http_put():
file = open("/home/pi/dht11/tmp_data.txt")
temperature= float(file.read())
CurTime = datetime.datetime.now()
url='http://api.heclouds.com/devices/505201136/datapoints'
values={'datastreams':[{"id":"temp","datapoints":[{"at":CurTime.isoformat(),"value":temperature}]}]}
print("the time is: %s" %CurTime.isoformat())
print("The upload temperature value is: %.3f" %temperature)
jdata = json.dumps(values)
print(jdata)
request = urllib2.Request(url, jdata)
request.add_header('api-key', APIKEY)
request.get_method = lambda:'POST'
request = urllib2.urlopen(request)
return request.read()
while True:
time.sleep(5)
resp = http_put()
print("OneNET result:\n %s" %resp)
time.sleep(5)
上传湿度程序:
import urllib2
import json
import time
import datetime
APIKEY = 'VfI2evG7h1=H2jGSz9=sz98ijM0= '
def http_put():
file = open("/home/pi/dht11/hum_data.txt")
humidity= float(file.read())
CurTime = datetime.datetime.now()
url='http://api.heclouds.com/devices/505201136/datapoints'
values={'datastreams':[{"id":"hum","datapoints":[{"at":CurTime.isoformat(),"value":humidity}]}]}
print("the time is: %s" %CurTime.isoformat())
print("The upload humidity value is: %.3f" %humidity)
jdata = json.dumps(values)
print(jdata)
request = urllib2.Request(url, jdata)
request.add_header('api-key', APIKEY)
request.get_method = lambda:'POST'
request = urllib2.urlopen(request)
return request.read()
time.sleep(5)
resp = http_put()
print("OneNET result:\n %s" %resp)
file.closes
拍照:
from picamera import PiCamera
from time import sleep
camera = PiCamera()
n=0
while True:
camera.start_preview()
sleep(2)
a=input("所否拍摄:")
if a=="是":
camera.capture('/home/pi/Desktop/picture/%d.jpg'%n)
n=n+1
else:
break
camera.stop_preview()
监控:
from picamera import PiCamera
from time import sleep
camera = PiCamera()
camera.start_preview()
camera.start_recording('/home/pi/Desktop/video.h264')
sleep(10)
camera.stop_recording()
camera.stop_preview()
火焰报警:
#include<wiringPi.h>
#include<stdio.h>
#include<sys/time.h>
#define FIRE 29
#define BEEP 28
int main()
{
if (wiringPiSetup()==-1)
{
printf("初始化失败!\n");
return 1;
}
pinMode(FIRE,INPUT);//将FIRE口设置为输入模式
pinMode(BEEP,OUTPUT);//将蜂鸣器设置为输出模式
while(1)
{
if (digitalRead(FIRE)==1)//高电平说明有火,就报警
{
printf("没有火\n");
digitalWrite(BEEP,LOW);
delay(333);
}
else
{
printf("有火\n");
digitalWrite(BEEP,HIGH);
delay(333);
}
}
return 0;
}
对话机器人:
语音识别代码:
# coding: utf-8
import sys
import json
import urllib2
import base64
import requests
reload(sys)
sys.setdefaultencoding('utf-8')
def get_access_token():
url = 'https://openapi.baidu.com/oauth/2.0/token'
body = { 'grant_type':'client_credentials','client_id':'mGxvq3Nwr3aVjD4UFIFGsaMD','client_secret':'YIN3wxizj16zCRYZ6EGpdopuA6FwHRhB'}
r = requests.post(url,data=body,verify=True)
respond = json.loads(r.text)
return respond['access_token']
def yuyinshibie_api(audio_data,token):
speech_data = base64.b64encode(audio_data).decode('utf-8')
speech_length = len(audio_data)
post_data = {'format':'wav','rate':16000,'channel':1,'cuid':'B8-27-EB-BA-24-14','token':token,'speech':speech_data,'len':speech_length}
url = "http://vop.baidu.com/server_api"
json_data = json.dumps(post_data).encode("utf-8")
json_length = len(json_data)
req = urllib2.Request(url, data=json_data)
req.add_header("Content-Type", "application/json")
req.add_header("Content-Length", json_length)
resp = urllib2.urlopen(req)
resp = resp.read()
resp_data = json.loads(resp.decode("utf-8"))
if resp_data["err_no"] == 0:
return resp_data["result"]
else:
print(resp_data)
return None
def asr_main(filename,tok):
try:
f = open(filename,'rb')
audio_data = f.read()
f.close()
resp = yuyinshibie_api(audio_data,tok)
return resp[0]
except Exception,e:
return '识别失败'.encode('utf-8')
图灵机器人对话:
# coding: utf-8
import requests
import json
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
def Tuling(words):
Tuling_API_KEY = "6e363e966e904675a3590363a65c07d3"
body = {"key":Tuling_API_KEY,"info":words.encode("utf-8")}
url = "http://www.tuling123.com/openapi/api"
r = requests.post(url,data=body,verify=True)
if r:
date = json.loads(r.text)
print date["text"]
return date["text"]
else:
return None
将对话内容进行语音合成:
# coding: utf-8
import sys
import urllib2
import json
import os
import yuyinshibie
reload(sys)
sys.setdefaultencoding('utf-8')
def yuyinhecheng_api(tok,tex):
cuid = 'B8-27-EB-BA-24-14'
spd = '4'
url = 'http://tsn.baidu.com/text2audio?tex='+tex+'&lan=zh&cuid='+cuid+'&ctp=1&tok='+tok+'&per=3'
return url
def tts_main(filename,words,tok):
voice_date = yuyinhecheng_api(tok,words)
f = open(filename,"wb")
f.write(voice_date)
f.close()
主要代码:
# coding: utf-8
import os
import time
import yuyinhecheng
import Turling
import yuyinshibie
tok = yuyinshibie.get_access_token()#获取百度语音识别密钥
switch = True
while switch:
os.system('sudo arecord -D "plughw:1" -f S16_LE -r 16000 -d 3 /home/pi/Desktop/voice.wav')
time.sleep(0.5)
info = yuyinshibie.asr_main("/home/pi/Desktop/voice.wav",tok)
if '关闭'.encode("utf-8") in info:#如果录音中含有关闭信息
while True:
os.system('sudo arecord -D "plughw:1" -f S16_LE -r 16000 -d 10 /home/pi/Desktop/voice.wav')
time.sleep(10)
info = yuyinshibie.asr_main("/home/pi/Desktop/voice.wav",tok)#拿到识别结果
if '开启'.encode("utf-8") in info:
break
url = "http://tsn.baidu.com/text2audio?tex=开启成功&lan=zh&cuid=B8-27-EB-BA-24-14&ctp=1&tok="+tok+"&per=3"
os.system('mpg123 "%s"'%url)
elif '暂停'.encode("utf-8") in info:
url = "http://tsn.baidu.com/text2audio?tex=开始暂停&lan=zh&cuid=B8-27-EB-BA-24-14&ctp=1&tok="+tok+"&per=3"
os.system('mpg123 "%s"'%url)
time.sleep(10)
url = "http://tsn.baidu.com/text2audio?tex=暂停结束&lan=zh&cuid=B8-27-EB-BA-24-14&ctp=1&tok="+tok+"&per=3"
os.system('mpg123 "%s"'%url)
continue
else:
tex = Turling.Tuling(info)#将识别结果传给图灵机器人
url = yuyinhecheng.yuyinhecheng_api(tok,tex)
os.system('mpg123 "%s"'%url)
time.sleep(0.5)
智能光照窗帘:
import RPi.GPIO as GPIO
import time
delay=2.4 #delay 2.5ms
pin_4 = 4
pin_17 = 17
pin_23 = 23
pin_24 = 24
light = 0
GPIO.setmode(GPIO.BCM) #设置引脚的编码方式
GPIO.setup(light,GPIO.IN)
kaichuang = 0#开窗控制标志位
guanchuang = 0#关窗控制标志位
def init():
GPIO.setwarnings(False)
GPIO.setup(pin_4, GPIO.OUT)
GPIO.setup(pin_17, GPIO.OUT)
GPIO.setup(pin_23, GPIO.OUT)
GPIO.setup(pin_24, GPIO.OUT)
def forward(delay):
setStep(1, 0, 0, 0)
time.sleep(delay)
setStep(0, 1, 0, 0)
time.sleep(delay)
setStep(0, 0, 1, 0)
time.sleep(delay)
setStep(0, 0, 0, 1)
time.sleep(delay)
def backward(delay):
setStep(0, 0, 0, 1)
time.sleep(delay)
setStep(0, 0, 1, 0)
time.sleep(delay)
setStep(0, 1, 0, 0)
time.sleep(delay)
setStep(1, 0, 0, 0)
time.sleep(delay)
def setStep(w1, w2, w3, w4):
GPIO.output(pin_4, w1)
GPIO.output(pin_17, w2)
GPIO.output(pin_23, w3)
GPIO.output(pin_24, w4)
def main():
init()
while True:
"""当光照比较强时"""
if GPIO.input(light)==1:
#判断是否达到开窗上限
if kaichuang < 1800:
backward(int(delay) / 1000.0)
kaichuang = kaichuang+1
else:
#如果已达开窗上限并且又达到了关窗上限则将关窗标志位清零
if guanchuang >= 1800:
guanchuang = 0
else:
#判断是否达到关窗上限
if guanchuang < 1800:
forward(int(delay) / 1000.0)
guanchuang = guanchuang+1
else:
#如果已达开窗上限并且又达到了关窗上限则将关窗标志位清零
if kaichuang >= 1800:
kaichuang = 0
main() #调用main
燃气报警换气:
import RPi.GPIO as GPIO # 导入库,并进行别名的设置
import time
import os
CHANNEL=19 # 确定引脚口。按照真实的位置确定
feng=3
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) # 选择引脚系统,这里我们选择了BOARD
GPIO.setup(CHANNEL,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
#初始化引脚,将36号引脚设置为输入下拉电阻,因为在初始化的时候不确定的的引电平,因此这样设置是用来保证精准,(但是也可以不写“pull_up_down=GPIO.PUD_DOWN”)
GPIO.setup(feng,GPIO.OUT)
# 带有异常处理的主程序
try:
while True: # 执行一个while死循环
status=GPIO.input(CHANNEL) # 检测36号引脚口的输入高低电平状态
#print(status) # 实时打印此时的电平状态
if status == True: # 如果为高电平,说明MQ-2正常,并打印“OK”
print ("正常")
GPIO.output(feng,GPIO.LOW)
pass
else: # 如果为低电平,说明MQ-2检测到有害气体,并打印“dangerous”
print ("检测到危险气体 ! ! !")
GPIO.output(feng,GPIO.HIGH)
os.system("sudo mplayer 报警.mp3")
time.sleep(0.1) # 睡眠0.1秒,以后再执行while循环
except KeyboardInterrupt: # 异常处理,当检测按下键盘的Ctrl+C,就会退出这个>脚本
GPIO.cleanup() # 清理运行完成后的残余