Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
!/usr/bin/env python
# -*- coding: utf-8 -*-
# Import required libraries, including python-requests and hcsr04.py
import sys, time, requests, json, hcsr04
import RPi.GPIO as GPIO
# Set a default interval of 5 seconds. If the script was run with an argument,
# such as "python ultrasonic_harvest.py 2", use that value instead.
interval=3 if len(sys.argv)==1 else int(sys.argv[1])
is_running=False
print "Starting distance measurement! Press Ctrl+C to stop this script."
time.sleep(1)
while True:
print "Entering"
# Track the current time so we can loop at regular intervals
loop_start_time = time.time()
# Read the distance using the read_distance function from hcsr04.py
distance = hcsr04.read_distance()
if is_running:
GPIO.setmode(GPIO.BCM)
GPIO.setup(21,GPIO.OUT)
GPIO.output(21,GPIO.LOW)
if (distance>40 and not is_running):
print "Have to switch on motor"
GPIO.setmode(GPIO.BCM)
GPIO.setup(21,GPIO.OUT)
GPIO.output(21,GPIO.LOW)
is_running=True
if (distance<35 and is_running):
print "Have to switch off motor"
is_running=False
GPIO.cleanup()
if distance:
print "Distance: %.1f cm" % (distance)
# Set the HTTP request header and payload content
headers = {"Content-Type": "application/json"}
payload = {"depth":round(distance * 10) / 10 }
# Send the HTTP request to Harvest
print "Sending data %s to Harvest..." % (json.dumps(payload))
try:
response = requests.post("<AWS EC2 INSTANCE>", data=json.dumps(payload), headers=headers, timeout=5)
except requests.exceptions.ConnectTimeout:
print "Error: Connection timeout. Is the modem connected?"
# Display HTTP request response
if response.status_code == 201:
print "Response 201: Success!"
# sleep until next loop
time_to_wait = loop_start_time + interval - time.time()
if time_to_wait > 0:
time.sleep(time_to_wait)
print "sleeping"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.