Skip to content

Commit 1f57e58

Browse files
committed
Initial commit
1 parent d9dadbc commit 1f57e58

File tree

8 files changed

+206
-0
lines changed

8 files changed

+206
-0
lines changed

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,14 @@
11
# pyultrasonic
22

33
Retrieve distances using a Raspberry Pi with ultrasonic sensor HC-SR04
4+
5+
# WIP WIP WIP
6+
7+
# TODO
8+
9+
* multiple output types
10+
* text
11+
* influxdb
12+
* json
13+
* Error handling
14+
* No GPIO jumpers connected detection

pyultrasonic/__main__.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from pyultrasonic import UltrasonicSensor
2+
from pyultrasonic.output import output_influx
3+
4+
VERSION = "0.1"
5+
6+
def main():
7+
"""Entrypoint function."""
8+
parser = argparse.ArgumentParser()
9+
parser.add_argument('-t', '--trigger',
10+
help='Your GPIO Trigger pin')
11+
parser.add_argument('-e', '--echo',
12+
help='Your GPIO Echo pin')
13+
parser.add_argument('-d', '--depth',
14+
help='Pit depth')
15+
parser.add_argument('-c', '--compensation',
16+
help='Compensation')
17+
parser.add_argument('-j', '--json', action='store_true',
18+
default=False, help='Json output')
19+
parser.add_argument('-i', '--influxdb', action='store_true',
20+
default=False, help='InfluxDb output')
21+
22+
args = parser.parse_args()
23+
24+
if args.version:
25+
print(VERSION)
26+
return 0
27+
28+
if not args.trigger or not args.echo:
29+
parser.print_usage()
30+
print("pyultrasonic: error: the following arguments are required: "
31+
"-t/--trigger, -p/--echo, -d/--depth")
32+
return 3
33+
34+
sensor = UltrasonicSensor(args.trigger, args.echo, args.depth, args.compensation)
35+
loop = asyncio.get_event_loop()
36+
37+
sensor.retrieveDistance()
38+
39+
if args.influxdb:
40+
output_influx(sensor.get_data())
41+
elif args.json:
42+
output_json(client.get_data())
43+
return 0
44+
45+
46+
if __name__ == '__main__':
47+
sys.exit(main())
48+
49+

pyultrasonic/output.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""PyUltrasonic Output Module."""
2+
3+
def output_influx(data):
4+
"""Print data using influxDB format."""
5+
6+
# Pop yesterdays data
7+
retrievetime_data = data['retrievetime']
8+
del data['retrievetime']
9+
10+
# Print general data
11+
# out = "pyultrasonic,contract=" + contract + " "
12+
out = "pyultrasonic,source=\"HC-SR04sensor\" "
13+
14+
for index, key in enumerate(data):
15+
if index != 0:
16+
out = out + ","
17+
out += key + "=" + str(data[contract][key])
18+
19+
out += " " + self.ts_utc_from_datestr(last_ts_str) + '000000000'
20+
print(out)
21+
22+
@staticmethod
23+
def ts_utc_from_datestr(utc_date_str):
24+
utc = datetime.strptime(utc_date_str, '%Y-%m-%d %H:%M:%S')
25+
26+
pst = pytz.timezone('Etc/UTC')
27+
utc = pst.localize(utc)
28+
29+
# return calendar.timegm(dt.utctimetuple())
30+
return utc.timestamp()

pyultrasonic/sensor.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""pyUltrasonic Sensor Module."""
2+
import RPi.GPIO as GPIO
3+
import time
4+
5+
class UltrasonicSensor(object):
6+
7+
def __init__(self, gpio_trigger, gpio_echo, depth, compensation=0):
8+
"""Initialize the sensor object."""
9+
self.distance = None
10+
self.startTime = None
11+
self.distance = None
12+
self.gpio_trigger = gpio_trigger
13+
self.gpio_echo = gpio_echo
14+
self.depth = depth
15+
self.compensation = compensation
16+
17+
#GPIO Mode (BOARD / BCM)
18+
GPIO.setmode(GPIO.BCM)
19+
20+
#set GPIO direction (IN / OUT)
21+
GPIO.setup(self.gpio_trigger, GPIO.OUT)
22+
GPIO.setup(self.gpio_echo, GPIO.IN)
23+
24+
def __del__(self):
25+
"""clean up all the ports you’ve used."""
26+
GPIO.cleanup()
27+
28+
def retrieveDistance(self):
29+
"""Retrieve the distance."""
30+
# set Trigger to HIGH
31+
GPIO.output(self.gpio_trigger, True)
32+
33+
# set Trigger after 0.01ms to LOW
34+
time.sleep(0.00001)
35+
GPIO.output(self.gpio_trigger, False)
36+
37+
self.startTime = time.time()
38+
startElapsed = time.perf_counter()
39+
stopElapsed = time.perf_counter()
40+
41+
# save StartTime
42+
while GPIO.input(self.gpio_echo) == 0 and (time.perf_counter() - startElapsed) < 30:
43+
startElapsed = time.perf_counter()
44+
if (time.perf_counter() - startElapsed) >= 30:
45+
pass
46+
#TODO: Raise an Error
47+
48+
# save time of arrival
49+
while GPIO.input(self.gpio_echo) == 1 and (time.perf_counter() - stopElapsed) < 30:
50+
stopElapsed = time.perf_counter()
51+
if (time.perf_counter() - stopElapsed) >= 30:
52+
pass
53+
#TODO: Raise an Error
54+
55+
# time difference between start and arrival
56+
disdistance = ((stopElapsed - startElapsed) * 34300) / 2 + self.compensation
57+
self.distance = round(disdistance, 0)
58+
59+
def getDistance(self):
60+
"""Return the distance value."""
61+
if self.distance is None:
62+
self.retrieveDistance()
63+
64+
return self.distance
65+
66+
def waterLevel(self):
67+
"""Return the water level value."""
68+
if self.distance is None:
69+
self.retrieveDistance()
70+
71+
return self.depth - self.distance
72+
73+
def waterLevelPercent(self):
74+
"""Return the water level in percentage."""
75+
if self.distance is None:
76+
self.retrieveDistance()
77+
78+
return round((self.depth - self.distance) / self.depth * 100 ,0)

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
RPi.GPIO==0.6.1

setup.cfg

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[metadata]
2+
description-file = README.md

setup.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import sys
2+
3+
from setuptools import setup
4+
from pyultrasonic.__main__ import VERSION
5+
6+
if sys.version_info < (3,4):
7+
sys.exit('Sorry, Python < 3.4 is not supported')
8+
9+
install_requires = list(val.strip() for val in open('requirements.txt'))
10+
tests_require = list(val.strip() for val in open('test_requirements.txt'))
11+
12+
setup(name='pyultrasonic',
13+
version=VERSION,
14+
description='RRetrieve distances using a Raspberry Pi with ultrasonic sensor HC-SR04',
15+
author='Richard Dubois',
16+
author_email='[email protected]',
17+
url='https://github.com/richie256/pyultrasonic',
18+
package_data={'': ['LICENSE']},
19+
include_package_data=True,
20+
packages=['pyultrasonic'],
21+
entry_points={
22+
'console_scripts': [
23+
'pyultrasonic = pyultrasonic.__main__:main'
24+
]
25+
},
26+
license='Apache 2.0',
27+
install_requires=install_requires,
28+
tests_require=tests_require,
29+
classifiers=[
30+
'Programming Language :: Python :: 3.4',
31+
'Programming Language :: Python :: 3.5',
32+
'Programming Language :: Python :: 3.6',
33+
]
34+
35+
)

test_requirements.txt

Whitespace-only changes.

0 commit comments

Comments
 (0)