def measureMoisture(): pump = SETTINGS["PUMP"] try: average = MCP3008.readMoisture(pi) except: average = 0 if average > 0: average = round(average, 2) wateringTime = round(average / pump["WATERING_FACTOR"], 2) if wateringTime < pump["MIN_WATER"]: print("Watering time, {}, too low. Use minimum watering time: {}". format(wateringTime, pump["MIN_WATER"])) wateringTime = pump["MIN_WATER"] else: wateringTime = pump["WATERING_TIME"] print("Failed to get moisture reading, use default watering time {}". format(wateringTime)) for sensor in SETTINGS["SENSORS"]: utils.blinkLed(pi, sensor["LED"], 20, 0.2) # turn pump on for some seconds print("{}: moisture: {} - turn pump on for {} seconds".format( timestamp, average, wateringTime)) pi.set_mode(pump["LED_GPIO"], pigpio.OUTPUT) pi.set_mode(pump["GPIO"], pigpio.OUTPUT) pi.write(pump["LED_GPIO"], 1) pi.write(pump["GPIO"], 0) time.sleep(wateringTime) pi.write(pump["GPIO"], 1) pi.write(pump["LED_GPIO"], 0)
def get_volumetric_water_content(self): adc = MCP3008.MCP3008() reading = adc.read_channel(self.channel) voltage = adc.convert_to_volts(reading, 4) vwc = ((1 + 16.103 * voltage - (38.725 * voltage)**2 + (60.881 * voltage)**3 - (46.032 * voltage)**4 + (13.536 * voltage)**5) - 1.3) / 6.1 return round(vwc, 4)
def main(): while True: GPIO.setmode(GPIO.BCM) GPIO.setup(DISPLAY_E, GPIO.OUT) GPIO.setup(DISPLAY_RS, GPIO.OUT) GPIO.setup(DISPLAY_DATA4, GPIO.OUT) GPIO.setup(DISPLAY_DATA5, GPIO.OUT) GPIO.setup(DISPLAY_DATA6, GPIO.OUT) GPIO.setup(DISPLAY_DATA7, GPIO.OUT) GPIO.setup(CLK, GPIO.OUT) GPIO.setup(DIN, GPIO.OUT) GPIO.setup(DOUT, GPIO.IN) GPIO.setup(CS, GPIO.OUT) wert = MCP3008.getAnalogData(adCh, CLK, DIN, DOUT, CS)/float(310) ref = 15/float(3.3) wert12v = wert * ref wertg = round(wert12v, 3) display_init() rx_bytes, tx_bytes = get_network_bytes('eth0') rx1_bytes, tx1_bytes = get_network_bytes('wlan0') lcd_byte(DISPLAY_LINE_1, DISPLAY_CMD) lcd_string('Home - '+get_up_stats()[0]) lcd_byte(DISPLAY_LINE_2, DISPLAY_CMD) lcd_string('Free: '+str(get_ram()[1])+'/'+str(get_ram()[0])+'MB') time.sleep(5) lcd_byte(DISPLAY_LINE_1, DISPLAY_CMD) lcd_string('C: '+str(get_temperature())+chr(223)+'C '+str(get_cpu_speed()[:3])+'MHz') lcd_byte(DISPLAY_LINE_2, DISPLAY_CMD) #lcd_string('Ld: '+str(os.getloadavg()[:2])) lcd_string(str(wertg) + " Volt") time.sleep(5) lcd_byte(DISPLAY_LINE_1, DISPLAY_CMD) lcd_string('Eth0 send/rec.') lcd_byte(DISPLAY_LINE_2, DISPLAY_CMD) lcd_string(str(rx_bytes)+'/'+str(tx_bytes)+' MB') time.sleep(5) lcd_byte(DISPLAY_LINE_1, DISPLAY_CMD) lcd_string('WLAN0 send/rec.') lcd_byte(DISPLAY_LINE_2, DISPLAY_CMD) lcd_string(str(rx1_bytes)+'/'+str(tx1_bytes)+' MB') time.sleep(5)
def measureMoisture(): try: average = MCP3008.readMoisture(pi) except: average = 0 if average == 0: utils.turnOffLeds(pi) print("Failed to get moisture reading!\n") return "not read" return average
def loop(): interval = get_data("select frequency from users ")[0][0] UV = sensor_UV.readUV() degrees = sensor_temp_pressure.read_temperature() humidity, temperature = MyPyDHT.sensor_read(MyPyDHT.Sensor.DHT22, 4) pascals = sensor_temp_pressure.read_pressure() hectopascals = pascals / 100 uvIndex = UV / 100.0 windspeed = abs(round(MCP3008.value_to_kmh((mcp.read_channel(0))), 3)) if windspeed < 1: windspeed = 0 save_sensor_value(temperature, humidity, degrees, hectopascals, uvIndex, windspeed) sleep(int(interval) * 60)
def lightintensity(self): l3[2] = MCP3008.analogue(1)
def soilhumidity(self): l3[0] = MCP3008.analogue(0)
def get_lux(self): adc = MCP3008.MCP3008() reading = adc.read_channel(self.channel) voltage = adc.convert_to_volts(reading, 4) lux = 322 * voltage**2 + 719 * voltage + 187 return int(lux)
def Exterior(name): #Thread 3 countDHTout = 0 countWind = 0 wind_count = 0 radius_cm = 9 interval = 5 store_speeds = [] wind_gust = 0 water_const = 0.2794 #Millimiters of water :) rain_count = 0 store_rain = [] mmToIn = .0393 total_rain = 0 def spin(): global wind_count wind_count = wind_count + 1 def rain(): global rain_count rain_count += 1 def reset_rain(): global rain_count rain_count = 0 def rainfall(time_sec): global rain_count water = rain_count * water_const * mmToIn return (water/time_sec) wind_speed_sensor = Button(16) wind_speed_sensor.when_pressed = spin SPI_PORT = 0 SPI_DEVICE = 0 mcp = MCP.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) store_dire =[] rain_gauge_sensor = Button(26) rain_gauge_sensor.when_pressed = rain def reset_wind(): global wind_count wind_count = 0 def calculate_speed(time_sec): global wind_count circumference_cm = (2 * math.pi) * radius_cm rotations = wind_count / 2 dist_cm = circumference_cm * rotations dist_miles = dist_cm / 160934.4 time_hr = time_sec / 3600 speed = dist_miles / time_hr return speed def convert(input): """Converts the value from the MCP value to the actual wind direction\n Returns a Tuple data type""" switch = { 752: ("N",0), 92: ("E",90), 285: ("S",180), 890: ("W",270), 455: ("NE",45), 183: ("SE",135), 611: ("SW",225), 840: ("NW",315), 400: ("NNE",22.5), 83: ("ENE",67.5), 65: ("ESE",112.5), 126: ("SSE",157.5), 243: ("SSW",202.5), 583: ("WSW",247.5), 790: ("WNW",292.5), 660: ("NNW",337.5) } return switch.get(input,-1) #WORK NEEDED HERE FOR TABLE STUFF while True: humid, temp = dht.read_retry(dht.DHT22, 24) if humid is not None and temp is not None: countDHTout = 0 try: logging.info("Thread %s: Logging External Temp/Humid into MariaDB",name) tempin = temp*(9/5)+32 cur.execute("INSERT INTO temp_ext (temp,taken_at) VALUES (?,?)", (tempin,datetime.datetime.now())) cur.execute("INSERT INTO humid_ext (humid,taken_at) VALUES (?,?)", (humid,datetime.datetime.now())) conn.commit() except mariadb.Error as e: print(f"Error: {e}") dataStorageFail("External DHT22") cleanExit() else: print("External DHT Data could not be retrieved") countDHTout = countDHTout + 1 #Counts here bc data was not collected #shoving more stuff in here than usual, PLZ TEST ME :) start_time = time.time() while time.time() - start_time <= interval: reset_wind() time.sleep(interval) final_speed = calculate_speed(interval) store_speeds.append(final_speed) if (wind_gust <= max(store_speeds)): wind_gust = max(store_speeds) windSpeed = statistics.mean(store_speeds) store_speeds.clear() reset_rain() time.sleep(interval) final_rain = rainfall(interval) store_rain.append(final_rain) for x in store_rain: total_rain += x print("rain value:",final_rain,"inches over 5 seconds") print("total rain of day:",total_rain,"inches") store_rain.clear() wind = mcp.read_adc(0) store_dire.append(wind) most = mode.mode(store_dire) windDirection = convert(most) if windDirection == -1: most = most -6 while windDirection == -1: most += 1 windDirection = convert(most) if windSpeed is not None and windDirection is not None: try: logging.info("Thread %s: Logging wind Dire/Speed into MariaDB",name) cur.execute("INSERT INTO wind_direction (letterDire,numberDire,taken_at) VALUES (?,?,?)", (windDirection[0],windDirection[1],datetime.datetime.now())) cur.execute("INSERT INTO wind_speed (speed,taken_at) VALUES (?,?)", (windSpeed,datetime.datetime.now())) cur.execute("INSERT INTO rainfall (rain,taken_at) VALUES (?,?)", (total_rain,datetime.datetime.now())) conn.commit() except mariadb.Error as e: print(f"Error: {e}") dataStorageFail("Anemometer/Wind Vane") else: print("External Wind Data was not collected") countWind = countWind + 1 #counts here bc data was not collected. if countDHTout >= 5: #Send email, but no shut off noDataExt("DHT22") countDHTout = 0 if countWind >= 5: #Send email, but no shut off noDataExt("Wind System") countWind = 0
import time import MCP3008 import RPi.GPIO as GPIO adCh = 0 CLK = 11 DIN = 9 DOUT = 10 CS = 7 TRESHOLD = 3 GPIO.setup(CLK, GPIO.OUT) GPIO.setup(DIN, GPIO.OUT) GPIO.setup(DOUT, GPIO.IN) GPIO.setup(CS, GPIO.OUT) while True: wert = MCP3008.getAnalogData(adCh, CLK, DIN, DOUT, CS)/float(310) #float(310) = 1023/310 = 3.3 ref = 15/float(3.3) wert12v = wert * ref wertg = round(wert12v, 2) print str(wertg)
from flask import Flask, render_template from flask_bootstrap import Bootstrap app = Flask(__name__, static_folder='static', static_url_path='') import json cred = dict() with open('credentials') as f: cred = json.load(f) # # Analog to Digital Converter Code # from MCP3008 import * adcDevice = 0 adcChannel = 0 adc = MCP3008(device=adcDevice) @app.route("/") def index(): return render_template('index.html', homePage=True, page_title="Home Page", light=adc.read(adcChannel)) # # SMS Sending Code # from twilio.rest import TwilioRestClient, exceptions sms = TwilioRestClient(cred['account_sid'], cred['auth_token'])
from time import sleep import mysql.connector as mariadb from ADAFRUIT_BME280_LIBRARY import * import time import SI1145 import MCP3008 import MyPyDHT log = logging.getLogger(__name__) logging.basicConfig(filename='example.log', level=logging.DEBUG) running = True sensor_temp_pressure = BME280(t_mode=BME280_OSAMPLE_8, p_mode=BME280_OSAMPLE_8, h_mode=BME280_OSAMPLE_8) sensor_UV = SI1145.SI1145() mcp = MCP3008.MCP3008() def get_data(sql, params=None): conn = mariadb.connect(database='weatherstation', user='******', password='******') cursor = conn.cursor() records = [] try: log.debug(sql) cursor.execute(sql, params) result = cursor.fetchall() for row in result: records.append(list(row))
def soilhumidity(self): l3[0]=1000-MCP3008.analogue(0) #"invert" signal
def wait_end_move(self, axis, goal, errorMax, senslist): # fonction appelée à la fin des fonctions Move pour assurer # l'execution complète du mouvement/déplacement. ''' [EN TEST ] CONDITION DE DETECTION D'OBSTACLE ''' nb = 1 # plus la liste est petite plus la condition du while lachera rapidement avg = nb * [0] index = 0 movAvg = abs(goal - axis.encoder.pos_estimate) self.ActDone = False # [A tester] (pour lecture capteur en fonction du sens de Translation) Sen = [0, 1, 2, 3, 4] self.SenOn = [0 for i in range(len(Sen))] prev_step = axis.encoder.pos_estimate diff_step = 0 wd = 0 while movAvg >= errorMax: Sen_count = 0 #print("Values vaut : ", MCP3008.readadc(1) ) #print("Encoder : ", axis.encoder.pos_estimate,"Goal/Target : ", goal, "movAvg : ", movAvg ) for i in range(len(Sen)): if senslist[i] == True: if MCP3008.readadc(Sen[i]) > 700: # 600 trop de detection # 1000 test self.OBS = True self.SenOn[i] = 1 #print("Obstacle détécté") #self.detect_obs(axis, goal) #print("Values vaut : ", MCP3008.readadc(Sen[i]) for i in self.SenOn: if i != 0: Sen_count += 1 if Sen_count == 0: self.OBS = False #self.detect_obs(axis, goal) #A revoir pour relancer le robot apres un arret. for i in range(index, nb): avg[i] = abs(goal - axis.encoder.pos_estimate) movAvg = 0 for i in range(0, nb): movAvg += avg[i] / nb diff_step = fabs(axis.encoder.pos_estimate - prev_step) #print(diff_step) if diff_step < 10: wd += 1 if wd > 200: self.ActDone = True return else: wd = 0 prev_step = axis.encoder.pos_estimate ## boucle d'accélération waitendmove #if self.buffer == movAvg: # self.seuil += 1 # print("seuil =",self.seuil) # if self.seuil > 100: # self.seuil = 0 # self.odrv0.axis0.controller.move_to_pos(2000,True) # self.odrv0.axis1.controller.move_to_pos(-2000,True) # time.sleep(0.3) #else: # self.seuil = 0 # #self.buffer = movAvg #print("seuil =", self.seuil) elif Sen_count != 0: return self.ActDone = True
from ADAFRUIT_BME280_LIBRARY import * import time import SI1145 import MCP3008 import MyPyDHT sensor_temp_pressure = BME280(t_mode=BME280_OSAMPLE_8, p_mode=BME280_OSAMPLE_8, h_mode=BME280_OSAMPLE_8) mcp = MCP3008.MCP3008() interval = 0.5 sensor_UV = SI1145.SI1145() while True: humidity, temperature = MyPyDHT.sensor_read(MyPyDHT.Sensor.DHT22, 4) print(MyPyDHT.sensor_read(MyPyDHT.Sensor.DHT22, 4)) vis = sensor_UV.readVisible() IR = sensor_UV.readIR() UV = sensor_UV.readUV() windspeed = abs(round(MCP3008.value_to_kmh((mcp.read_channel(0))), 3)) degrees = sensor_temp_pressure.read_temperature() pascals = sensor_temp_pressure.read_pressure() hectopascals = pascals / 100 uvIndex = UV / 100.0 print('Temp BME280 {0:0.3f} deg C'.format(degrees)) print('Temp DHT22 {0:0.3f} deg C'.format(temperature)) print('Pressure: {0:0.2f} hPa'.format(hectopascals)) print('Humidity: {0:0.2f} %'.format(humidity)) print('UV Index: ' + str(uvIndex)) print('Windspeed: ' + str(windspeed))