def __init__(self, pwm_args, dir_args, enable_args): """ :param pwm_args: e.g. {'gpio_name': 'GPIO7A1', 'mux': 1, 'name': 'PWM1', 'freq': 'xx', 'duty': 'xx'} :param dir_args: e.g. {'name': 'GPIO8A4', 'write': 0} :param enable_args: e.g. {'name': 'GPIO8A7', 'write': 1} """ self._pwm = SmartPwm(pwm_args['name']) self._pwm.set_config(pwm_args['freq'], pwm_args['freq'] / 2) self._dir = GPIO(dir_args['name']) self._dir.set_output() self._dir.write(dir_args['write']) self._enable = GPIO(enable_args['name']) self._enable.set_output() self._enable.write(enable_args['write'])
def getValOut(pinnum): "This prints a passed string into this function" gpio_in = GPIO(pinnum, "out") value = gpio_in.read() gpio_in.close() return value
def elaborate(self, platform: Platform) -> Module: m = Module() imem = Memory(width=32, depth=128, init=self.imem_init) dmem = Memory(width=32, depth=128) m.submodules.cpu = cpu = Misato(xlen=XLEN.RV32, with_RVFI=False) m.submodules.gpio = gpio = GPIO() m.submodules.imem_r = imem_r = imem.read_port() m.submodules.dmem_r = dmem_r = dmem.read_port() m.submodules.dmem_w = dmem_w = dmem.write_port() # Connect cpu and instruction memory m.d.comb += cpu.i_instr.eq(imem_r.data) m.d.comb += imem_r.addr.eq(cpu.o_i_addr[2:]) # Connect cpu write to data bus arbiter with m.If(cpu.o_d_addr == 0x80): m.d.comb += gpio.i_w_en.eq(cpu.o_d_Wr) m.d.comb += dmem_w.en.eq(0) with m.Else(): m.d.comb += gpio.i_w_en.eq(0) m.d.comb += dmem_w.en.eq(cpu.o_d_Wr) # Connect cpu to data bus m.d.comb += gpio.i_data.eq(cpu.o_d_data) m.d.comb += dmem_r.addr.eq(cpu.o_d_addr) m.d.comb += cpu.i_data.eq(dmem_r.data) m.d.comb += dmem_w.addr.eq(cpu.o_d_addr) m.d.comb += dmem_w.data.eq(cpu.o_d_data) m.d.comb += self.o_gpio.eq(gpio.o_data) m.d.comb += self.o_trap.eq(cpu.o_trap) return m
def printme(pinnum, boolval): "This prints a passed string into this function" gpio_out = GPIO(pinnum, "out") value = boolval gpio_out.write(value) gpio_out.close() return str(True)
def clockinit(args): POL = GPIO("480", "out") CLK = GPIO("481", "out") clock = Clock(CLK, POL) statestore = StateStore(clock) statestore.restore() nvramstore = NVRAMStore(clock) if args.require_nvram and not nvramstore.restore(): print "Cannot read clock state from the NVRAM. Exiting..." sys.exit(1) if args.invert: clock.inverse = True if args.uninvert: clock.inverse = False if args.state: clock.setState(args.state) return (clock, statestore, nvramstore)
def __init__(self): self.udp_server = UDPServer() self.gpio = GPIO() self.camera = Camera() self.logger = Logger() self.drives = [0, 0] self.model = None self.auto = False print('Started')
def init_writer(self): """Overwrites the init_writer() method of the BayEOSGatewayClient class.""" # gpio pins ADDR_PINS = [11, 12, 13, 15, 16, 18] # GPIO 17, 18, 27, 22, 23, 24 DATA_PIN = 24 # GPIO 8 EN_PIN = 26 # GPIO 7 self.gpio = GPIO(ADDR_PINS, EN_PIN, DATA_PIN) self.init_sensors() self.addr = 1 # current address
def __init__(self): self.pins = [GPIO(12), GPIO(13), GPIO(182)] self.process = None self.colors_dict = { "off": [0, 0, 0], "red": [1, 0, 0], "green": [0, 1, 0], "blue": [0, 0, 1], "white": [1, 1, 1], "yellow": [1, 1, 0], "cyan": [0, 1, 1], "magenta": [1, 0, 1], "orange": [1, 0.4, 0], "weakred": [0.1, 0, 0] } self.pwm_channels = [0, 1, 2] #red, green, blue
def __init__(self, master=None): #ensure environment is set up and ready to go. self.a = assets() self.g = GPIO() self.l = light_ctrl() Frame.__init__(self, master) self.configure(background='#333', cursor='none') master.bind("<Button-1>", self.init_capture) master.bind("<Button-3>", self.quit_me) self.focus_set() self.pack() self.webcam = True self.capture = False self.createWidgets() self.populateWidgets()
def init_chip(): """Before we can measure temperature and pressure, the chip needs to be initialized and reset. The process is relatively straight forward. First, pull the PS low to activate the SPI protocol Second, issue the reset command Third, pull the PS high Short waits are issued between each action to allow the chip to activate the proper routine :return: a reference to the chip that can be used to actually measure temperature and pressure """ chip = GPIO() chip.pin_mode(CHIP_SELECT, chip.OUTPUT) chip.write_pin(CHIP_SELECT, 1) time.sleep(LONG_WAIT) with spi_mode(chip): chip.send_data([RESET_COMMAND]) time.sleep(LONG_WAIT) return chip
#!/usr/bin/python import signal import time from gpio import GPIO def sig_handler(signum, frame): global loop_exit if signum == signal.SIGINT: loop_exit = 1 signal.signal(signal.SIGINT, sig_handler) loop_exit = 0 LED_base = 898 leds = [GPIO(i, 'out') for i in range(LED_base, LED_base + 4)] idx = 0 while True: cur_led = leds[idx] cur_led.write(1) time.sleep(1) cur_led.write(0) time.sleep(1) idx = (idx + 1) % len(leds) if loop_exit == 1: break
## MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ## ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ## WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ## ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF ## OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ## __version__ = '$Id: __init__.py 120 2017-03-07 08:05:10Z dima $' __all__ = ['GPIO', 'GPIOPin', 'z', 'gpio'] import _gpiolx from _gpiolx import * from gpio import GPIO from pin import GPIOPin __all__ += dir(_gpiolx) def load_global_consts(): for x in dir(_gpiolx): if x.startswith('GPIO_'): s = x[5:] if s not in globals(): globals()[s] = getattr(_gpiolx, x) __all__.append(s) load_global_consts() z = gpio = GPIO()
import time from gpio import GPIO FPGA_RESET_PIN = 12 # RPI_TMS = GPIO12 works as SPI_MISO3 - temporarily reset input for FPGA if __name__ == '__main__': try: reset = GPIO(FPGA_RESET_PIN) print(f'Resetting FPGA using RPi GPIO {FPGA_RESET_PIN}...') reset.set(1) time.sleep(1) reset.set(0) print('Done.') finally: reset.close()
global int_pad_Lock, int_pad_Flag int_pad_Lock.acquire() # wait intPad lock release int_pad_Flag = True int_pad_Lock.release() #如果你想要用SPI驱动此模块,打开下面两行的注释,并通过SPI连接好模块和树莓派 #RASPBERRY_PIN_CS = 27 #Chip selection pin when SPI is selected #acce = DFRobot_H3LIS200DL_SPI(RASPBERRY_PIN_CS) #如果你想要应IIC驱动此模块,打开下面三行的注释,并通过I2C连接好模块和树莓派 I2C_MODE = 0x01 #default use I2C1 ADDRESS_0 = 0x19 #I2C address acce = DFRobot_H3LIS200DL_I2C(I2C_MODE, ADDRESS_0) int_pad = GPIO(INT1, GPIO.IN) # set int_Pad to input int_pad.setInterrupt(GPIO.FALLING, int_pad_callback) #set int_Pad interrupt callback #Chip initialization acce.begin() #Get chip id print("chip id :") print(acce.getID()) ''' set range:Range(g) RANGE_100_G # ±100g RANGE_200_G # ±200g ''' acce.set_range(acce.RANGE_100_G) ''' Set data measurement rate
# Maximum size of assembled image image_size = (2352, 1568) # Size of pictures in the assembled image thumb_size = (1176, 784) # Image basename picture_basename = "{0}/{1}/{2}/pic".format( cfg.get("photo_dir"), cfg.get("event_name"), datetime.now().strftime("%Y-%m-%d")) # GPIO channels gpio_green_button = 6 gpio_green_led = 13 gpio_red_button = 5 gpio_red_led = 19 gpio = GPIO( handle_gpio, [gpio_green_button, gpio_red_button], [gpio_green_led, gpio_red_led], in_alias=['green_but', 'red_but'], out_alias=['green_led', 'red_led'], ) # pygame fps fps = 45 main()
def from_gpio_name(cls, name): _gpio = GPIO(name) _gpio.set_input() return cls(_gpio)
def __init__(self): self.pin = 18 self.mode = 1 #open is 1 close is 0 self.mgpio = GPIO() self.mgpio.setPinMode(pin=self.pin, mode=1) #OUTPUT 1 INPUT 0
# gpio pins ADDR_PINS = [11, 12, 13, 15, 16, 18] # GPIO 17, 18, 27, 22, 23, 24 DATA_PIN = 24 # GPIO 8 EN_PIN = 26 # GPIO 7 # configuration for BayEOSWriter and BayEOSSender PATH = '/tmp/raspberrypi/' NAME = 'RaspberryPi' URL = 'http://bayconf.bayceer.uni-bayreuth.de/gateway/frame/saveFlat' # instantiate objects of BayEOSWriter and BayEOSSender writer = BayEOSWriter(PATH) sender = BayEOSSender(PATH, NAME, URL) # initialize GPIO Board on Raspberry Pi gpio = GPIO(ADDR_PINS, EN_PIN, DATA_PIN) # initialize I2C Bus with sensors try: i2c = I2C() sht21 = SHT21(1) mcp3424 = MCP3424(i2c.get_smbus()) except IOError as err: sys.stderr.write( 'I2C Connection Error: ' + str(err) + '. This must be run as root. Did you use the right device number?') # measurement method def measure(seconds=10): """Measures temperature, humidity and CO2 concentration.
pinOut.setOut(GPIO.HIGH) time.sleep(1) ''' IO1 = 21 IO1Lock = threading.Lock() IO1Flag = False def IO1CallBack(): global IO1Lock, IO1Flag IO1Lock.acquire() # wait key A lock release IO1Flag = True IO1Lock.release() io1 = GPIO(IO1, GPIO.IN) io1.setInterrupt(GPIO.RISING, IO1CallBack) def main(): global IO1Lock, IO1Flag while True: sensor.clear_interrupt() while IO1Flag: IO1Lock.acquire() # wait io1 release IO1Flag = False IO1Lock.release() print("Distance(mm) :%.f" % sensor.get_distance()) time.sleep(0.1) time.sleep(0.1)
def hello_world(): return 'Hello, World!' @app.route('/threshold', methods=['POST']) def posts_threshold(): global distance_threshold distance_threshold = json.loads(list( request.form.to_dict().keys())[0])['stuff'] print('Setting threshold to: ' + str(distance_threshold)) return json.dumps({'success': True}), 200, { 'ContentType': 'application/json' } with GPIO() as gpio_interface: @app.route('/brake', methods=['POST', 'GET']) def brake(): gpio_interface.brake() return "braking" @app.route('/unbrake', methods=['POST', 'GET']) def unbrake(): gpio_interface.unbrake() return "unbraking" @app.route('/points', methods=['POST']) def post_points(): distances = json.loads(list(request.form.to_dict().keys())[0])['stuff']
def create_dbg(pin_id, direction, is_inversion): dbg = GPIODebuger() dbg.mio = GPIO(pin_id, direction, is_inversion) return dbg
def main(): # Show welcome header print("--------------------------") print("Hydroponics Software Start") print() # Initialize classes # Database class initialization print("Database init.. ", end = '\n\n') database = Database() print("\nsuccessful\n") # Initialize the GPIO class print("GPIO init.. ", end = '\n\n') gpio = GPIO() print("\nsuccessful\n") # Turn the circuits on for initialization gpio.transistor5V.off() gpio.transistor3V3.off() # gpio.transistorPH.off() print("All power circuits turned successfully on\n") # Wait for the power supply time.sleep(0.1) # Now, initialize all sensor classes # GPIO expander print("GPIO expander init.. ", end = '') gpioExpander = GPIOExpander() # Set the main tank sensor as default gpioExpander.setSensor(0) print("successful") time.sleep(0.1) # Debug point for distance sensors # time.sleep(100000000) # Light sensor print("Light sensor init.. ", end = '') lightSensor = LightSensor() print("successful") try: # Water sensor print("Water temperature sensor init.. ", end = '') waterTemperatureSensor = WaterTemperatureSensor() print("successful") except (KeyboardInterrupt, SystemExit, OSError): print("Skipping main tank sensor") # Distance sensor print("Distance sensor init.. ", end = '') mainTankLevelSensor = DistanceSensor() print("successful") # PH sensor print("PH sensor init.. ", end = '') pHsensor = PHsensor() print("successful") # DHT22: temperature and humidity print("*Temperature and humidity sensor init.. ", end = '') dht22 = DHT22() print("*successful") # EC sensor print("EC sensor init.. ", end = '') ecsensor = EcSensor() print("successful") # EC level detection repetitions and buffer # Number of sensor reading repetetitions to determine the median ecLevelRepetitions = 7 # Buffer to save the readings ecLevelBuffer = [2] * ecLevelRepetitions # Interval between ec level detections is set later to 1h = 60 * 60 s ecLevelDetectionInterval = 0 ecReadingNumber = 0 # Default EC level ecLevel = 100 # Buffer for main tank's water level sensor: 10 repetitions waterLevelMainTankBuffer = [80] * 10 # Interval between tank level detections tankLevelDetectionInterval = 60 * 60 # Variable for tank level control waitingOnTankLevelDetection = False # Skip the tank sensor if an error is reported skipLevelSensor = False # DHT22 humidty and temperature reading interval = 1 min dhtDetectionInterval = 60 # Initialize nutrient table matrix nutrientTable = [[1, 1, 1, 1.5, 1.5, 1, 0.5, 0.5, 0.5], # FloraGro [1, 1, 1, 1, 1, 1, 1, 1, 1], # FloraMicro [1, 1, 1, 0.5, 0.5, 1, 1.5, 1.5, 1.5], # FloraBloom [0.7, 0.8, 0.8, 0.9, 1, 1, 1, 1, 1]] # EC level # Variables for last sensor readings last_plantHeight_detection = datetime.now() last_tankLevel_detection = datetime.now() last_ecLevel_detection = datetime.now() last_dth22_detection = datetime.now() # List to save plant height sensors' reading plant_heights = [0, 0, 0] # List to save tank levels of each tank tank_levels = [0, 0, 0, 0, 0, 0] # If one manually closes the program with Ctrl+c: def cleanAndExit(): print("Cleaning...") # Closing the database connection database.closeConnection() # Setting all GPIO pins low gpioExpander.cleanClose() print("Bye!") print("\n") # Close the program sys.exit() # Starting system start_up = True # Variable to remember the last system state user input last_systemState = False # Main loop # runs forever except if a user exception (ctrl-c) occurs while True: # Try to run the loop try: # Check userInput data from database userInput = database.getUserInput() # The tables includes: # userInput.time = x[0] # userInput.systemState = x[1] # userInput.pHmeasureState = x[2] # userInput.ledState = x[3] # userInput.autoLedState = x[4] # userInput.sunrise = x[5] # userInput.sunset = x[6] # userInput.autoHeightAdaptionState = x[7] # userInput.plantingDate = x[8] # userInput.ledUp = x[9] # userInput.ledDown = x[10] # Check, if the system is switched on if (userInput.systemState == True): # Switch transistors on if the system state was just enabled if(last_systemState == False): # Turn the 3.3 V and 5 V circuits on gpio.transistor5V.off() gpio.transistor3V3.off() print("\n3.3 V and 5 V circuits turned on") # Wait for the power time.sleep(0.1) # System state has been enabled last_systemState = True # Reading sensors print("\nReading sensors") # Read the light sensor values [full_spectrum, infrared] = lightSensor.getValues() # Calculate the share of visible light visibleLight = full_spectrum - infrared # Print the values print ("Full Spectrum(IR + Visible) : {} lux".format(full_spectrum) ) print ("Infrared Value : {} lux".format(infrared) ) print ("Visible Value : {} lux".format(visibleLight) ) # Read the water temperature sensor try: waterTemperatureSensor.ads.gain = 2 waterTemperature = waterTemperatureSensor.getTemperature() print ("Water temperature: {:.1f} °C".format(waterTemperature) ) except (KeyboardInterrupt, SystemExit, OSError): # Setting water temperature default waterTemperature = 20 print ("Skipping water temperature sensor. Setting water temperature to: {:.1f} °C".format(waterTemperature) ) # Check, if the user switched the LEDs on if (userInput.ledState == True): # Get current time now = datetime.now() # Transform current time into timedelta (of that day) now = timedelta(hours = now.hour, minutes = now.minute) # print(now) # If current time is between sunrise and sunset if( (now > userInput.sunrise) and (now < userInput.sunset) ): print("Current time is between sunrise and sunset") # If LEDs are set by the user to auto adjust if (userInput.autoLedState == True): # Calculate LEDs' target intensity (between 0 and 1) # from the measured visible light value. # Light target intensity collectively: 150 lux ledIntensity = 1 - (visibleLight / 150 / 100) ledIntensity = max(ledIntensity, 0) # If there is more than a 5 % difference between the measured light intensity and the target value if(abs(gpio.leds13.value - ledIntensity) > 0.05): print("True") # Adjust the LEDs' intensity upwards by 0.1 % # as long as there is a 0.5 % deviation. # Thereby a smooth intensity transition is achieved. while ((ledIntensity - gpio.leds13.value) > 0.005): gpio.leds13.value += 0.001 gpio.leds15.value += 0.001 gpio.leds13.value = round(gpio.leds13.value, 3) gpio.leds15.value = round(gpio.leds15.value, 3) time.sleep(0.001) # Read the light sensor values [full_spectrum, infrared] = lightSensor.getValues() # Calculate the share of visible light visibleLight = full_spectrum - infrared ledIntensity = 1 - (visibleLight / 150 / 100) ledIntensity = round(ledIntensity, 3) ledIntensity = max(ledIntensity, 0) # print("LED intensity: {}".format(ledIntensity)) # print("{0}, {1}, {2}".format (gpio.leds13.value, ledIntensity, visibleLight)) # print("gpio.leds13.value: {}".format(gpio.leds13.value)) # Adjust the LEDs' intensity downwards while ((gpio.leds13.value - ledIntensity) > 0.005): # if (gpio.leds13.value > 0 and gpio.leds15.value > 0): gpio.leds13.value -= 0.001 gpio.leds15.value -= 0.001 gpio.leds13.value = round(gpio.leds13.value, 3) gpio.leds15.value = round(gpio.leds15.value, 3) time.sleep(0.001) # Read the light sensor values [full_spectrum, infrared] = lightSensor.getValues() # Calculate the share of visible light visibleLight = full_spectrum - infrared ledIntensity = 1 - (visibleLight / 150 / 100) ledIntensity = round(ledIntensity, 3) ledIntensity = max(ledIntensity, 0) # print("LED intensity: {}".format(ledIntensity)) # print("gpio.leds13.value: {}".format(gpio.leds13.value)) # print("{0}, {1}, {2}".format (gpio.leds13.value, ledIntensity, visibleLight)) print("Turned 1:3 LEDs to {0:.0f} % and 1:5 LEDs to {1:.0f} %".format(gpio.leds13.value*100, gpio.leds15.value*100)) if ((gpio.leds13.value - ledIntensity) == 0.005): gpio.leds13.value = 0 gpio.leds15.value = 0 # print("{0}, {1}, {2}".format (gpio.leds13.value, ledIntensity, visibleLight)) # LEDs are not set to auto adjust else: # Set the LED levels both to 50 % gpio.leds13.value = 0.5 gpio.leds15.value = 0.5 print("Turned 1:3 LEDs to {0} % and 1:5 LEDs to {1} %".format(gpio.leds13.value*100, gpio.leds15.value*100)) # The current time not between sunrise and sunset else: # Turn the LEDs off gpio.leds13.off() gpio.leds15.off() print("LEDs switched off") # The LEDs are not switched on by the user else: # Turn LEDs off gpio.leds13.off() gpio.leds15.off() print("LEDs switched off") # Initialize control variables at system start up if(start_up == True): # Print banner print("\nInitial sensor init") print("-------------------") # Get current time current_time = datetime.now() # print(current_time) # Detect tank levels # Time since last detection time_delta_tankLevel = current_time - last_tankLevel_detection # If the last tank level detection is more than 1 h ago if( (time_delta_tankLevel.seconds > tankLevelDetectionInterval) or (start_up == True) ): # 60*60 # Reset detection interval tankLevelDetectionInterval = 60 * 60 # Loop through the sensors for i in range(1, 7): # Turn sensor with gpio expander on gpioExpander.setSensor(i) time.sleep(0.01) # Initialize the sensor distance_sensor = DistanceSensor() # Measure the distance distance = distance_sensor.getDistance() # Save distance in list tank_levels[i - 1] = distance print ("Tank level sensor {0}: {1} mm".format((i), tank_levels[i - 1]) ) # Save current time last_tankLevel_detection = datetime.now() # Set default sensor to main tank level sensor gpioExpander.setSensor(0) time.sleep(0.01) # Initialize sensor mainTankLevelSensor = DistanceSensor() print("Main tank sensor reinitialized") # Read the main tank water level sensor sensorRepetitions = 0 # 10 Repetitions while(sensorRepetitions < 10): try: # Read the sensor's distance distance = mainTankLevelSensor.getDistance() # Calculate the level from the sensor height waterLevelMainTankReading = 247 - distance # Print the reading # print ("Distance of main tank level sensor: {0} mm".format(distance) ) print ("Water level main tank: {0} mm".format(waterLevelMainTankReading) ) # Did not skip skipLevelSensor = False # Catch an error message and display the message except (KeyboardInterrupt, SystemExit, OSError): print("Skipping main tank level sensor") print("X"*90) # Skip skipLevelSensor = True # If the reading was successful if (skipLevelSensor == False): # Set first value of buffer waterLevelMainTankBuffer[0] = waterLevelMainTankReading # Rotate buffer waterLevelMainTankBuffer = waterLevelMainTankBuffer[-1:] + waterLevelMainTankBuffer[:-1] # Adjust sensor reading number sensorRepetitions += 1 # print(waterLevelMainTankBuffer) # Calculate mean water level # waterLevelMainTank = sum(waterLevelMainTankBuffer) / len(waterLevelMainTankBuffer) # Calculate median of buffer waterLevelMainTank = median(waterLevelMainTankBuffer) print("Current water tank level median: {:.0f}".format(waterLevelMainTank)) # Tank level detection succesfull waitingOnTankLevelDetection = False # Update database database.updateSensors(visibleLight, waterTemperature, waterLevelMainTank) # Get current time now = datetime.now() # Transform current time into timedelta (of that day) now = timedelta(hours = now.hour, minutes = now.minute) # Check, if the main tank's water level is too low # and there have been at least 10 water level main tank sensor readings # and the current time is within the sunrise sunset hours if( (waterLevelMainTank < 60) and (now > userInput.sunrise) and (now < userInput.sunset) and (waitingOnTankLevelDetection == False)): # Turn water refill pump on for 3 s # gpio.pumpWaterSupply.value = 1 # 0.4 print("Water refill pump turned on") time.sleep(3) # Turn pump off gpio.pumpWaterSupply.off() # Refresh the main tank's level in 60 seconds tankLevelDetectionInterval = 60 # Wait for the main tank level reading before the pump is switched on again waitingOnTankLevelDetection = True # Turn the circulation pump on to 30 % (most silent) gpio.pumpCirculation.value = 0.0 # 0.3 print("Turning the circulation pump on to {} %".format(gpio.pumpCirculation.value*100)) # DHT22 # Air temperature and humidity reading # current_time = datetime.now() # Time since last reading time_delta_dht22 = current_time - last_dth22_detection print("time_delta_dht22.seconds: {}".format(time_delta_dht22.seconds)) # On start up or if the detection interval is over if( (start_up == True) or (time_delta_dht22.seconds > dhtDetectionInterval ) ): # Read sensor [humidity, temperature] = dht22.getValues() # Print sensor values print("D"*80) print ("Humidity: {:.1f} %".format(humidity) ) print ("Temperature: {:.1f} °C".format(temperature) ) # Write to database database.updateDHT22(temperature, humidity) # Save time last_dth22_detection = datetime.now() # Calculate time since last plant height detection time_delta_plantHeight = current_time - last_plantHeight_detection # Detect plant height if the detection interval is up # The time since the last detection was already calculated above if( (start_up == True) or (time_delta_plantHeight.seconds > 60 * 60) ): # 60*60 # Loop through the sensors for i in range(7, 10): # Enable sensor gpioExpander.setSensor(i) time.sleep(0.01) # Initialize sensor distance_sensor = DistanceSensor() # Measure distance = distance_sensor.getDistance() # Save plant_heights[i - 7] = distance # Print value print ("Distance plant height sensor {0}: {1} mm".format((i-6), plant_heights[i - 7]) ) # Save time last_plantHeight_detection = datetime.now() # Set main tank level sensor gpioExpander.setSensor(0) time.sleep(0.01) # Reinitialize default sensor mainTankLevelSensor = DistanceSensor() print("Main tank sensor reinitialized") # EC level # Get current time current_time = datetime.now() # Time since last detection time_delta_ecLevel = current_time - last_ecLevel_detection print("time_delta_ecLevel.seconds: {}".format(time_delta_ecLevel.seconds)) ################################# # EC level detection not in a row # # Waiting time between individual measurements # timeBetweenECMeasurements = 15 # 30 # # Time of next reading # nextECReading = timeBetweenECMeasurements * ecReadingNumber + 6 + ecLevelDetectionInterval # print("nextECReading: {}".format(nextECReading)) # # Keep water temperature constant during measurement # if (ecReadingNumber == 0): # ecWaterTemperature = waterTemperature # # If one reading sequence has not been completed and the interval between readings is up: # if((ecReadingNumber < ecLevelRepetitions) and (time_delta_ecLevel.seconds > nextECReading)): # # Try to make a measurement # try: # # Print reading number # print(str(ecReadingNumber + 1)*90) # print("\n\nEC Reading No. {}".format(ecReadingNumber + 1)) # # Wait for voltage stabilization # time.sleep(0.2) # # Read the sensor # ecLevelReading = ecsensor.getEC(ecWaterTemperature) # # Set first value of buffer # ecLevelBuffer[0] = ecLevelReading # # Rotate buffer # ecLevelBuffer = ecLevelBuffer[-1:] + ecLevelBuffer[:-1] # print("ecLevelBuffer: {}".format(ecLevelBuffer)) # # Reading number up # ecReadingNumber += 1 # # Catch an error message and display the message # except (KeyboardInterrupt, SystemExit): # cleanAndExit() # # If all readings of one detection cycle were concluded # if(ecReadingNumber >= ecLevelRepetitions): # # print(ecLevelBuffer) # # print(ecLevelBuffer[1:ecLevelRepetitions]) # # print((len(ecLevelBuffer) - 1)) # # Calculate mean water level # # ecLevel = sum(ecLevelBuffer[1:ecLevelRepetitions]) / (len(ecLevelBuffer) - 1) # # ecLevel = sum(ecLevelBuffer) / len(ecLevelBuffer) # # Calculate median # ecLevel = median(ecLevelBuffer) # # Update database # database.updateEC(ecLevel) # # Set detection interval # ecLevelDetectionInterval = 60 * 60 # # Restart counting # ecReadingNumber = 0 # # Save time # last_ecLevel_detection = datetime.now() # print("===================================================================================") # print("Current EC level median: {:.3f}".format(ecLevel)) ############################# # EC level detection in a row # If the interval is up or start up true if((time_delta_ecLevel.seconds > ecLevelDetectionInterval) or (start_up == True)): # 60*60 # Reset detection interval ecLevelDetectionInterval = 60*60 # Let the voltage settle time.sleep(3) # Set reading number readingNumber = 0 # Drop the first three readings while(readingNumber < ecLevelRepetitions + 3): # Try to run the loop try: print("\n\nEC Reading No. {}".format(readingNumber + 1)) # Read sensor ecLevelReading = ecsensor.getEC(waterTemperature) # Set first value of buffer ecLevelBuffer[0] = ecLevelReading # Rotate buffer ecLevelBuffer = ecLevelBuffer[-1:] + ecLevelBuffer[:-1] # Adjust reading number readingNumber += 1 # Catch an error message and display the message except (KeyboardInterrupt, SystemExit): cleanAndExit() # Sleep for the ions to settle T = 1 time.sleep(T) # Print buffer print(ecLevelBuffer) # Calculate mean water level # ecLevel = sum(ecLevelBuffer) / len(ecLevelBuffer) # Calculate median ecLevel = median(ecLevelBuffer) print("Current EC level median: {:.3f}".format(ecLevel)) # Update database database.updateEC(ecLevel) # Save time last_ecLevel_detection = datetime.now() ecLevel = 20 # Check, if pH sensing is switched on if(userInput.pHmeasureState == True): # Turn pH sensor circuit on gpio.transistorPH.off() time.sleep(0.1) # Read the pH sensor pH = pHsensor.getPH() print ("PH: {:.3f}".format(pH)) # Update database database.updatePH(pH) # PH sensing is switched off else: # Turn pH sensor circuit off gpio.transistorPH.on() # Auto Adjust LED height # Get current time now = datetime.now() # Transform current time into timedelta (of that day) now = timedelta(hours = now.hour, minutes = now.minute) # If the current time is within the active hours # and the user turned auto adaption on if ((now > userInput.sunrise) and (now < userInput.sunset) and (userInput.autoHeightAdaptionState == True)): # As long as one sensor senses a plant while ((plant_heights[0] < 500) or (plant_heights[1] < 500) or (plant_heights[2] < 500)): # Adjust LED height # Enable actuator gpio.ledUp.value = 0.15 print("Moving the LEDs up with {} % power".format(gpio.ledUp.value*100)) time.sleep(0.1) # Check sensors again for i in range(7, 10): # Set sensor gpioExpander.setSensor(i) time.sleep(0.1) # Initialize sensor distance_sensor = DistanceSensor() # Read sensor distance = distance_sensor.getDistance() # Save value plant_heights[i - 7] = distance print ("Distance plant height sensor {0}: {1} mm".format((i-6), plant_heights[i - 7]) ) # Disable actuator gpio.ledUp.off() print("LED upward movement stopped") # Manual LED height adjustment led_movement_was_on = False # Check, if the LED Up button is being pressed while (userInput.ledUp == True): # Move LEDs up with full speed gpio.ledUp.value = 1 print("Moving the LEDs up with {} % power".format(gpio.ledUp.value*100)) time.sleep(0.5) # Check userInput data again userInput = database.getUserInput() # Button not pressed else: # Disable motor gpio.ledUp.off() print("LED upward movement stopped") # Check, if the LED Down button is being pressed while (userInput.ledDown == True): gpio.ledDown.value = 1 print("Moving the LEDs down with {} % power".format(gpio.ledDown.value*100)) time.sleep(0.5) # Check userInput data userInput = database.getUserInput() # Button not pressed else: gpio.ledDown.off() print("LED downward movement stopped") # Get current time as date object now = datetime.now().date() # Calculate current week number elapsed = now - userInput.plantingDate elapsed_weeks = int(elapsed.days / 7) print("Elapsed days since planting: {}".format(elapsed.days)) print("Elapsed weeks since planting: {}".format(elapsed_weeks)) # Get the current time now = datetime.now() # Current week number within nutrient table? if (elapsed_weeks < 9): print("EC level desired: {}".format(nutrientTable[3][elapsed_weeks])) # Transform current time into timedelta (of that day) now = timedelta(hours = now.hour, minutes = now.minute) # Is mean EC level below nutrient table entry and within sunrise/ sunset and the EC level has been updated at least 10 times? if( (ecLevel < nutrientTable[3][elapsed_weeks]) and (now > userInput.sunrise) and (now < userInput.sunset) and False): # Adjust nutrient level # Turn each pump on for a short moment according to the nutrient table gpio.pumpFloraGro.value = 0.2 time.sleep(nutrientTable[1][elapsed_weeks]) gpio.pumpFloraGro.off() gpio.pumpFloraMicro.value = 0.2 time.sleep(nutrientTable[2][elapsed_weeks]) gpio.pumpFloraMicro.off() gpio.pumpFloraBloom.value = 0.2 time.sleep(nutrientTable[3][elapsed_weeks]) gpio.pumpFloraBloom.off() print("Nutrients refilled") # Next EC level detection in 10 min ecLevelDetectionInterval = 60*5 # Time outside nutrient table else: # Is mean EC level below last nutrient table entry and within sunrise/ sunset and the EC level has been updated at least 10 times? if( (ecLevel < nutrientTable[3][8]) and (now > userInput.sunrise) and (now < userInput.sunset) and False): # Adjust nutrient level # Turn each pump on for a short moment according to the nutrient table gpio.pumpFloraGro.value = 0.2 time.sleep(nutrientTable[1][8]) gpio.pumpFloraGro.off() gpio.pumpFloraMicro.value = 0.2 time.sleep(nutrientTable[2][8]) gpio.pumpFloraMicro.off() gpio.pumpFloraBloom.value = 0.2 time.sleep(nutrientTable[3][8]) gpio.pumpFloraBloom.off() print("Nutrients refilled") # Next EC level detection in 10 min ecLevelDetectionInterval = 60*5 # Start up over start_up = False # System is switched off else: # Turn pH sensor circuit off gpio.transistorPH.on() # Turn the LEDs off gpio.leds13.off() gpio.leds15.off() print("LEDs switched off") # Turn the circulation pump off gpio.pumpCirculation.off() print("Turning the circulation pump off") # Turn the circuits off gpio.transistor5V.on() gpio.transistor3V3.on() print("3.3 V and 5 V power circuits turned off") # Safe system state last_systemState = False # Wait 0.1 for new user input time.sleep(0.1) print("\n") # Catch an error message and display the message except (KeyboardInterrupt, SystemExit): cleanAndExit()
import uasyncio as asyncio from uasyncio.websocket.server import WSReader, WSWriter import uos as os import machine import socket import utime from gpio import GPIO io = GPIO() g_mem_free = 0 async def dns_server(): def getPacketAnswerA(packet, ipV4Bytes) : try : queryEndPos = 12 while True : domPartLen = packet[queryEndPos] if (domPartLen == 0) : break queryEndPos += 1 + domPartLen queryEndPos += 5 return b''.join( [ packet[:2], # Query identifier b'\x85\x80', # Flags and codes packet[4:6], # Query question count b'\x00\x01', # Answer record count b'\x00\x00', # Authority record count b'\x00\x00', # Additional record count