def flow(t, relayPin, valvePin): # Duty cycle of signal dc = 100.0 # Frequency of signal freq = 10000 onTime = dc / freq offTime = 0.0 cycleNumRelay = int(t * 1.2 * freq / 100) # Gives more time for pump cycleNumValve = int(t * freq / 100) # Scale because DC not 0<x<1 pR = gpiozero.PWMOutputDevice(relayPin, active_high=True, frequency=(freq * 100)) pV = gpiozero.PWMOutputDevice(valvePin, active_high=True, frequency=(freq * 100)) try: pR.blink(on_time=onTime, off_time=offTime, n=cycleNumRelay, background=True) pV.blink(on_time=onTime, off_time=offTime, n=cycleNumValve, background=False) except KeyboardInterrupt: pass pR.off() pV.off()
def __init__(self, spi, cs_pin, pwm_pin) -> None: ''' `UI_LEDs(spi, cs, pwm)` initializes the UI LEDs with the given SPI core `spi`, Chip Select pin number `cs`, and PWM pin number `pwm`, and finally turns all the LEDs off. Args: `spi` (gpiozero.SPIDevice): the SPI device to use `cs_pin` (int): the GPIO pin number to use for Chip Select `pwm_pin`(int): the GPIO pin number to use for the PWM brightness control Note: prefer pins 12, 13, 18, or 19 for the PWM pin, these are hardware PWM pins, other pins will use software PWM. Side effects: turns all the LEDs off Raises: PinInvalidPin if either the `cs` or `pwm` pins are not valid pin numbers. ''' self.spi = spi self.chip_sel = gpiozero.DigitalOutputDevice(cs_pin, active_high=False) self.pwm = gpiozero.PWMOutputDevice( pwm_pin, active_high=False, initial_value=0.0) self.all_off() self._cached_write = 0
def __init__( self, contactSwitch=[2, 3], ledVolume=4, potVolume=17, motorDirection=[18, 23, 24], muteSwitch=25, ): self.contactSwitch = [ gpiozero.Button(contactSwitch[0], bounce_time=self.BOUNCE_TIME), gpiozero.Button(contactSwitch[1], bounce_time=self.BOUNCE_TIME) ] self.ledVolume = gpiozero.PWMLED(ledVolume) self.potVolume = gpiozero.MCP3008(channel=potVolume) # TODO program motorDirection[2] for PWM speed control # see L298N motor driver documentation for details self.motorDirection = [ gpiozero.Motor(motorDirection[0], motorDirection[1], pwm=False), gpiozero.PWMOutputDevice(motorDirection[2]) ] # This is a toggle switch not a button self.muteSwitch = gpiozero.Button(muteSwitch, bounce_time=self.BOUNCE_TIME) self.strikeState = 'idle'
def __init__(self, parent, text, pin, *args, **kwargs): ttk.Button.__init__(self, text=text, *args, **kwargs) self.text = text self.pin = pin #self.function = function self.func = gpiozero.PWMOutputDevice(pin=pin, active_high=True, initial_value=0, frequency=100)
def _setup_hardware(self): """ Create instances of all peripherals needed. """ self._main_LED = gpiozero.RGBLED(12,13,19,pwm=True) self._piezo = gpiozero.PWMOutputDevice(18,frequency=400) self._button = gpiozero.Button(4,hold_time=3,hold_repeat=False,pull_up=True) self._button.when_pressed = self._on_button_press self._button.when_released = self._on_button_release self._button.when_held = self._on_button_hold
def __init__(self, forward=None, backward=None, enable=None, pin_factory=None): if not all(p is not None for p in [forward, backward, enable]): raise gz.GPIOPinMissing( 'forward and backward pins must be provided.' ) super(PWM_Motor, self).__init__( forward_device=gz.OutputDevice(forward, pin_factory=pin_factory), backward_device=gz.OutputDevice(backward, pin_factory=pin_factory), enable_device=gz.PWMOutputDevice(enable, pin_factory=pin_factory), _order=('forward_device', 'backward_device', 'enable_device'), pin_factory=pin_factory )
def _setup_hardware(self): """ Create instances of all peripherals needed. """ # TODO: Ensure the following peripherals are correctly connected self._main_LED = gpiozero.RGBLED(12,13,19,pwm=True) self._piezo = gpiozero.PWMOutputDevice(18,frequency=400) self._sensor_adc = gpiozero.MCP3002(port=0,device=0,channel=0) self._button = gpiozero.Button(4,hold_time=3,hold_repeat=False,pull_up=True) self._button.when_pressed = self._on_button_press self._button.when_released = self._on_button_release self._button.when_held = self._on_button_hold
def LAMove(move, factory): # Purpose: Move LA to the move location # Wait until movement has been carried out # Can only move LA away from home # Assume: None # End: LA moved to input location # Input: move = [x, y, z, a, b] # factory (IP address) # Output: True = moved to location # False = couldn't move to location # Print y destination y = move[1] print('LA moving to ' + str(y)) # Set Pi pin for direction DIR = gpiozero.DigitalOutputDevice(20, active_high=False, pin_factory=factory) DIR.off() # Sets direction to away from home # Conversion constants d2p = 400 / 5 # 400 pulses per rev / 5mm lead p2t = 1 / 1600 # frequency is 1600Hz # Calculate time to sleep and print it # If time calculated is too great return False t = abs(y) * d2p * p2t print('Time: ' + str(t)) if t > 16: return False # Start step pulse and sleep for calculated time STEP = gpiozero.PWMOutputDevice(21, active_high=False, initial_value=0.5, frequency=1600, pin_factory=factory) sleep(t) # End step pulse STEP.off() # Print destination reached print('LA moved to ' + str(y)) return True
def __init__(self,jp,logger): # Initlize sensor interface, datalogger, & controller settings self.jp = jp self.logger = logger self.settings = ControlSettings() # Sets up the GPIO interface for valve control. self.inlet = gpiozero.DigitalOutputDevice(17, active_high=True, initial_value=True) #starts open self.inspir = gpiozero.PWMOutputDevice(22, active_high=True, initial_value=0, frequency = 20) #starts closed self.expir = gpiozero.DigitalOutputDevice(27, active_high=False, initial_value=True) #Starts open # Initialize control state (assume I.C. is inhale) self._state = 0 self.__inhale() # Keep's track of how long each state lasts self.state_time = time.time()
def __init__(self, pwmMA, pwmMB, pwmMC, pwmMD, pwmServo1, pwmServo2, dataPin, clockPin, latchPin): self.motorControl = IC74HC595(dataPin, clockPin, latchPin) self.pwmMA = gpiozero.PWMOutputDevice(pwmMA) self.pwmMB = gpiozero.PWMOutputDevice(pwmMB) self.pwmMC = gpiozero.PWMOutputDevice(pwmMC) self.pwmMD = gpiozero.PWMOutputDevice(pwmMD) self.pwmServo1 = gpiozero.PWMOutputDevice(pwmServo1) self.pwmServo2 = gpiozero.PWMOutputDevice(pwmServo2)
def move(t, pin): # Duty cycle of signal dc = 80.0 # Frequency of signal freq = 10000 onTime = dc / freq offTime = (100.0 - dc) / freq cycleNum = int(t / 1000 * freq / 100) # Scale because DC not 0<x<1 p = gpiozero.PWMOutputDevice(pin, active_high=True, frequency=(freq * 100)) try: p.blink(on_time=onTime, off_time=offTime, n=cycleNum, background=False) except KeyboardInterrupt: pass p.off()
def __init__(self, guizero_app, direction_pin, pwm_pin): self.guizero_app = guizero_app self.accelerometer = mpu6050(0x68) # The way my accereometer is oriented: # 9.8 Gs on Z axis --> slat is flat --> blinds open # zero Gs on Z axis --> slat is vertical --> blinds closed self.accelerometer_z_Gs_blinds_closed = 5.5 self.accelerometer_z_Gs_blinds_open = 9.7 self.gpio_device_motor_direction = gpiozero.DigitalOutputDevice( direction_pin) self.gpio_device_motor_speed = gpiozero.PWMOutputDevice( pwm_pin, initial_value=0, frequency=20_000)
def __init__(self, pins=[0, 0, 0, 0], port=None, resol=1, cogfact=1.0): self.en = None self.step = None self.chop = None self.dir = None self.en = gpiozero.DigitalOutputDevice(pins[0], initial_value=True) self.step = gpiozero.PWMOutputDevice(pins[1], initial_value=0) self.chop = gpiozero.DigitalOutputDevice(pins[2], initial_value=True) self.dir = gpiozero.DigitalOutputDevice(pins[3], initial_value=False) self.resol = resol self.cogfact = cogfact self.pulse = 3e-6 self.port = port if self.port: self._setup()
def _setup_hardware(self): """ Create instances of all peripherals needed. """ self._main_LED = ... # TODO: create your RGB LED instance here # TODO: ensure that the correct GPIO pin is used for the piezo self._piezo = gpiozero.PWMOutputDevice(18, frequency=400) self._sensor_adc = ... # TODO: Create an instance of a # TODO: ensure that the correct GPIO pin is used for the button self._button = gpiozero.Button(4, hold_time=3, hold_repeat=False, pull_up=True) self._button.when_pressed = self._on_button_press self._button.when_released = self._on_button_release self._button.when_held = self._on_button_hold
def __init__(self, pwm_pin) -> None: ''' `Voltmeter(pwm)` initializes a Voltmeter object with the given PWM pin number `pwm`, and sets the initial voltmeter value to 0.0 Args: `pwm_pin` (int): the GPIO pin number to use to control the voltmeter Note: prefer pins 12, 13, 18, or 19 for the PWM pin, these are hardware PWM pins, other pins will use software PWM Raises: PinInvalidPin if the `pwm` pin is not a valid pin number ''' self.pwm = gpiozero.PWMOutputDevice(pwm_pin, active_high=True, initial_value=0.0)
def __init__(self, address=ADDRESS, pwm_pin=PWM_PIN, enable_pin=EN_PIN, target=40, warning=60.0, error=80.0, emergency=100.0): self.address = address self.pwm = gpiozero.PWMOutputDevice(pwm_pin, frequency=20000) self.enable_pin = gpiozero.LED(enable_pin, active_high=False) self.target = target self.warning = warning self.error = error self.emergency = emergency self.on = False self.last_temp = 0.0 self.pwm_value = 0 self.pwm.value = float(self.pwm_value) / 100.0
def LAHome(factory): # Purpose: Send LA to home position # Assume: None # End: LA located in its home position # Input: factory (IP address) # Output: True = reached home # False = failed to reach home print('LA going home') # Set Pi pins for reading limit switch, controlling direction, and outputting a step pulse HOME = gpiozero.Button(14, pull_up=False, pin_factory=factory) DIR = gpiozero.DigitalOutputDevice(20, active_high=False, pin_factory=factory) DIR.on() # Sets direction towards home STEP = gpiozero.PWMOutputDevice(21, active_high=False, initial_value=0.5, frequency=1600, pin_factory=factory) tStart = time.time() # Wait until limit switch is triggered then disable step pulse and return True # If limit switch isn't triggered for 30 sec disable step pulse and return False while HOME.value == 1: STEP.off() DIR.off() tCurr = time.time() if tCurr - tStart > 16: STEP.off() DIR.off() return False print('LA home') return True
def move(t, pin): # Duty cycle of signal dc = 80.0 # Frequency of signal freq = 10000 onTime = dc / freq offTime = (100.0 - dc) / freq cycleNum = int(t / 1000 * freq / 100) # Scale because DC not 0<x<1 # active_high=True -> Usually off, natural behavior # mult. Freq by 100 to get smoother behavior p = gpiozero.PWMOutputDevice(pin, active_high=True, frequency=(freq * 100)) try: # If background False, program will wait # If background True , program will continue print("\tIn move_to: Starting movement, time to complete:", str(t)) p.blink(on_time=onTime, off_time=offTime, n=cycleNum, background=False) print("\tIn move_to: Stopped movement") except KeyboardInterrupt: pass p.off()
def lights_on(i, t, pin): # Duty cycle of signal dc = i # Frequency of signal freq = 10000 onTime = dc / freq offTime = (100.0 - dc) / freq cycleNum = int(t * 60 * freq / 100) # Scale because DC not 0<x<1 # active_high=True -> Usually off, natural behavior # mult. Freq by 100 to get smoother behavior p = gpiozero.PWMOutputDevice(pin, active_high=True, frequency=(freq * 100)) try: # If background False, program will wait # If background True , program will continue #startTime = time.time() p.blink(on_time=onTime, off_time=offTime, n=cycleNum, background=True) #endTime = time.time() except KeyboardInterrupt: pass # print('Time on: ',str(round(endTime - startTime,3)),' s') p.off()
from flask_restful import abort, Api factory = PiGPIOFactory() # Define Motor Configuration # Used for controlling forwards and backwards. motor_1 = gpiozero.Motor(15, 14,pwm=False,pin_factory=factory) # Used for controlling direction. motor_2 = gpiozero.Motor(23, 24,pwm=False, pin_factory=factory) #Define servo servoPin = 17 #GPIO servo = Servo(servoPin, max_pulse_width=1.9/1000, min_pulse_width=0.4/1000,pin_factory=factory) speed = 0.5 pwm = gpiozero.PWMOutputDevice(3,initial_value=speed, pin_factory=factory) # Setup the server. app = Flask(__name__) api = Api(app) speed = 0.5 # Application routing. @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/set_speed', methods=['GET']) def set_speed():
# 12 or 13 on the pi 4 to allow for usage of hardware PWM) import time import subprocess import gpiozero FAN_PIN = 12 CHECK_DELAY_S = 30 # Fan is off until FAN_ON_TEMP_C and then duty cycle increases linearly # (see pwm_curve function) FAN_ON_TEMP_C = 30 PI_MAX_TEMP_C = 80 # Configure pin for PWM fan = gpiozero.PWMOutputDevice(FAN_PIN, active_high=True, frequency=100) fan.value = 0 def pwm_curve(temp): ''' Returns PWM duty cycle ''' if(temp < FAN_ON_TEMP_C): return 0 else: return (1 - (PI_MAX_TEMP_C - temp) / (PI_MAX_TEMP_C - FAN_ON_TEMP_C)) def fan_control(): ''' Get CPU temp + change fan PWM as needed ''' temp = subprocess.run(["vcgencmd", "measure_temp"], stdout=subprocess.PIPE)
and DarkElfinAngel from Raspberrypi.org forum for the timer. ''' import gpiozero as gp import tkinter as tk import sys, os, csv, datetime, cv2, platform, subprocess, time, threading from tkinter import ttk, messagebox from PIL import Image, ImageTk from ttkthemes import ThemedStyle from time import sleep #Hardware Variable names, always match to schematic with numbers. Change your pins if differen. S1 = gp.Button(25) #Counter switch S2 = gp.Button(8) # Reset Cases S3 = gp.Button(7) #Reset Primers S4 = gp.Button(24) #Binding prox switches M1 = gp.PWMOutputDevice(20, frequency=1) #Primer vibrator M2 = gp.PWMOutputDevice(21, frequency=1) #Powder Vibrator Ldr1 = gp.LightSensor(4) #Low Primer Ldr2 = gp.LightSensor(19) #Bullet Feeder Ldr3 = gp.LightSensor(26) #Case Feeder # For Passive buzzers use PWM. Active buzzers use Buzzer. Be wise that too high a # frequecy will peg out CPU. Buzzer = gp.PWMOutputDevice(18, frequency=1500) #If you relays operate backwards swap the active_high state (default is True). #Setting initial_value to false ensures relays start closed enstead of current state. Relay1 = gp.OutputDevice(6, initial_value=False, active_high=True) Relay2 = gp.OutputDevice(12, initial_value=False, active_high=True) #Note to self: the way this works is the csv is turned into a class. The class name is the list ID which is Recipe[n], #where N is the number of the recipe line with 0 being the first line. After that the heading can be use as a dot atribut, #IE Recipe[0].cartridge will give you the cartridge name of recipe 0.
return data # Switch on the Extra delay mode. while True: sli = input("Extra Delay Mode: ") if sli == 'no': slip = 0 break elif sli == 'yes': slip = 0.15 break # Initialize motor I/O. Backward_1 = gpiozero.OutputDevice(24) # On/Off output Forward_1 = gpiozero.OutputDevice(23) #On/Off output SpeedPWM_1 = gpiozero.PWMOutputDevice(18) # set up PWM pin Backward_0 = gpiozero.OutputDevice(12) # On/Off output Forward_0 = gpiozero.OutputDevice(13) #On/Off output SpeedPWM_0 = gpiozero.PWMOutputDevice(16) # set up PWM pin # Create SPI connection. spi = spidev.SpiDev() spi.open(0,0) # Create MPU9250 connection. mpu_0 = MPU9250( address_ak=AK8963_ADDRESS, address_mpu_master=MPU9050_ADDRESS_68, # In 0x68 Address WRIST address_mpu_slave=None, bus=1, gfs=GFS_1000,
import datetime import os import time import gpiozero import toml from gpiozero.pins.pigpio import PiGPIOFactory STEP_WIDTH = 5 ON_OFF_HYSTERESIS = 5 SKRIPTPFAD = os.path.abspath(os.path.dirname(__file__)) factory = PiGPIOFactory() PWM_FAN = gpiozero.PWMOutputDevice(18, pin_factory=factory) TACHO_PIN = gpiozero.Button(23) def load_config(pfad=SKRIPTPFAD): configfile = os.path.join(pfad, "config.toml") with open(configfile) as conffile: config = toml.loads(conffile.read()) return config CONFIG = load_config() class Tacho: def __init__(self): self.start_time = None self.current_measurement = 0 self.last_measurement = datetime.datetime.now()
if "YES" not in lines[0]: time.sleep(0.2) continue m = re.search(r" t=(\d+)$", lines[1]) if m: return int(m.group(1)) / 1000 Exception("boom") def transform(val, off, fact, min_, max_): x = (val - off) * fact x = min(x, max_) x = max(x, min_) return x sensor = DS18S20() fan = gpiozero.PWMOutputDevice(pin=18) while True: cpu_temp = gpiozero.CPUTemperature().temperature hdd_temp = sensor.get() cpu_need = transform(cpu_temp, 35, 0.1, 0, 1) hdd_need = transform(hdd_temp, 25, 0.1, 0, 1) speed = max([cpu_need, hdd_need]) print(cpu_temp, cpu_need, hdd_temp, hdd_need, speed) fan.value = speed time.sleep(10)
import gpiozero as gpio import gpiopins from hcsr04sensor.sensor import Measurement import Adafruit_DHT # GPIO_MODE = GPIO.BOARD DHT22 = Adafruit_DHT.DHT22 pump_up_relay = gpio.OutputDevice(gpiopins.PUMP_UP_PIN) pump_mix_relay = gpio.OutputDevice(gpiopins.PUMP_MIX_PIN) grow_light_relay = gpio.OutputDevice(gpiopins.LED_PIN) solenoid_valve_relay = gpio.OutputDevice(gpiopins.SOLENOID_PIN) distance_sensor = gpio.DistanceSensor(gpiopins.ECHO_PIN,gpiopins.TRIGGER_PIN,max_distance=gpiopins.MAX_DISTANCE) temp_controller_fan = gpio.PWMOutputDevice() def turnOnPump(): while distance_sensor.value > 0: pump_up_relay.on() pump_up_relay.off() def turnOffPump(): pump_up_relay.off() def turnOnLight(): grow_light_relay.on() def turnOffLight():
import time import smbus import numpy as np import gpiozero as gpio from apds9960 import APDS9960 ########################### # Motor related functions # ########################### motor_pins = { 'AIN1': gpio.DigitalOutputDevice(27), 'AIN2': gpio.DigitalOutputDevice(23), 'PWMA': gpio.PWMOutputDevice(22), 'BIN1': gpio.DigitalOutputDevice(17), 'BIN2': gpio.DigitalOutputDevice(15), 'PWMB': gpio.PWMOutputDevice(14), 'STBY': gpio.DigitalOutputDevice(18), } def get_motor_pins(motor): if motor not in ('a', 'b'): raise ValueError('motor should be in ("a", "b")!') in1, in2, pwm = ((motor_pins['AIN1'], motor_pins['AIN2'], motor_pins['PWMA']) if motor == 'a' else (motor_pins['BIN1'], motor_pins['BIN2'], motor_pins['PWMB'])) return in1, in2, pwm
cont = False break else: continue # Run Time in seconds onTime = dc / freq offTime = (100.0 - dc) / freq cycleNum = int(t / 1000 * freq / 100) # Scale because DC not 0<x<1 print('CycleNum = ', cycleNum) print('onTime = ', onTime) print('offTime = ', offTime) # active_high=True -> Usually off, natural behavior # mult. Freq by 100 to get smoother behavior p = gpiozero.PWMOutputDevice(pin, active_high=True, frequency=(freq * 100)) try: # If background False, program will wait # If background True , program will continue startTime = time.time() p.blink(on_time=onTime, off_time=offTime, n=cycleNum, background=False) endTime = time.time() except KeyboardInterrupt: pass p.off() print('Time on: ', str(round(endTime - startTime, 3) * 1000), ' ms') ''' || @changelog || | 1.0 2020-04-30 - Nathaniel Furman : Initial Release || # '''
import gpiozero from time import sleep import json import requests import sys #Set up GPIO pins Forward = gpiozero.OutputDevice(23) SpeedPWM = gpiozero.PWMOutputDevice(24) North = gpiozero.LED(2) East = gpiozero.LED(3) South = gpiozero.LED(17) West = gpiozero.LED(27) try: goAgain = 'Y' while goAgain == 'Y': Forward.on() try: #get city, state, country code data from user print("Please enter a city name: ") city = raw_input() print( "Please input the corresponding state - only if city is in the US: " ) state = raw_input() print("Please input the corresponding country code: ") country = raw_input() URL = "https://api.openweathermap.org/data/2.5/weather"
from crh_botnet import * import gpiozero robot = Robot() robot.network.set_server_address('choate-robotics-rpi-01.local') motor_left = gpiozero.PWMOutputDevice(17) motor_right = gpiozero.PWMOutputDevice(18) H_left_1 = gpiozero.DigitalOutputDevice(22) H_left_2 = gpiozero.DigitalOutputDevice(23) H_right_1 = gpiozero.DigitalOutputDevice(26) H_right_2 = gpiozero.DigitalOutputDevice(20) def setup(): H_left_1.on() H_right_1.on() def on_message(message): if message == 'on': motor_left.value = 0.75 motor_right.value = 0.75 elif message == 'off': motor_left.value = 0 motor_right.value = 0 robot.run(globals())