Skip to content

Instantly share code, notes, and snippets.

@banasiak
Last active November 19, 2019 16:22
Show Gist options
  • Save banasiak/c97018fefdbb5a3ff5802951ba52f2b5 to your computer and use it in GitHub Desktop.
Save banasiak/c97018fefdbb5a3ff5802951ba52f2b5 to your computer and use it in GitHub Desktop.
# pip3 install RPI.GPIO
# pip3 install adafruit-circuitpython-ads1x15
import board
import busio
import adafruit_ads1x15.ads1115 as ADS
import RPi.GPIO as GPIO
from adafruit_ads1x15.analog_in import AnalogIn
from board import SCL, SDA
from math import floor
from time import sleep
# moisture levels
SATURATED = 13500
MOIST = 17000
DRY = 18500
ARID = 19500
# pinouts
RED = 9
GREEN = 10
BLUE = 11
SPEAKER = 13
# speaker frequencies
FREQS = [261, 294, 329, 349, 392, 440, 493, 523.25]
# setup output
GPIO.setmode(GPIO.BCM)
GPIO.setup(RED, GPIO.OUT)
GPIO.setup(GREEN, GPIO.OUT)
GPIO.setup(BLUE, GPIO.OUT)
GPIO.setup(SPEAKER, GPIO.OUT)
# setup input
i2c = busio.I2C(board.SCL, board.SDA)
ads = ADS.ADS1115(i2c)
chan0 = AnalogIn(ads, ADS.P0)
chan1 = AnalogIn(ads, ADS.P1)
chan2 = AnalogIn(ads, ADS.P2)
chan3 = AnalogIn(ads, ADS.P3)
def reset():
GPIO.output(RED, 0)
GPIO.output(GREEN, 0)
GPIO.output(BLUE, 0)
GPIO.output(SPEAKER, 0)
def buzz():
p = GPIO.PWM(SPEAKER, 100)
p.start(10)
for x in range(0, 3):
for freq in FREQS:
p.ChangeFrequency(freq)
sleep(0.1)
def red():
GPIO.output(RED, 1)
GPIO.output(GREEN, 0)
GPIO.output(BLUE, 0)
def yellow():
GPIO.output(RED, 1)
GPIO.output(GREEN, 1)
GPIO.output(BLUE, 0)
def green():
GPIO.output(RED, 0)
GPIO.output(GREEN, 1)
GPIO.output(BLUE, 0)
def blue():
GPIO.output(RED, 0)
GPIO.output(GREEN, 0)
GPIO.output(BLUE, 1)
def white():
GPIO.output(RED, 1)
GPIO.output(GREEN, 1)
GPIO.output(BLUE, 1)
def updateLed(level):
if level < SATURATED :
blue()
if level >= SATURATED and level < MOIST :
green()
if level >= MOIST and level < DRY :
yellow()
if level >= DRY and level < ARID :
red()
if level >= ARID :
red()
buzz()
def logToFile(level):
f = open("moisture.csv", "a")
f.write(str(level) + ",")
f.close()
try:
while True:
white()
avg = floor((chan0.value + chan1.value + chan2.value) / 3)
print(chan0.value, chan1.value, chan2.value, "[" + str(avg) + "]")
updateLed(avg)
logToFile(avg)
sleep(60)
except KeyboardInterrupt:
reset()
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment