strawberry-pi-greenhouse/main.py

90 lines
2.4 KiB
Python
Raw Normal View History

import time
import os
from datetime import datetime
import signal
import sys
try:
import paho.mqtt.client as mqtt
import gpiozero
import RPi.GPIO as GPIO
import board
import busio
import adafruit_bmp280
except ImportError:
print('Some modules are missing. Try to install them with "pip3 install -r requirements.txt"')
print(ImportError)
exit()
sys.path.append('./SDL_Adafruit_ADS1x15')
import SDL_Adafruit_ADS1x15
def debug_print(message: str):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print('[DEBUG]['+current_time+'] '+message)
def error_print(message: str):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print('[ERROR]['+current_time+'] '+message)
#relay
def relay_controller(pin: int, status: str):
if status == "ON":
relay = gpiozero.OutputDevice(pin, active_high=False, initial_value=False)
relay.on()
elif status == "OFF":
relay = gpiozero.OutputDevice(pin, active_high=False, initial_value=False)
relay.off()
else:
error_print("Unknown status for relay ("+status+")")
#ultrasonic
def get_water_level():
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO_TRIGGER = 18
GPIO_ECHO = 24
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
startTime = time.time()
StopTime = time.time()
while GPIO.input(GPIO_ECHO) == 0:
startTime = time.time()
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
TimeElapsed = StopTime - startTime
distance = (TimeElapsed * 34300) / 2
return int(distance)
#moisture
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
def get_moisture():
ADS1115 = 0x01
gain = 6144
sps = 250
adc = SDL_Adafruit_ADS1x15.ADS1x15(ic=ADS1115)
2022-07-10 16:58:12 +00:00
return adc.readADCSingleEnded(0, gain, sps) / 1000 + adc.readADCSingleEnded(1, gain, sps) / 1000 + adc.readADCSingleEnded(2, gain, sps) / 1000 + adc.readADCSingleEnded(3, gain, sps) / 1000
#temperature
def get_temperature():
i2c = busio.I2C(board.SCL, board.SDA)
bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c, address=0x76)
return int(bmp280.temperature)
# print(get_moisture())
# print(get_water_level())
print(get_temperature())