class PWMLEDIndicator(object): """ A pulse-width modulated LED. """ def __init__(self, gpio_pin, brightness=100): """ Constructor of a PWM LED. :param gpio_pin: GPIO pin assignment (not the header pin number) :param brightness: Brightness percentage. Defaults to 100%. """ self.led = PWMLED(gpio_pin) self.brightness = brightness / 100.0 # brightness value is from 0 to 1.0 def turn_on(self): # ~ self.led.on() self.led.value = self.brightness def turn_off(self): # ~ self.led.off() self.led.value = 0 def blink(self, max_times=10): # blink in a separate thread self.led.blink(0.5, 0.2, n=max_times) def pulse(self, max_times=10): # pulse in a separate thread self.led.pulse(n=max_times) def close(self): self.led.close()
class Hardware1: def __init__(self): from gpiozero import PWMLED self.motor1_pin = PWMLED(6) self.servo_pin = PWMLED(13) try: from picamera import PiCamera self.camera = PiCamera() except Exception as e: print('Camera is disabled due to error:', e) """ Current power on first motor """ @property def motor1(self): return self.motor1_pin.value @motor1.setter def motor1(self, value): self.motor1_pin.value = value """ Current PWM signal on servo """ @property def servo(self): return self.hw.servo_pin.value @servo.setter def servo(self, value): self.servo_pin.value = value def release(self): if self.camera: self.camera.close() if self.motor1: self.motor1_pin.close() if self.servo: self.servo_pin.close() def capture_opencv(): stream = BytesIO() self.camera.capture(stream, format='rgb') # "Rewind" the stream to the beginning so we can read its content stream.seek(0) image = Image.open(stream) return numpy.array(image.convert('RGB'))
def main(): try: led = PWMLED(14) log.info("Reading from GPIO pin: %s" % (led.pin)) while True: brighten(led) dim(led) except KeyboardInterrupt: log.info("...^C pressed...") except: log.error(str(sys.exc_info()[1])) log.error(traceback.format_tb(sys.exc_info()[2])) finally: log.info("Cleaning up/closing.") led.close() # this ensures a clean exit
class Turn(): def __init__(self, left, right): self.left = PWMLED(left) self.right = PWMLED(right) def turn_left(self, value=0.2, for_time=0.2): self.left.value = value time.sleep(for_time) self.left.value = 0 def turn_right(self, value=0.2, for_time=0.2): self.right.value = value time.sleep(for_time) self.right.value = 0 def stop(self): self.right.off() self.left.off() def close(self): self.left.close() self.right.close()
AUTHOR DISCLAIMS ALL WARRANTIES INCLUDING ALL IMPLIED WARRANTIES OF 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. """ from signal import pause from time import sleep from gpiozero import PWMLED left = PWMLED(13) middle = PWMLED(19) right = PWMLED(26) try: left.value = 1 middle.value = 0.5 right.value = 0.25 pause() except KeyboardInterrupt: pass finally: left.close() middle.close() right.close()
#!/usr/bin/python3 from gpiozero import PWMLED from signal import pause red = PWMLED(21) print("Press Crtl-C to stop the program.") while True: try: red.pulse() pause() except KeyboardInterrupt: print("Stopping program.\n") red.close() exit()
class GpiofancontrollerPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.AssetPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.SimpleApiPlugin, octoprint.plugin.ShutdownPlugin): def __init__(self): self.fan = None self.speed = 0.0 self.gcode_command_enable = False self.gcode_index_enable = False self.gcode_fan_index = 4 self.pin_factory = RPiGPIOFactory() self.cpu_fan_timer = None self.cpu_fan_enable = False self.cpu_fan_temp_min = CPU_FAN_TEMP_MIN_DEFAULT self.cpu_fan_temp_max = CPU_FAN_TEMP_MAX_DEFAULT self.cpu_fan_speed_min = CPU_FAN_SPEED_MIN_DEFAULT self.cpu_fan_speed_max = CPU_FAN_SPEED_MAX_DEFAULT self.cpu_fan_old_temp = None def init_fan(self, pin, frequency, speed): try: self.deinit_fan() self.fan = PWMLED(pin=pin, initial_value=speed, frequency=frequency, pin_factory=self.pin_factory) self._logger.info("PWM pin initialized with pin factory: " + str(self.fan.pin_factory)) except: self._logger.error("Error occurred while initializing PWM pin") def deinit_fan(self): try: if self.fan is not None: self.fan.close() self.fan = None self._logger.info("PWM pin deinitialized") except: self._logger.error("Error occurred while deinitializing PWM pin") def start_cpu_fan_timer(self): try: self.stop_cpu_fan_timer() if self.cpu_fan_enable: self.cpu_fan_timer = octoprint.util.RepeatedTimer( CPU_FAN_UPDATE_INTERVAL, self.update_cpu_fan_speed, run_first=True, ) self.cpu_fan_timer.start() self._logger.info("CPU fan update timer started") except: self._logger.error( "Error occurred while starting cpu fan update timer") def stop_cpu_fan_timer(self): try: if self.cpu_fan_timer is not None: self.cpu_fan_timer.cancel() self.cpu_fan_timer = None self._logger.info("CPU fan update timer stopped") except: self._logger.error( "Error occurred while stopping cpu fan update timer") def update_fan_speed(self, speed): if self.fan is not None and speed >= 0.0 and speed <= 1.0: self.speed = speed self.fan.value = self.speed def on_after_startup(self): pin = self._settings.get_int(["pin"]) freq = self._settings.get_int(["freq"]) if pin is not None and freq is not None and self.speed is not None: self.init_fan(pin, freq, self.speed) gcode_command_enable = self._settings.get_boolean( ["gcode_command_enable"]) if gcode_command_enable is not None: self.gcode_command_enable = gcode_command_enable gcode_index_enable = self._settings.get_boolean(["gcode_index_enable"]) if gcode_index_enable is not None: self.gcode_index_enable = gcode_index_enable gcode_fan_index = self._settings.get_int(["gcode_fan_index"]) if gcode_fan_index is not None: self.gcode_fan_index = gcode_fan_index cpu_fan_enable = self._settings.get_boolean(["cpu_fan_enable"]) if cpu_fan_enable is not None: self.cpu_fan_enable = cpu_fan_enable cpu_fan_temp_min = self._settings.get_int(["cpu_fan_temp_min"]) if cpu_fan_temp_min is not None: self.cpu_fan_temp_min = cpu_fan_temp_min cpu_fan_temp_max = self._settings.get_int(["cpu_fan_temp_max"]) if cpu_fan_temp_max is not None: self.cpu_fan_temp_max = cpu_fan_temp_max cpu_fan_speed_min = self._settings.get_int(["cpu_fan_speed_min"]) if cpu_fan_speed_min is not None: self.cpu_fan_speed_min = cpu_fan_speed_min cpu_fan_speed_max = self._settings.get_int(["cpu_fan_speed_max"]) if cpu_fan_speed_max is not None: self.cpu_fan_speed_max = cpu_fan_speed_max self.start_cpu_fan_timer() def on_shutdown(self): self.stop_cpu_fan_timer() self.deinit_fan() def on_settings_save(self, data): octoprint.plugin.SettingsPlugin.on_settings_save(self, data) pin = self._settings.get_int(["pin"]) freq = self._settings.get_int(["freq"]) if pin is not None and freq is not None and self.speed is not None: self.init_fan(pin, freq, self.speed) else: self._logger.error("Error occurred while initializing PWM pin") gcode_command_enable = self._settings.get_boolean( ["gcode_command_enable"]) if gcode_command_enable is not None: self.gcode_command_enable = gcode_command_enable gcode_index_enable = self._settings.get_boolean(["gcode_index_enable"]) if gcode_index_enable is not None: self.gcode_index_enable = gcode_index_enable gcode_fan_index = self._settings.get_int(["gcode_fan_index"]) if gcode_fan_index is not None: self.gcode_fan_index = gcode_fan_index cpu_fan_enable = self._settings.get_boolean(["cpu_fan_enable"]) if cpu_fan_enable is not None: self.cpu_fan_enable = cpu_fan_enable cpu_fan_temp_min = self._settings.get_int(["cpu_fan_temp_min"]) if cpu_fan_temp_min is not None: self.cpu_fan_temp_min = cpu_fan_temp_min cpu_fan_temp_max = self._settings.get_int(["cpu_fan_temp_max"]) if cpu_fan_temp_max is not None: self.cpu_fan_temp_max = cpu_fan_temp_max cpu_fan_speed_min = self._settings.get_int(["cpu_fan_speed_min"]) if cpu_fan_speed_min is not None: self.cpu_fan_speed_min = cpu_fan_speed_min cpu_fan_speed_max = self._settings.get_int(["cpu_fan_speed_max"]) if cpu_fan_speed_max is not None: self.cpu_fan_speed_max = cpu_fan_speed_max self.start_cpu_fan_timer() def get_settings_defaults(self): return dict( pin=17, freq=100, gcode_command_enable=False, gcode_index_enable=False, gcode_fan_index=4, cpu_fan_enable=False, cpu_fan_temp_min=CPU_FAN_TEMP_MIN_DEFAULT, cpu_fan_temp_max=CPU_FAN_TEMP_MAX_DEFAULT, cpu_fan_speed_min=CPU_FAN_SPEED_MIN_DEFAULT, cpu_fan_speed_max=CPU_FAN_SPEED_MAX_DEFAULT, ) def get_assets(self): return dict(js=["js/gpiofancontroller.js"], css=["css/gpiofancontroller.css"], less=["less/gpiofancontroller.less"]) def get_template_configs(self): return [ dict(type="settings", custom_bindings=False), ] def get_api_commands(self): return dict(update_speed=["speed"]) def on_api_command(self, command, data): if command == "update_speed": speedStr = data.get('speed', None) if speedStr != None: speed = float(speedStr) if speed is not None: self.update_fan_speed(speed) def gcode_parse_speed(self, cmd): params = cmd.split("S") if len(params) != 2: return None else: try: speed = int(params[1].split()[0]) if speed < 0 or speed > 255: return None else: return speed / 255 except: return None def gcode_parse_index(self, cmd): params = cmd.split("P") if len(params) != 2: return None else: try: index = int(params[1].split()[0]) if index > 0: return index else: return None except: return None def on_gcode_command(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs): if not self.gcode_command_enable: return if gcode and gcode.startswith("M106"): speed = self.gcode_parse_speed(cmd) if self.gcode_index_enable: index = self.gcode_parse_index(cmd) if index is not None and speed is not None: if index == self.gcode_fan_index: self.update_fan_speed(speed) else: if speed is not None: self.update_fan_speed(speed) elif gcode and gcode.startswith("M107"): if self.gcode_index_enable: index = self.gcode_parse_index(cmd) if index is not None: if index == self.gcode_fan_index: self.update_fan_speed(0.0) else: self.update_fan_speed(0.0) self._plugin_manager.send_plugin_message(self._identifier, dict(speed=self.speed)) def update_cpu_fan_speed(self): try: res = os.popen('vcgencmd measure_temp').readline() new_temp = float(res.replace("temp=", "").replace("'C\n", "")) #self._logger.info("Old CPU Temp: " + str(self.cpu_fan_old_temp)) #self._logger.info("New CPU Temp: " + str(new_temp)) if self.cpu_fan_old_temp is None: self.cpu_fan_old_temp = new_temp return new_speed = self.speed old_temp = self.cpu_fan_old_temp self.cpu_fan_old_temp = new_temp if new_temp > self.cpu_fan_temp_max and old_temp > self.cpu_fan_temp_max: new_speed = float(self.cpu_fan_speed_max) / 100.0 elif new_temp < self.cpu_fan_temp_min and old_temp < self.cpu_fan_speed_min: new_speed = 0.0 elif new_temp >= self.cpu_fan_temp_min and new_temp <= self.cpu_fan_temp_max and old_temp >= self.cpu_fan_temp_min and old_temp <= self.cpu_fan_temp_max: speed_range = (float(self.cpu_fan_speed_max) / 100.0) - (float(self.cpu_fan_speed_min) / 100.0) temp_range = float(self.cpu_fan_temp_max) - float( self.cpu_fan_temp_min) slope = speed_range / temp_range y_int = (float(self.cpu_fan_speed_max) / 100.0) - slope * float(self.cpu_fan_temp_max) new_speed = slope * new_temp + y_int else: return #self._logger.info("New Fan Speed: " + str(new_speed)) self.update_fan_speed(new_speed) self._plugin_manager.send_plugin_message(self._identifier, dict(speed=self.speed)) except: self._logger.error("Error occurred while updating CPU fan speed") def get_update_information(self): # Define the configuration for your plugin to use with the Software Update # Plugin here. See https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html # for details. return dict(gpiofancontroller=dict( displayName="Gpiofancontroller Plugin", displayVersion=self._plugin_version, # version check: github repository type="github_release", user="******", repo="OctoPrint-GpioFanController", current=self._plugin_version, # update method: pip pip= "https://github.com/z4gunn/OctoPrint-GpioFanController/archive/{target_version}.zip" ))
class KillTeam: def __init__(self): self.plusButton = Button(17) self.minusButton = Button(27) self.okButton = Button(22) self.canticleLed1 = PWMLED(5) # IncantationOfTheIronSoul self.canticleLed2 = PWMLED(6) # LitanyOfTheElectromancer self.canticleLed3 = PWMLED(13) # Chant of the Remorseless Fist self.canticleLed4 = PWMLED(19) # Shroudpsalm self.canticleLed5 = PWMLED(26) # Invocation of Machine Might self.canticleLed6 = PWMLED(21) # Benediction of the Omnissiah self.initiativeLed = PWMLED(23) self.movementLed = PWMLED(24) self.psychicLed = PWMLED(25) self.shootingLed = PWMLED(12) self.meleeLed = PWMLED(16) self.moraleLed = PWMLED(20) self.selected_canticle = INCANTATION_OF_THE_IRON_SOUL self.canticle1Used = False self.canticle2Used = False self.canticle3Used = False self.canticle4Used = False self.canticle5Used = False self.canticle6Used = False self.continueGame = True def select_canticles(self): self.initiativeLed.off() self.movementLed.off() self.psychicLed.off() self.shootingLed.off() self.meleeLed.off() self.moraleLed.off() self.plusButton.when_pressed = self.canticle_plus_button self.minusButton.when_pressed = self.canticle_minus_button self.okButton.when_pressed = self.canticle_ok_button self.display_canticle() self.okButton.wait_for_press() self.plusButton.when_pressed = None self.minusButton.when_pressed = None self.okButton.when_pressed = None sleep(0.5) def canticle_plus_button(self): self.selected_canticle += 1 if self.selected_canticle == 8: self.selected_canticle = INCANTATION_OF_THE_IRON_SOUL self.display_canticle() def canticle_minus_button(self): self.selected_canticle -= 1 if self.selected_canticle == -1: self.selected_canticle = BENEDICTION_OF_THE_OMNISSIAH self.display_canticle() def canticle_ok_button(self): if self.selected_canticle == 0 or self.selected_canticle == 7: self.selected_canticle = randint(1, 6) else: if self.selected_canticle == INCANTATION_OF_THE_IRON_SOUL: self.canticle1Used = True elif self.selected_canticle == LITANY_OF_THE_ELECTROMANCER: self.canticle2Used = True elif self.selected_canticle == CHANT_OF_THE_REMORSELESS_FIST: self.canticle3Used = True elif self.selected_canticle == SHROUDPSALM: self.canticle4Used = True elif self.selected_canticle == INVOCATION_OF_MACHINE_MIGHT: self.canticle5Used = True elif self.selected_canticle == BENEDICTION_OF_THE_OMNISSIAH: self.canticle6Used = True self.display_canticle(True) def initiative_phase(self): self.initiativeLed.on() self.movementLed.off() self.psychicLed.off() self.shootingLed.off() self.meleeLed.off() self.moraleLed.off() self.plusButton.when_pressed = None self.minusButton.when_pressed = None self.okButton.when_pressed = None self.okButton.wait_for_press() sleep(0.5) def movement_phase(self): self.initiativeLed.off() self.movementLed.on() self.psychicLed.off() self.shootingLed.off() self.meleeLed.off() self.moraleLed.off() self.plusButton.when_pressed = None self.minusButton.when_pressed = None self.okButton.when_pressed = None self.okButton.wait_for_press() sleep(0.5) def psychic_phase(self): self.initiativeLed.off() self.movementLed.off() self.psychicLed.on() self.shootingLed.off() self.meleeLed.off() self.moraleLed.off() self.plusButton.when_pressed = None self.minusButton.when_pressed = None self.okButton.when_pressed = None self.okButton.wait_for_press() sleep(0.5) def shooting_phase(self): self.initiativeLed.off() self.movementLed.off() self.psychicLed.off() self.shootingLed.on() self.meleeLed.off() self.moraleLed.off() if self.selected_canticle in [ SHROUDPSALM, BENEDICTION_OF_THE_OMNISSIAH ]: self.display_canticle(True, True) self.plusButton.when_pressed = None self.minusButton.when_pressed = None self.okButton.when_pressed = None self.okButton.wait_for_press() if self.selected_canticle in [ SHROUDPSALM, BENEDICTION_OF_THE_OMNISSIAH ]: self.display_canticle(True, False) sleep(0.5) def melee_phase(self): self.initiativeLed.off() self.movementLed.off() self.psychicLed.off() self.shootingLed.off() self.meleeLed.on() self.moraleLed.off() if self.selected_canticle in [ LITANY_OF_THE_ELECTROMANCER, CHANT_OF_THE_REMORSELESS_FIST, INVOCATION_OF_MACHINE_MIGHT ]: self.display_canticle(True, True) self.plusButton.when_pressed = None self.minusButton.when_pressed = None self.okButton.when_pressed = None self.okButton.wait_for_press() if self.selected_canticle in [ LITANY_OF_THE_ELECTROMANCER, CHANT_OF_THE_REMORSELESS_FIST, INVOCATION_OF_MACHINE_MIGHT ]: self.display_canticle(True, False) sleep(0.5) def morale_phase(self): self.initiativeLed.off() self.movementLed.off() self.psychicLed.off() self.shootingLed.off() self.meleeLed.off() self.moraleLed.on() if self.selected_canticle in [1]: self.display_canticle(True, True) self.plusButton.when_pressed = None self.minusButton.when_pressed = None self.okButton.when_pressed = None self.okButton.wait_for_press() if self.selected_canticle in [1]: self.display_canticle(True, False) sleep(0.5) def select_if_end_game(self): self.initiativeLed.pulse() self.movementLed.pulse() self.psychicLed.pulse() self.shootingLed.pulse() self.meleeLed.pulse() self.moraleLed.pulse() self.plusButton.when_pressed = None self.minusButton.when_pressed = self.end_game_select self.okButton.when_pressed = None self.okButton.wait_for_press() self.plusButton.when_pressed = None self.minusButton.when_pressed = None self.okButton.when_pressed = None sleep(0.5) def end_game_select(self): self.continueGame = not self.continueGame if self.continueGame: self.initiativeLed.pulse() self.movementLed.pulse() self.psychicLed.pulse() self.shootingLed.pulse() self.meleeLed.pulse() self.moraleLed.pulse() else: self.initiativeLed.off() self.movementLed.off() self.psychicLed.off() self.shootingLed.off() self.meleeLed.off() self.moraleLed.off() def close(self): self.initiativeLed.close() self.movementLed.close() self.psychicLed.close() self.shootingLed.close() self.meleeLed.close() self.moraleLed.close() self.canticleLed1.close() self.canticleLed2.close() self.canticleLed3.close() self.canticleLed4.close() self.canticleLed5.close() self.canticleLed6.close() self.plusButton.close() self.minusButton.close() self.okButton.close() def display_canticle(self, selected=False, blinking=False): if selected: self.canticleLed1.off() self.canticleLed2.off() self.canticleLed3.off() self.canticleLed4.off() self.canticleLed5.off() self.canticleLed6.off() if self.selected_canticle == 1: if blinking: self.canticleLed1.pulse() else: self.canticleLed1.on() elif self.selected_canticle == LITANY_OF_THE_ELECTROMANCER: if blinking: self.canticleLed2.pulse() else: self.canticleLed2.on() elif self.selected_canticle == CHANT_OF_THE_REMORSELESS_FIST: if blinking: self.canticleLed3.pulse() else: self.canticleLed3.on() elif self.selected_canticle == SHROUDPSALM: if blinking: self.canticleLed4.pulse() else: self.canticleLed4.on() elif self.selected_canticle == INVOCATION_OF_MACHINE_MIGHT: if blinking: self.canticleLed5.pulse() else: self.canticleLed5.on() elif self.selected_canticle == BENEDICTION_OF_THE_OMNISSIAH: if blinking: self.canticleLed6.pulse() else: self.canticleLed6.on() else: if not self.canticle1Used: self.canticleLed1.on() else: self.canticleLed1.off() if not self.canticle2Used: self.canticleLed2.on() else: self.canticleLed2.off() if not self.canticle3Used: self.canticleLed3.on() else: self.canticleLed3.off() if not self.canticle4Used: self.canticleLed4.on() else: self.canticleLed4.off() if not self.canticle5Used: self.canticleLed5.on() else: self.canticleLed5.off() if not self.canticle6Used: self.canticleLed6.on() else: self.canticleLed6.off() if self.selected_canticle == 1: self.canticleLed1.pulse() elif self.selected_canticle == LITANY_OF_THE_ELECTROMANCER: self.canticleLed2.pulse() elif self.selected_canticle == CHANT_OF_THE_REMORSELESS_FIST: self.canticleLed3.pulse() elif self.selected_canticle == SHROUDPSALM: self.canticleLed4.pulse() elif self.selected_canticle == INVOCATION_OF_MACHINE_MIGHT: self.canticleLed5.pulse() elif self.selected_canticle == BENEDICTION_OF_THE_OMNISSIAH: self.canticleLed6.pulse() else: self.canticleLed1.pulse() self.canticleLed2.pulse() self.canticleLed3.pulse() self.canticleLed4.pulse() self.canticleLed5.pulse() self.canticleLed6.pulse()
from gpiozero import PWMLED from time import sleep led = PWMLED(21) intense = 0.1 while intense<1.0: led.value = intense sleep(1) intense = intense+0.1 led.close()
print(error) if __name__ == "__main__": print("CO2Zero startet, bitte warten...") pwm_g = PWMLED(17) pwm_y = PWMLED(27) pwm_r = PWMLED(22) pwm_g.pulse() pwm_y.pulse() pwm_r.pulse() read_config() init_influxdb() lcd.lcd_init() lcd.lcd_string("CO2Zero startet,", lcd.LCD_LINE_1) lcd.lcd_string("bitte warten ...", lcd.LCD_LINE_2) time.sleep(5) pwm_g.close() pwm_y.close() pwm_r.close() init_leds() main()
lighter_thread = threading.Thread(target=lighter_light) lighter_thread.start() change_thread.start() # main loop try: while True: # If PIN 20 pushed, choose from 0 or 1 if GPIO.input(20) == True: random_input = random.choice([0,1]) # if 1 play m**********r.mp3 else chose one of the mp3s in path_list if random_input == 1: sound = path+"m**********r.mp3" else: sound = random.choice(path_list) # use pygame to play the mp3 over the headphone jack pygame.mixer.music.load(sound) pygame.mixer.music.play() time.sleep(1) except KeyboardInterrupt: GPIO.cleanup() language_status_led.close() lighter.close()
if algorithm == "power_2": return pow(2, level / 10) / 1024 elif algorithm == "logarithmic": return (pow(2, ((level / led_step) / fade_factor)) - 1) / steps else: # default to linear return level / 100 try: while True: # loop forever for level in range(led_min, led_max + 1, int( led_step)): # variable x incremented from min to max by step bright = brightness(level) # calculate new duty cycle print("increasing:", level, bright * 100) # print for debug light.value = bright # change duty cycle to vary the brightness of LED. sleep(loop_delay) # sleep in seconds for level in range(led_max, led_min - 1, int( -led_step)): # variable x decremented from max to min by step bright = brightness(level) # calculate new duty cycle print("decreasing:", level, bright * 100) # print for debug light.value = bright # change duty cycle to vary the brightness of LED. sleep(loop_delay) # sleep in seconds except KeyboardInterrupt: pass finally: light.close()
class Element(Function): def __init__(self, id, config, inputData, return_queue, cmd_queue): super().__init__(id, config, inputData, return_queue, cmd_queue) def execute(self): ##################################### # # # REFERENCE IMPLEMENTATION # # # ##################################### specificConfig = self.config.get('SpecificConfig') if not specificConfig: self.return_queue.put( Record(None, message='Trigger: {:04d}'.format( self.config['Identifier']))) return gpioName = None mainMode = None subModeLED = None subModePWMLED = None gpioWorker = None cmd = None self.gpio = None self.initFlag = False for attrs in specificConfig: if attrs['Name'] == 'GPIO': gpioName = attrs['Data'] if attrs['Name'] == 'MainMode': mainMode = attrs['Data'] elif attrs['Name'] == 'SubModeLED': subModeLED = attrs['Data'] elif attrs['Name'] == 'SubModePWMLED': subModePWMLED = attrs['Data'] if mainMode == 'LED': self.gpio = LED(gpioName, initial_value=False) if subModeLED == 'Toggle on input': gpioWorker = self.ledWorkerToggle self.gpio.toggle() self.logLEDstate() elif subModeLED == 'Control on Input': gpioWorker = self.ledWorkerCtrl # set initial state if self.inputData is not None: if self.inputData: self.gpio.on() else: self.gpio.off() self.logLEDstate() elif subModeLED == 'Blink': def a(cmd=None): pass gpioWorker = a # assign an empty function self.gpio.blink() self.return_queue.put( Record( None, 'Start LED Blink Mode on GPIO{}'.format( self.gpio.pin.number))) elif mainMode == 'PWMLED': self.gpio = PWMLED(gpioName, initial_value=False) if subModePWMLED == 'Control on Input': gpioWorker = self.pwmLedWorkerCtrl if self.inputData is not None: self.gpio.value = self.inputData self.return_queue.put( Record( None, 'PWMLED: Set brightness on GPIO{} to {:.2f}'. format(self.gpio.pin.number, self.inputData))) elif subModePWMLED == 'Pulse': def a(cmd=None): pass gpioWorker = a # assign an empty function self.gpio.pulse() self.return_queue.put( Record( None, 'Start PWMLED Pulse Mode on GPIO{}'.format( self.gpio.pin.number))) ##################################### # # # Start of the infinite loop # # # ##################################### while (True): # Example code: Do something try: # Block for 1 second and wait for incoming commands cmd = None cmd = self.cmd_queue.get(block=True, timeout=1) except queue.Empty: pass if isinstance(cmd, ProcCMD): if cmd.bStop: # Stop command received, exit self.return_queue.put( Record(None, 'GPIO{} closed'.format(self.gpio.pin.number))) self.gpio.close() return gpioWorker(cmd) def logLEDstate(self): self.return_queue.put( Record( None, 'Switch LED on GPIO{} to {}'.format(self.gpio.pin.number, self.gpio.is_active))) def ledWorkerToggle(self, cmd=None): if cmd is None: return self.gpio.toggle() self.logLEDstate() def ledWorkerCtrl(self, cmd=None): if cmd is None: return if cmd.data: self.gpio.on() else: self.gpio.off() self.logLEDstate() def pwmLedWorkerCtrl(self, cmd=None): if cmd is None: return try: self.gpio.value = cmd.data except Exception: self.gpio.close() raise self.return_queue.put( Record( None, 'PWMLED: Set brightness on GPIO{} to {:.2f}'.format( self.gpio.pin.number, cmd.data)))
from signal import pause from gpiozero import PWMLED light = PWMLED(21) # create a PWMLED object called "led" try: light.pulse() # blink the LED with fade-in and fade-out time pause() # pause the program except KeyboardInterrupt: # capture CTRL-C to prevent warning pass finally: light.close() # clean up the GPIO
o19.on() sleep(2) print("20..") o20.on() sleep(2) print("21..") o21.on() sleep(2) print("22..") o22.on() sleep(2) print("23..") o23.on() sleep(2) print("24..") o24.on() sleep(2) print("done..") input() #except KeyboardInterrupt: # code to run before CTRL+C #except: # all other errors finally: o6.close() run.close() # cleanup gpio so we don't get an error next time
class DroneControl: def __init__(self): """ instantiate objects this process will establish communication links if fail then raise an exception that will terminate the program """ # dictionary of flight parameters self.parameters = {"descent_vel": 0.25, "logging_interval": 0.1} # Pulse the green LED constantly while script is running self.green_led = PWMLED(22) self.green_led.pulse(fade_in_time=0.5, fade_out_time=0.5) # Flash the red LED if an error occurs self.red_led = LED(17) # If the button is held for 3 seconds then end the script self.button = Button(26) self.button.hold_time = 3 self.button.when_held = self.__prepare_exit self.gcs = GroundControlStation() if self.gcs.initSuccessful: self.report("Link to GCS established") else: # if fail to open link to GCS no means of reporting so enter specific sequence self.alert_initialisation_failure() raise ValueError( "Failed to communicate with Ground Control Station") self.fc = FlightController() if self.fc.initSuccessful: self.report("Link to FC established") else: self.report("Link to FC failed") raise ValueError("Failed to communicate with Flight Controller") self.uC = MicroController() if self.uC.initSuccessful: self.report("Link to uC established") else: self.report("Link to uC failed") raise ValueError("Failed to communicate with Micro Controller") self.logger = DataLogging() self.vision = LandingVision() self.scheduler = RecurringTimer(self.parameters["logging_interval"], self.__monitor_flight) # Setting up class attributes self.abortFlag = None self.emergency_land = False self.state = "Initial" self.received_mission = None self.mission_title = "Default mission name" self.reporting_count = 0 def alert_initialisation_failure(self): """ in case communication to the ground control station (GCS) was not established, drone should have other means of reporting initialisation failure """ self.red_led.blink(on_time=0.1, off_time=0.1) def report(self, message): """ method to directly report a message to GCS """ self.gcs.send_message(message) print(message) def abort(self): """ called at any time and will reset drone so in idle state """ self.red_led.blink( on_time=0.1, off_time=0.1, n=25) # Flash red for 5 seconds while going back to idle self.report("Aborting mission...") self.abortFlag = True self.report("Mission abort successful.") def wait_for_command(self): """ drone is in idle state waiting for a command return: 0 - shutdown 1 - mission 2 - reboot else - error so abort if mission, then save the mission command as a property """ self.report("Drone is idle. Waiting for command.") command = -1 while command == -1: # msg will be type None if no message to read msg = self.gcs.read_message() if msg == "shutdown": command = 0 elif msg == "reboot": command = 2 elif msg == "mission": # mission command recieved, waiting for mission details. start = time.perf_counter() # timeout after 5 sec while time.perf_counter() - start < 5: mission_message = self.gcs.read_message() if mission_message is not None: self.received_mission = json.loads(mission_message) command = 1 break else: self.report( "Wait for mission details timed out after 5 seconds") self.abort() return command def process_mission(self): """ Processes the received mission and set class attributes """ try: self.mission_title = self.received_mission["title"] self.fc.set_destination(self.received_mission["location"]) self.fc.mission_height = int(self.received_mission["altitude"]) except: self.report("Error processing mission, aborting.") self.abortFlag = True else: self.report("Mission processing finished.") def battery_load(self): """ loops until battery is loaded poll FC to determine if loaded timeout after 30 s """ self.report("Waiting for battery to be loaded.") # wait for battery connection start = time.perf_counter() while time.perf_counter() - start < 20: if self.fc.is_battery_connected(): self.report("Battery connected.") break else: self.report("Battery not connected within 20 seconds.") # wait for battery secured confirmation start = time.perf_counter() while time.perf_counter() - start < 20: if self.gcs.read_message() == "battery secured": self.report("Battery loaded.") break else: self.report( "Battery secured confirmation not received within 20 seconds.") def parcel_load(self): """ Waits for button press to start parcel load """ # Wait for the button to be pressed self.button.wait_for_press() # This function is blocking self.report("Closing grippers") self.uC.close_grippers() if self.uC.is_parcel_loaded(): self.report("Parcel loaded.") else: self.report("Failed to load parcel.") self.abort() def check_armable(self): """ do necessary checks to determine if drone is ready to arm note, hardware safety switch is pressed after this """ if self.fc.get_armmable_status(): self.report("Drone ready to arm.") else: self.report("Arming check failed.") self.abort() def wait_for_flight_authorisation(self): """ wait for authorisation from ground control station to begin flight timeout after 30 s """ self.report("Waiting for authorisation to fly.") self.report("Reply \"takeoff\"") # wait for message authorising flight - timeout 30 s timeout = 30 start = time.perf_counter() while time.perf_counter() - start < timeout: if self.gcs.read_message() == "takeoff": self.report("Authorisation received.") break else: self.report("Authorisation window timed out.") self.abort() def execute_flight(self): """ monitor drone status facilitate logging report to base continue when loiter point reached """ # Start data logging self.logger.prepare_for_logging(self.mission_title) self.scheduler.start() self.report("Drone is arming and taking off...") self.state = "Arming" self.fc.arm() # Loop until the drone is almost at traverse altitude self.state = "Ascending" self.fc.start_ascending() while self.fc.get_altitude() < self.fc.mission_height * 0.95: time.sleep(0.1) # Loop until the drone is within 5m of destination self.fc.fly_to_destination() self.state = "Traversing" while self.fc.get_distance_left() > 5: time.sleep(0.1) # Loop until the drone is within 2m of ground self.fc.change_flight_mode("AUTO") self.state = "Descending" current_alt = self.fc.get_altitude() while current_alt > 2: # Use vision system for guidance x_vel, y_vel = 1, 2 # self.vision.get_offset(current_alt) z_vel = self.parameters["descent_vel"] p_gain = 0.2 self.fc.move_relative(p_gain * x_vel, p_gain * y_vel, z_vel, 0) # Add a delay so that the drone isn't at an angle when the picture is taken time.sleep(1) current_alt = self.fc.get_altitude() # Loop until the drone has landed and is disarmed self.state = "Landing" self.fc.land() # This is non blocking while self.fc.vehicle.armed: drone.report("Drone is landing") time.sleep(1) drone.report("Drone landed.") # Stop data logging self.scheduler.stop() self.logger.finish_logging() def __monitor_flight(self): """ Get flight data from various places and send them to the data logging module """ if self.gcs.read_message() == "emergency land": self.fc.vehicle.mode = "LAND" while self.fc.vehicle.armed: self.report("Drone is executing emergency landing.") time.sleep(1) self.report("Drone has finished emergency landing.") # Then exit the script so operator can approach and turn off the drone self.__prepare_exit() # Get details to log fc_stats = self.fc.get_fc_stats() current = self.fc.vehicle.battery.current # self.uC.get_current() for SITL # Send the details to the data logging module self.logger.log_info(current, fc_stats) # Every second, report the flight stats to the GCS if self.reporting_count % 10 == 0: message = "State: " + self.state.ljust(10) \ + " | Altitude: " + fc_stats["Location alt"].ljust(6) \ + " | Remaining Distance: " + str(round(float(fc_stats["Distance to waypoint"]))).ljust(4) \ + " | Speed: " + str(round(float(fc_stats["Groundspeed"]), 2)).ljust(5) \ + " | Battery Voltage (V): " + fc_stats["Battery"].ljust(5) \ + " | Battery Current (A): " + str(round(float(current))).ljust(5) self.report(message) self.reporting_count += 1 def release_package(self): """ open the grippers to release the package """ self.report("Releasing parcel.") self.uC.open_grippers() # blocking function self.report("Parcel released.") def upload_return_mission(self): """ mission to return to base the mission will be executed using previously defined functions """ # Define the return mission try: self.mission_title += "_return" self.fc.set_destination("Post Room") # self.fc.mission_height remains the same except: self.report("Error processing return mission, aborting.") self.abortFlag = True else: self.report("Mission processing finished.") def shutdown(self): """ close communication ports and perform clean shutdown of electronics running from secondary battery """ self.report("Drone is shutting down.") self.__prepare_exit() # Shutdown raspberry pi os.system('sudo shutdown now') def reboot(self): """ close communication ports and reboot drone control components good incase we need to reset anything """ self.report("Drone is rebooting.") self.__prepare_exit() # Reboot raspberry pi os.system('sudo shutdown -r now') def __prepare_exit(self): self.report("Button held - preparing script exit.") # Allow modules to cleanly close their processes self.logger.close() self.uC.close() self.fc.close() self.gcs.close() # Safely exit from GPIO usage self.green_led.close() self.red_led.close() self.button.close()