-
Notifications
You must be signed in to change notification settings - Fork 0
/
waterSensor.py
57 lines (49 loc) · 1.53 KB
/
waterSensor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from time import sleep
import RPi.GPIO as GPIO
import spidev
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 250000
GPIO.setmode(GPIO.BCM)
GPIO.setup(14, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
def poll_sensor(channel):
"""Poll MCP3002 ADC
Args:
channel (int): ADC channel 0 or 1
Returns:
int: 10 bit value relating voltage 0 to 1023
"""
assert 0 <= channel <= 1, 'ADC channel must be 0 or 1.'
# First bit of cbyte is single=1 or diff=0.
# Second bit is channel 0 or 1
if channel:
cbyte = 0b11000000
else:
cbyte = 0b10000000
# Send (Start bit=1, cbyte=sgl/diff & odd/sign & MSBF = 0)
r = spi.xfer2([1, cbyte, 0])
# 10 bit value from returned bytes (bits 13-22):
# XXXXXXXX, XXXX####, ######XX
return ((r[1] & 31) << 6) + (r[2] >> 2)
try:
while True:
channel = 0
channeldata = poll_sensor(channel)
voltage = round(((channeldata * 3300) / 1024), 0)
print('Voltage (mV): {}'.format(voltage))
print('Data : {}\n'.format(channeldata))
if voltage < 180:
# Green
print("No Water Detected")
elif voltage < 330:
# Yellow
print("Water is Being Detected")
else:
# Red
print("1.5 inches of Standing Water Detected")
sleep(2)
finally: # run on exit
spi.close() # clean up
GPIO.cleanup()
print("\n All cleaned up.")