-
-
Save ma2shita/e7f5d72c7592e8eb09adf92dcdf4310c to your computer and use it in GitHub Desktop.
Storebot for Raspberry Pi with Amazon Polly (Let's try IoT Prototyping / MFT2020)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
MIN_DISTANCE_CM = 20 | |
MAX_DISTANCE_CM = 100 | |
STAY_COUNT = 5 | |
import time | |
# 距離を読む関数 | |
def read_distance(): | |
# 必要なライブラリのインポート・設定 | |
import RPi.GPIO as GPIO | |
# 使用するピンの設定 | |
GPIO.setmode(GPIO.BOARD) | |
TRIG = 11 # ボード上の11番ピン(GPIO17) | |
ECHO = 13 # ボード上の13番ピン(GPIO27) | |
# ピンのモードをそれぞれ出力用と入力用に設定 | |
GPIO.setup(TRIG,GPIO.OUT) | |
GPIO.setup(ECHO,GPIO.IN) | |
GPIO.output(TRIG, GPIO.LOW) | |
# TRIG に短いパルスを送る | |
GPIO.output(TRIG, GPIO.HIGH) | |
time.sleep(0.00001) | |
GPIO.output(TRIG, GPIO.LOW) | |
# ECHO ピンがHIGHになるのを待つ | |
signaloff = time.time() | |
while GPIO.input(ECHO) == GPIO.LOW: | |
signaloff = time.time() | |
# ECHO ピンがLOWになるのを待つ | |
signalon = signaloff | |
while time.time() < signaloff + 0.1: | |
if GPIO.input(ECHO) == GPIO.LOW: | |
signalon = time.time() | |
break | |
# GPIO を初期化しておく | |
GPIO.cleanup() | |
# 時刻の差から、物体までの往復の時間を求め、距離を計算する | |
timepassed = signalon - signaloff | |
distance = timepassed * 17000 | |
# 500cm 以上の場合はノイズと判断する | |
if distance <= 500: | |
return distance | |
else: | |
return None | |
import urllib2 | |
import json | |
import base64 | |
from subprocess import Popen, PIPE | |
def main(): | |
cnt = 0 | |
while True: | |
distance = read_distance() | |
if distance: | |
print "距離: %.1f cm" % distance | |
if MIN_DISTANCE_CM <= distance and distance <= MAX_DISTANCE_CM: | |
cnt += 1 | |
else: | |
cnt = 0 | |
if cnt > STAY_COUNT - 1: | |
cnt = 0 | |
headers = {'Content-Type': 'application/json'} | |
payload = json.dumps({}) | |
response = urllib2.urlopen(urllib2.Request('http://uni.soracom.io', payload, headers)) | |
print(response.getcode()) | |
body = json.loads(response.read()) | |
mp3data = base64.b64decode(body['data']) | |
cp = Popen(['mpg123', '-'], stdin=PIPE) | |
cp.communicate(input=mp3data) | |
print(cnt) | |
time.sleep(1) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment