Created
August 3, 2016 23:39
-
-
Save brianmhess/074859bb50f944d14ed55041a757dc16 to your computer and use it in GitHub Desktop.
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/python | |
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
#|R|a|s|p|b|e|r|r|y|P|i|-|S|p|y|.|c|o|.|u|k| | |
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
# | |
# ultrasonic_1.py | |
# Measure distance using an ultrasonic module | |
# | |
# Author : Matt Hawkins | |
# Date : 09/01/2013 | |
# Import required Python libraries | |
import time | |
import RPi.GPIO as GPIO | |
# Imports for Google Sheet | |
import json | |
import gspread | |
from oauth2client.service_account import ServiceAccountCredentials | |
import datetime | |
# Use BCM GPIO references | |
# instead of physical pin numbers | |
GPIO.setmode(GPIO.BCM) | |
# Define GPIO to use on Pi | |
GPIO_TRIGGER = 11 | |
GPIO_ECHO = 9 | |
# You need to change the variable "compensation" according to the distance from the edge of the pit to the sensor | |
compensation = -11 | |
print "Ultrasonic Measurement" | |
# Set pins as output and input | |
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger | |
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo | |
# Set trigger to False (Low) | |
GPIO.output(GPIO_TRIGGER, False) | |
# Allow module to settle | |
time.sleep(0.5) | |
# Send 10us pulse to trigger | |
GPIO.output(GPIO_TRIGGER, True) | |
time.sleep(0.00001) | |
GPIO.output(GPIO_TRIGGER, False) | |
start = time.time() | |
while GPIO.input(GPIO_ECHO)==0: | |
start = time.time() | |
while GPIO.input(GPIO_ECHO)==1: | |
stop = time.time() | |
# Calculate pulse length | |
elapsed = stop-start | |
# Distance pulse travelled in that time is time | |
# multiplied by the speed of sound (cm/s) | |
distance = elapsed * 34000 | |
# That was the distance there and back so halve the value | |
distance = distance / 2 | |
distance = distance + compensation | |
print "Distance : %.1f" % distance | |
# Reset GPIO settings | |
GPIO.cleanup() | |
# Upload info to Google Sheet | |
scope = ['https://spreadsheets.google.com/feeds'] | |
credentials = ServiceAccountCredentials.from_json_keyfile_name('creds9.json', scope) | |
gc = gspread.authorize(credentials) | |
wks = gc.open("Readings") | |
wksheet = wks.worksheet("Last") | |
now = datetime.datetime.now() | |
d = wksheet.cell(1,1) | |
d.value = now | |
v = wksheet.cell(1,2) | |
v.value = distance | |
#wksheet.update_cells([d,v]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment