import RPi.GPIO as GPIO import time import sys from gpiozero import Motor GPIO.setmode(GPIO.BCM) ### Setup Motor Control ### leftPos = 3 leftNeg = 2 rightPos = 17 rightNeg = 4 motorLeft = Motor(leftPos, leftNeg); motorRight = Motor(rightPos, rightNeg); motorLeft.stop(); motorRight.stop(); sensorForHardRight = [1, 1, 1, 0, 0, 0]; sensorForCurveRight = [0, 1, 1, 0, 0, 0]; sensorForRight = [1, 0, 0, 0, 0, 0]; sensorForRight1 = [0, 1, 0, 0, 0, 0]; sensorForHardLeft = [0, 0, 1, 0, 1, 1]; sensorForCurveLeft = [0, 0, 1, 0, 1, 0]; sensorForLeft = [0, 0, 0, 0, 1, 0]; sensorForLeft1 = [0, 0, 0, 0, 0, 1]; sensorForStraight1 = [0, 0, 1, 1, 0, 0]; sensorForStraight2 = [0, 0, 0, 1, 0, 0]; sensorForStraight3 = [0, 0, 1, 0, 0, 0]; sensorForStop = [0, 0, 0, 0, 0, 0];
# import curses from gpiozero import Motor, Servo from time import sleep xMotor = Motor(forward=7, backward=0) # yMotor = Motor(forward=2, backward=3) # triggerServo = Servo(1) while True: xMotor.forward() sleep(5) xMotor.backward() sleep(5)
from gpiozero import Robot, Motor, DistanceSensor from signal import pause sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2) robot = Robot(left=Motor(4, 14), right=Motor(17, 18)) sensor.when_in_range = robot.backward sensor.when_out_of_range = robot.stop pause()
from gpiozero import Motor pump = Motor(17, 18) pump.stop()
class Py_Driver(): #Node): def __init__(self, **kwargs): #super().__init__('py_driver') #self.subscription = self.create_subscription(Twist,'cmd_vel',self.listener_callback,0) # Store 10 messages, drop the oldest one #self.subscription # prevent unused variable warning self.kwargs = kwargs # print(self.kwargs) self._left_pwm = PWMOutputDevice(kwargs['left_pin'], kwargs['left_active_high']) self._left_motor = Motor(kwargs['left_forward'], kwargs['left_backward'], kwargs['left_pwm']) self._right_pwm = PWMOutputDevice(kwargs['right_pin'], kwargs['right_active_high']) self._right_motor = Motor(kwargs['right_forward'], kwargs['right_backward'], kwargs['right_pwm']) print("Py Pi driver initialiased") def listener_callback(self, msg): # self.get_logger().info('Setting left & right wheel speed: %d %d' % (msg.linear.x, msg.angular.z)) _move_dict = {'linear': msg.linear.x, 'angular': msg.angular.z} self.move = _move_dict def test_motors(self): # for i in range(0,6,1): # i=(i+5)/10 # print(i) i = 0.6 self._left_pwm.value = i self._left_motor.forward() self._right_pwm.value = i self._right_motor.forward() time.sleep(1.0) self._left_motor.stop() self._right_motor.stop() # Code relevant for tuning the left and right wheel movement @property def move(self): #, linear_speed, angular_speed): # Use cmd_vel print("Getting movement") return self._move # Check that movement is consistent for both wheels, maybe with a scalar in the PWM. @move.setter def move(self, _move_dict): # Speed is with respect to the front of the car if (abs(_move_dict['linear']) > 0.5): _move_dict['linear'] = np.sign(_move_dict['linear']) * 0.5 print("Movement constrained") if (abs(_move_dict['angular']) > 1.0): _move_dict['angular'] = np.sign(_move_dict['angular']) * 1.0 print("Movement constrained") if (abs(_move_dict['linear']) <= 0.5 and _move_dict['angular'] == 0.0): print("Change") self._left_pwm.value = abs(_move_dict['linear'] / 0.5) self._right_pwm.value = abs(_move_dict['linear'] / 0.5) if np.sign(_move_dict['linear']) == 1: self._left_motor.forward() self._right_motor.forward() elif np.sign(_move_dict['linear']) == -1: self._left_motor.backward() self._right_motor.backward() print("Acts") print("Linear movement") elif (abs(_move_dict['linear']) == 0.0 and abs(_move_dict['angular']) >= 1.0): self._left_pwm.value = abs(_move_dict['angular'] / 1.0) self._right_pwm.value = abs(_move_dict['angular'] / 1.0) if np.sign(_move_dict['angular']) == 1: self._left_motor.backward() self._right_motor.forward() print("Left wheel back, right wheel front") elif np.sign(_move_dict['angular']) == -1: self._left_motor.forward() self._right_motor.backward() print("Right wheel back, left wheel front") print("This bucket", (np.sign(_move_dict['angular']) == False)) elif (abs(_move_dict['linear']) >= 0.5 and abs(_move_dict['angular']) >= 1.0): if (np.sign(_move_dict['angular']) == 1 and np.sign(_move_dict['linear']) == 1): self._left_pwm.value = 0.5 self._right_pwm.value = 1.0 self._left_motor.forward() self._right_motor.forward() elif (np.sign(_move_dict['angular']) == -1 and np.sign(_move_dict['linear']) == 1): self._left_pwm.value = 1.0 self._right_pwm.value = 0.5 self._left_motor.forward() self._right_motor.forward() if (np.sign(_move_dict['angular']) == 1 and np.sign(_move_dict['linear']) == -1): self._left_pwm.value = 1.0 self._right_pwm.value = 0.5 self._left_motor.backward() self._right_motor.backward() elif (np.sign(_move_dict['angular']) == -1 and np.sign(_move_dict['linear']) == -1): self._left_pwm.value = 0.5 self._right_pwm.value = 1.0 self._left_motor.backward() self._right_motor.backward() print("Last bucket") else: self._left_pwm.value = abs( (_move_dict['linear'] / 0.5 - _move_dict['angular'] / 1.0) / 2.0) self._right_pwm.value = abs( (_move_dict['linear'] / 0.5 + _move_dict['angular'] / 1.0) / 2.0) if (np.sign(_move_dict['linear']) == 1): self._left_motor.forward() self._right_motor.forward() elif (np.sign(_move_dict['linear']) == -1): self._left_motor.forward() self._right_motor.backward() print("Really the last bucket now") time.sleep(0.1) self._left_motor.stop() self._right_motor.stop()
from gpiozero import Motor import time motor1 = Motor(9,10) motor2 = Motor(7,8) while True: for i in range(2): motor1.backward(speed=0.3) motor2.forward(speed=0.9) time.sleep(1) for i in range(2): motor1.backward(speed=1) motor2.forward(speed=0.2) time.sleep(1) motor1.stop() motor2.stop() time.sleep(1)
import paho.mqtt.client as mqtt import encoder_pid as epid from gpiozero import Motor import threading import time # import ultrasonic as us import math # motl = Motor(2, 3) # motr= Motor(14, 15) motl = Motor(3, 2) motr = Motor(15, 14) lr_pos_r = 0 fwrev_pos_r = 0 def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe('joystick/lr') client.subscribe('joystick/fwrev') client.subscribe('joystick/accl') client.subscribe('joystick/cam_rst') client.subscribe('joystick/cam_up_down') def on_message(client, userdata, msg): global lr_pos_r, fwrev_pos_r, accl_val
from gpiozero import Motor from time import sleep m1 = Motor(14,15) speed = 0.5 m1.forward(speed) sleep(1) m1.stop() speed = 1 m1.backward(speed) sleep(1) m1.stop()
label_wiimote_buttons = "Nintendo Wii Remote" label_wiimote_accel = "Nintendo Wii Remote Accelerometer" # Button ID's buttonId = [103, 108, 105, 106, 304, 305, 407, 412, 316, 257, 258] # Button Held States buttonHeld = [False, False, False, False, False, False, False, False, False, False, False] # Indexes for both arrays: # 0 1 2 3 4 5 6 7 8 9 10 # UP DOWN LEFT RIGHT (A) (B) PLUS MINUS HOME (1) (2) # Motors leftWheels = Motor(16, 13) rightWheels = Motor(6, 5) lowerArm = Motor(10, 25) upperArm = Motor(26, 21) clawExtend = Motor(3, 4) clawClose = Motor(17, 22) # Inhibits leftWheelsInh = LED(19) # note: I know this isn't an LED: the LED module simply works really easily rightWheelsInh = LED(12) lowerArmInh = LED(11) upperArmInh = LED(20) clawExtendInh = LED(2) clawCloseInh = LED(27) # Nerf gun
import paho.mqtt.client as mqtt from gpiozero import Motor import threading import time import ultrasonic as us # motl = Motor(2, 3) # motr= Motor(14, 15) motl = Motor(3, 2) motr = Motor(15, 14) joys_pos = [] lr_pos_r = 0 fwrev_pos_r = 0 l_stop_val = 0 r_stop_val = 0 def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe('joystick/lr') client.subscribe('joystick/fwrev') def on_message(client, userdata, msg): global joys_pos, lr_pos_r, fwrev_pos_r if msg.topic == 'joystick/fwrev': fwrev_pos_r = float(msg.payload.decode())
# -*- coding: utf-8 -*- """ Created on Sat Aug 29 22:54:52 2020 @author: Ryan """ from gpiozero import DistanceSensor as ds from gpiozero import Motor import time senFor = ds(31,32, max_distance = 1, threshold_distance = .15) senLeft= ds(33,34,max_distance = 1, threshold_distance = .15) senRight= ds(35,36,max_distance = 1, threshold_distance = .15) sen4Back= ds(37,38,max_distance = 1, threshold_distance = .15) motor1 = Motor(17,18)#left motor2 = Motor(19,20)#right def OnRoadAgain: motor1.forward(.2) motor2.forward(.2) def forwardOBPlan(): motor1.forward(0) motor2.forward(0) time.sleep(1) motor1.backward(.1) motor2.backward(.1)
from gpiozero import Motor from time import sleep mt = Motor(19, 13) mt.forward(0.5) sleep(3) mt.stop() sleep(1) mt.backward(0.5) sleep(3) mt.stop()
from gpiozero import Motor from time import sleep import Rpi.GPIO as GPIO motor = Motor(forward=26, backward=20) counter = 0 try: while counter < 10: motor.forward() sleep(5) motor.backward() sleep(5) counter +=1 finally: GPIO.cleanup()
# Starts a motor with Motor class from gpiozero import Motor from time import sleep motor = Motor(forward=4, backward=14) while True: motor.forward() sleep(5) motor.backward() sleep(5) motor.stop()
from gpiozero import Motor, AngularServo #then import the 'sleep' class from the 'time' library (so we can add pauses in our program) from time import sleep gun_motor = Motor(13, 19) laser = Motor(5, 6) servo = AngularServo(26, min_angle=-40, max_angle=50) retract = -40 fire = 50 print('laser on') laser.forward() print('servo back') servo.angle = retract sleep(0.5) print('motors on') gun_motor.forward(1) sleep(5) for x in range(5): print('fire ', x + 1) servo.angle = fire sleep(0.5) print('retract') servo.angle = retract sleep(3) gun_motor.stop()
from gpiozero import Motor import time #from gpiozero.Pin import #import RPi.GPIO as GPIO mr = Motor(3, 2) ml = Motor(15, 14) ml.stop() mr.stop() try: def forward(): ml.forward(0.3) mr.forward(0.3) def backward(): ml.backward(0.3) mr.backward(0.3) def sstop(): ml.stop() mr.stop() while(True): while(raw_input()=='w'): print "forward" forward() time.sleep(1) while(raw_input()=='s'):
def joystick_loop(j, ): robot = Robot((27, 4), (6, 5)) fork = Motor(15, 23) lift = Motor(20, 21) print('Pins OK') try: axes = {} d_pad = '(0, 0) ' buttons = [] acceleration_mode = False stick_mode = False forward = False d_pad_x, d_pad_y = 0, 0 nom_left, nom_right = 0, 0 while True: try: events = pygame.event.get() for event in events: if event.type == pygame.JOYBUTTONDOWN: buttons.append(str(event.button)) if event.button == 1: # switch soft acceleration mode acceleration_mode = not acceleration_mode elif event.button == 2: try: # blocking scan function scan() try: buttons.remove(str(event.button)) except ValueError: pass except Exception as e: print(f'\r{e}') elif event.button == 3: # switch control map stick_mode = not stick_mode elif event.type == pygame.JOYBUTTONUP: try: buttons.remove(str(event.button)) except ValueError: pass elif event.type == pygame.JOYAXISMOTION: if abs(event.value) > 0.1: axes[event.axis] = f'{event.value:+.4f}' else: axes[event.axis] = f'{0.0:+.4f}' elif event.type == pygame.MOUSEMOTION: pass # print(event.rel, event.buttons) elif event.type == pygame.MOUSEBUTTONDOWN: pass elif event.type == pygame.MOUSEBUTTONUP: pass elif event.type == pygame.JOYHATMOTION: d_pad = f'{event.value} ' d_pad_x, d_pad_y = event.value else: print(event) # logging and writing to motors buttons.sort(key=lambda x: int(x)) ax = list(axes.items()) ax.sort(key=lambda x: x[0]) left, right = -float(axes.get(1, '+0.0')), -float( axes.get(4, '+0.0')) if stick_mode: left, right = joy_to_motor_best( -float(axes.get(0, '+0.0')), -float(axes.get(1, '+0.0'))) if acceleration_mode: left, right, nom_left, nom_right = calculate_diff( left, right, nom_left, nom_right, diff=0.005) if forward: left, right = 0.1, 0.1 print('\rButtons: ' + d_pad + ' '.join(buttons) + ' Axes: ' + '; '.join([f'{k}: {v}' for k, v in ax]), end=f' ({left}, {right})') robot.value = (left, right) lift.value = -d_pad_y fork.value = -d_pad_x except Exception as e: print(f'\r{e}') except KeyboardInterrupt: print("\rEXITING NOW") j.quit()
from gpiozero import Motor import time #from gpiozero.Pin import #import RPi.GPIO as GPIO mr = Motor(3, 2) ml = Motor(15, 14) ml.stop() mr.stop() try: def forward(): ml.forward(0.6) mr.forward(0.6) def backward(): ml.backward(0.7) mr.backward(0.7) def sstop(): ml.stop() mr.stop() except KeyboardInterrupt: print "cleaning" finally: #GPIO.cleanup() print"check it"
self.old_btn_state[new_abbv] = 0 elif event.ev_type == 'Absolute': new_abbv = 'A' + str(self._other) self.abs_state[new_abbv] = 0 self.old_abs_state[new_abbv] = 0 else: return None self.abbrevs[key] = new_abbv self._other += 1 return self.abbrevs[key] Lmotor = Motor(forward=26, backward=19) Rmotor = Motor(forward=13, backward=6) last = [] def rC(ctrl): global last speed = 1 #THERES MORE BUT I THINK THIS IS ALL I NEED xpo = ('HX', 1) xz = ('HX', 0) xno = ('HX', -1) ypo = ('HY', 1) yz = ('HY', 0) yno = ('HY', -1)
# command server for driving import socket from gpiozero import Motor # motor control m1 = Motor(17, 18) m2 = Motor(4, 14) def stop(): m1.stop() m2.stop() def fwd(speed): m1.forward(speed / 255.0) m2.forward(speed / 255.0) def back(speed): m1.backward(speed / 255.0) m2.backward(speed / 255.0) def left(speed): m1.forward(speed / 255.0) m2.backward(speed / 255.0) def right(speed):
# GPIO numbers for motor MOTOR_PIN_FWD = 17 MOTOR_PIN_REV = 18 # GPIO pin for reed switch REED_PIN = 4 # max speed to reduce top speed # maximum value is 1 MAX_SPEED = 0.9 # How long to wait between speed increases ACC_DELAY = 0.5 # How long to wait at the station STATION_DELAY = 10 m1 = Motor(MOTOR_PIN_FWD, MOTOR_PIN_REV) reed_switch = Button(REED_PIN) # Go from stop to max speed def train_speed_up(max_speed): speed = 0 while speed < max_speed: speed += 0.1 m1.forward(speed) sleep(ACC_DELAY) def train_slow_down(current_speed): speed = current_speed while speed > 0:
# Edit line 6 to match your chosen GPIO pin from gpiozero import Motor, DistanceSensor from time import sleep motor = Motor(backward=4) sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2) sensor.when_in_range = motor.backward sensor.when_out_of_range = motor.close
def reload(self): super().reload() self.name = "RaspberryPi" self.duty = self.config["duty"] self.block_length = self.config["block_length"] self.duty_ratio = self.duty_ratio = self.config["raspberrypi"][ "motor"]["duty_ratio"] self.turn_right_period = 0.005 self.turn_left_period = 0.005 self.turn_right_period = self.config["raspberrypi"]["motor"][ "turn_right_period"] self.turn_left_period = self.config["raspberrypi"]["motor"][ "turn_left_period"] self.servo_horizontal = self.config["raspberrypi"]["camera"][ "servo_horizontal"] self.servo_vertical = self.config["raspberrypi"]["camera"][ "servo_vertical"] self.grab = True self.servo_claw = 1 self.servo_claw_angle_open = -60 self.servo_claw_angle_close = 60 self.servo_claw = self.config["raspberrypi"]["claw"]["servo"] self.servo_claw_angle_open = self.config["raspberrypi"]["claw"][ "angle_open"] self.servo_claw_angle_close = self.config["raspberrypi"]["claw"][ "angle_close"] self.servo_horizontal = 2 self.servo_vertical = 3 self.servo_horizontal = self.config["raspberrypi"]["camera"][ "servo_horizontal"] self.servo_vertical = self.config["raspberrypi"]["camera"][ "servo_vertical"] self.IN1 = 7 self.IN2 = 8 self.IN3 = 9 self.IN4 = 10 self.IN1 = self.config["raspberrypi"]["motor"]["pinout"]["IN1"] self.IN2 = self.config["raspberrypi"]["motor"]["pinout"]["IN2"] self.IN3 = self.config["raspberrypi"]["motor"]["pinout"]["IN3"] self.IN4 = self.config["raspberrypi"]["motor"]["pinout"]["IN4"] self.servos = [17, 27, 22] self.servos = self.config["raspberrypi"]["servos"] self.trigger = 18 self.echo = 24 self.trigger = self.config["raspberrypi"]["hcsr04"]["trigger"] self.echo = self.config["raspberrypi"]["hcsr04"]["echo"] motor_left = (self.IN1, self.IN2) motor_right = (self.IN3, self.IN4) self.motors = [ Motor(forward=motor_left[0], backward=motor_left[1]), Motor(forward=motor_right[0], backward=motor_right[1]) ] self.pi_servos = [] for gpio_servo in self.servos: self.pi_servos.append( AngularServo(gpio_servo, min_angle=-90, max_angle=90)) self.hcsr04 = DistanceSensor(echo=self.echo, trigger=self.trigger)
import socketio import eventlet import eventlet.wsgi import RPi.GPIO as GPIO from gpiozero import Motor, OutputDevice from time import sleep from flask import Flask, request, send_from_directory sio = socketio.Server() app = Flask(__name__) motor1 = Motor(24, 27) motor1_enable = OutputDevice(5, initial_value=1) # motor2 = Motor(6, 22) # motor2_enable = OutputDevice(17, initial_value=1) motor3 = Motor(23, 16) motor3_enable = OutputDevice(12, initial_value=1) motor4 = Motor(13, 18) motor4_enable = OutputDevice(25, initial_value=1) # @app.route('/<path:path>', methods=['POST', 'GET']) # def serve_page(path): # return send_from_directory('static', path) @app.route('/<path:path>', methods=['POST', 'GET']) def serve_page(path): return send_from_directory('static', path)
def __init__(self, pin1, pin2): self.pin1 = pin1 self.pin2 = pin2 self.myMotor = Motor(pin1, pin2)
class Robot: def __init__(self): self.m1 = Motor(27, 17) self.m2 = Motor(23, 24) self.m3 = Motor(6, 5) self.m4 = Motor(16, 13) self.stop_status = False self.data = [] self.data.append((0, 0, 7)) def print_data(self): while not self.stop_status: try: d = self.data.pop(0) except: print(len(self.data)) continue print(d) def move(self): while not self.stop_status: if len(self.data) == 0: continue _, y, z = self.data.pop(0) forward_power = (y / 10) # 7 doesn't have any special meaning, it is just the value I get when the accelerometer is on a flat surface # [-1, 7) means go *left*, [8, 19] go *right* # As you can see, for some reason the acclerometer have more 'levels' for *right* than *left*, so it is somewhat more # sensitive to turn right if z < 7: self.m1.forward(max(min(forward_power, 1), 0) * 0.25) self.m2.forward(max(min(forward_power, 1), 0)) self.m3.forward(max(min(forward_power, 1), 0)) self.m4.forward(max(min(forward_power, 1), 0) * 0.25) elif z > 7: self.m1.forward(max(min(forward_power, 1), 0)) self.m2.forward(max(min(forward_power, 1), 0) * 0.25) self.m3.forward(max(min(forward_power, 1), 0) * 0.25) self.m4.forward(max(min(forward_power, 1), 0)) else: self.m1.forward(max(min(forward_power, 1), 0)) self.m2.forward(max(min(forward_power, 1), 0)) self.m3.forward(max(min(forward_power, 1), 0)) self.m4.forward(max(min(forward_power, 1), 0))
# Edit line 6 to match your chosen GPIO pin from gpiozero import Motor, DistanceSensor from time import sleep motor = Motor(forward=4) sensor = DistanceSensor(23,24, max_distance=1, threshold_distance=0.2) sensor.when_in_range = motor.forward sensor.when_out_of_range = motor.close
from gpiozero import Motor from gpiozero.pins.pigpio import PiGPIOFactory import csv import time import cv2 turn_speed = 0.6 drive_speed = 0.2 remote_factory = PiGPIOFactory(host='192.168.1.130') motor_1 = Motor(forward=19, backward=13) motor_2 = Motor(forward=6, backward=5) drive_forward = motor_1.forward drive_backward = motor_1.backward turn_left = motor_2.forward turn_right = motor_2.backward turn_left(0) turn_right(0) drive_forward(0)
from gpiozero import Motor, LED from time import sleep switch = LED(4) switch.on() motora = Motor(forward=22, backward=17) motorb = Motor(forward=18, backward=27) motora.forward() motorb.forward() sleep(3)
''' https://gpiozero.readthedocs.io/en/stable/recipes.html http://raspberry.io/projects/view/reading-and-writing-from-gpio-ports-from-python/ https://pimylifeup.com/raspberry-pi-gpio/ ''' from gpiozero import Motor from time import sleep motor = Motor(forward=4, backward=14) def isopen(): return True def open(): motor.forward() pass def close(): motor.backward() pass if __name__ == "__main__": print('run as it self') while True: open() sleep(1)
from gpiozero import Motor #from gpiozero.Pin import #import RPi.GPIO as GPIO from encoders import d_move, refresh ml = Motor(2, 3) mr = Motor(14, 15) ml.stop() mr.stop() """ I am assuming that the initial location of the bot is facing upwards at 0,0 the bot can make only 90 degree turns """ direction = 'n' # n,e,w,s for different locations that it is facing usfront = 20 try: # ADD SOMETHING TO DO WHEN US IS LESS THAN 5; def forward(): if usfront <= 5: print "error" else: ml.forward() mr.forward() def sstop(): ml.stop()
from gpiozero import Motor from time import sleep motor = Motor(forward=20, backward=21, enable=16, pwm=True) while True: speed = 0.5 motor.forward(speed) sleep(5) motor.backward(speed) sleep(5)
import dynamodbfanlog import dynamodbtemperature import jsonconverter as jsonc # Custom MQTT message callback def customCallback(client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n") lcd = LCD() motor2 = Motor(20, 22, pwm=True) full_path = '/home/pi/Desktop/image1.jpg' file_name = 'image1.jpg' host = "a3c16s480tb79n-ats.iot.us-east-1.amazonaws.com" rootCAPath = "rootca.pem" certificatePath = "certificate.pem.crt" privateKeyPath = "private.pem.key" BUCKET = 'sp-p1650688-s3-bucket' # replace with your own unique bucket name location = {'LocationConstraint': 'us-east-1'} file_path = "/home/pi/Desktop" file_name = "test.jpg" best_bet_item = "Unknown"
import explorerhat from gpiozero import Button, LED, Motor from time import sleep button = Button(9) led1 = LED(10) motor1 = Motor(forward=19 , backward=20) motor2 = Motor(forward=21 , backward=26) while True: if button.is_pressed: print("Button pressed") led1.on() motor1.forward() motor2.forward() else: print("Button is not pressed") led1.off() motor1.stop() motor2.stop()
#!/usr/bin/env python # coding=UTF-8 from gpiozero import Motor from gpiozero import Button import datetime import time import logging TIME_CLOSE = 99 TIME_OPEN = 69 STATUSFILENAME = "/home/pi/domopoules/chickenpython/status.txt" motor = Motor(forward=17, backward=22) button = Button(2) def init(): logging.basicConfig(filename='chicken.log', level=logging.DEBUG, format='%(asctime)s — %(name)s — %(levelname)s — %(message)s') def print_and_log(message): logging.info(message) print message def info_button_pressed(): print_and_log("Door button pressed") button.when_pressed = info_button_pressed def read_status(): file = open(STATUSFILENAME, "r") status = file.readline() file.close()
from gpiozero import Motor, OutputDevice from time import sleep motor2 = Motor(6, 22) motor2_enable = OutputDevice(17, initial_value=1) motor3 = Motor(23, 16) motor3_enable = OutputDevice(12, initial_value=1) turn_time=0.95 def forward(): motor2.forward() motor3.forward() sleep(1.5) def backward(): motor3.backward() motor2.backward() sleep(1.5) def left_turn(): motor3.forward() motor2.backward() sleep(turn_time) def right_turn(): motor3.backward() motor2.forward() sleep(turn_time) def eight():
from gpiozero import Motor import time motorr = Motor(forward=22, backward=23) motorl = Motor(forward=18, backward=17) while True: print "Left motor forward" motorl.forward(1) time.sleep(0.5) motorl.forward(0) time.sleep(2) print "Right motor forward" motorr.forward(1) time.sleep(0.5) motorr.forward(0) time.sleep(2) print "Left motor backwards" motorl.backward(1) time.sleep(0.5) motorl.backward(0) time.sleep(2) print "Right motor backwards" motorr.backward(1) time.sleep(0.5) motorr.backward(0) time.sleep(2)