課程設計程式碼
阿新 • • 發佈:2018-12-31
語言控制功能:
#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() # 清理執行完成後的殘餘