def __init__(self): # defining pin for the sensor's parts. self.pinTrigger = 17 self.pinEcho = 18 self.pinLinefollower = 25 # distance conunter self.total_distance = 0 # distance measurment, starting at self.distance_away = 1 # motor speed self.motor_speed = .3 self.motorforward = (self.motor_speed, self.motor_speed) self.motorbackward = (-self.motor_speed, -self.motor_speed) self.motorleft = (self.motor_speed, 0) self.motorright = (0, self.motor_speed) self.sensor = DistanceSensor(echo = self.pinEcho, trigger = self.pinTrigger) self.rover = CamJamKitRobot()
def run_robot(): robot = CamJamKitRobot() controller = Controller('/dev/input/js0', debug=True) pos_l = 0.0 pos_r = 0.0 while True: event_info = controller.process_event() if event_info: event_name, event_value = event_info updated = False if event_name == 'y': pos_l = -event_value if event_value > THRESHOLD or event_value < -THRESHOLD else 0.0 updated = True if event_name == 'ry': pos_r = -event_value if event_value > THRESHOLD or event_value < -THRESHOLD else 0.0 updated = True if updated: robot.value = (pos_l, pos_r)
# Import the libraries from flask import Flask, render_template, request from gpiozero.pins.pigpio import PiGPIOFactory from gpiozero import Robot, LED, CamJamKitRobot, AngularServo # Define the flask app app = Flask(__name__) # Define the pin factories, the robots and the servos factory = PiGPIOFactory(host='192.168.0.25') factory2 = PiGPIOFactory(host='192.168.0.10') linus_eye = LED(16, pin_factory=factory) linus = Robot(left=(13, 21), right=(17, 27), pin_factory=factory) torvalds = CamJamKitRobot(pin_factory=factory2) angular_servo = AngularServo(22, min_angle=-90, max_angle=90, pin_factory=factory) angular_servo2 = AngularServo(23, min_angle=-90, max_angle=90, pin_factory=factory) # Main function where the main html file is displayed @app.route('/') def index(): return render_template('dual_robot.html') # Turns the eye on
# detect, then generate a set of bounding box colors for each class # An ignore class can be added to ignore classes like boats and bottles to only track living things like people or cats CLASSES = [ "background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor" ] COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3)) #Setup the robot, LED and its boolean value which should be set to false first. #If you plan to use the Robot module as opposed to the CamJamKitRobot module alter the code as such: #Let's say you use the pins 27 and 17 for left and 24 and 23 for right. Then alter it as such: #robot = Robot(left=(27, 17), right=(24,23)) #Also, you can choose another pin number for the LED if you wish. Also, the pin numbering is in BCM format so be sure to take that into consideration. devastator_eye = LED(25) devastator_robot = CamJamKitRobot() robotOn = False # Blink the LED 4 times to initiate code #You can omit this but it helps to have this so you know that it's working properly #Also, it looks cool if you use the LEDs as the eyes for your robot. for x in range(1, 5): devastator_eye.off() sleep(0.5) devastator_eye.on() sleep(0.5) # load our serialized model from disk # This will reference both the model and prototxt file print("[INFO] loading model...") net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
# gpioDrive.py # An autonomous robot using GPIO Zero # Date: 3/23/2017 # Author: Darrell Little - Roanoke Hobby # GNU General Public License v3.0 (GPL-3.0) from gpiozero import CamJamKitRobot, DistanceSensor from time import sleep myBot = CamJamKitRobot() sensor = DistanceSensor(echo=18, trigger=17, threshold_distance=0.15, max_distance=1) def driveForward(): if sensor.distance > 0.15: print('Clear Distance: ', sensor.distance * 100, 'cm') myBot.forward(0.5) else: print('Halt Program, objects too close!') myBot.stop() def avoidObstacle(): myBot.stop() sleep(1) print('Obstacle Detected at ', sensor.distance * 100, 'cm. Change Course') sleep(1) myBot.backward()
# CamJam EduKit 3 - Robotics # Worksheet 3 - Motor Test Code import time # Import the Time library from gpiozero import CamJamKitRobot # Import the CamJam GPIO Zero Library robot = CamJamKitRobot() # Turn the motors on print('Starting') robot.forward() # Wait for 1 seconds time.sleep(1) # Turn the motors off robot.stop() print('Stopping')
import cwiid from cwiid import * import math from serial import Serial from time import sleep from gpiozero import CamJamKitRobot # define robot robot = CamJamKitRobot() # define method to try to connect to wiimote recursively def connectToWiimote(): print("Press 1+2 on your Wiimote now...") wm = None while not wm: try: wm = cwiid.Wiimote() except RuntimeError: print("Connection failed, trying again") print("connected to wiimote") wm.led = 1 # turn on 1st led on wiimote return wm # define method to get wiimote joystick position def getjoystickposition(wiimote): return wiimote.state['nunchuk']['stick'] # define method to scale wiimote joystick position to standard coordinates def scale(x, y, oldminx, oldminy, oldmaxx, oldmaxy, newminx, newminy, newmaxx, newmaxy): # scale y yolddiff = oldmaxy - oldminy
#!/usr/bin/python3 # see: https://github.com/CamJam-EduKit/EduKit3 from gpiozero import CamJamKitRobot from picraftzero import Joystick, steering_mixer, scaled_pair, start robot = CamJamKitRobot() joystick = Joystick() robot.source = scaled_pair(steering_mixer(joystick.values), -1.0, 1.0, input_min=-100, input_max=100) start()
def __init__(self): self.robot = CamJamKitRobot() self.values = (0, 0)
class Rover: def __init__(self): # defining pin for the sensor's parts. self.pinTrigger = 17 self.pinEcho = 18 self.pinLinefollower = 25 # distance conunter self.total_distance = 0 # distance measurment, starting at self.distance_away = 1 # motor speed self.motor_speed = .3 self.motorforward = (self.motor_speed, self.motor_speed) self.motorbackward = (-self.motor_speed, -self.motor_speed) self.motorleft = (self.motor_speed, 0) self.motorright = (0, self.motor_speed) self.sensor = DistanceSensor(echo = self.pinEcho, trigger = self.pinTrigger) self.rover = CamJamKitRobot() def get_distance(self): self.distance_away = self.sensor.distance * 100 print(self.distance_away) def move_forward(self): self.rover.value = self.motorforward time.sleep(.5) self.rover.stop() print("Moving Forward") def move_back(self): self.rover.value = self.motorbackward time.sleep(1) self.rover.stop() print("Moving Back") def move_left(self): self.rover.value = self.motorright # the diffrence between the bots time to move left and right are due to issues of the rovers wheels not touch the ground evenly time.sleep(3) self.rover.stop() print("Moving to the left") def move_right(self): self.rover.value = self.motorleft time.sleep(.5) self.rover.stop() print("Moving to the Right") def navigate(self): while(self.total_distance <= 10): print(self.total_distance) self.get_distance() # checking to see if there is an object infront of the rover. if(self.distance_away < 20): print(self.distance_away) self.get_distance() print("getting close to an obstacle") self.move_left() self.move_forward() self.move_right() else: self.move_forward() time.sleep(1) self.total_distance += 1 time.sleep(1)
#import libraries from gpiozero import CamJamKitRobot #import Robot only if you use a different board from contours import get_saturated_colors, setup_camera #import from the contours script #setup the robot as well as the camera function #If you don't use the CamJam Edukit 3 here are the instructions #Let's say you use the pins 27 and 17 for left and 24 and 23 for right. Then alter it as such: #robot = Robot(left=(27, 17), right=(24,23)) devastator_robot = CamJamKitRobot() camera, capture_buffer = setup_camera() #Like before this sets the robot up for raw in camera.capture_continuous(capture_buffer, format="bgr"): image = raw.array masked, contours, found_color = get_saturated_colors(image) #This is exactly invoked as in the last script. print(f"Color {found_color}, h value: {found_color[0]}") #Just like before it prints the color name and the value if 5 < found_color[0] < 40: print("yellow") devastator_robot.backward() elif 100 < found_color[0] < 135: print("blue") devastator_robot.forward() elif 165 < found_color[0] < 180: #Red is added here for expandability. Again, based on the color wheel and it chooses the first value of the array print("red") devastator_robot.right() else: devastator_robot.stop() #It stops if it sees no other color. capture_buffer.truncate(0)
# CamJam EduKit 3 - Robotics # Worksheet 3 - Motor Test Code GPIO Zero Version # by Neil Bizzell (@PiVangelist) from gpiozero import CamJamKitRobot # Import the CAMJamKitRobot Class from teh GPIO Zero library from time import sleep # import the sleep function from the time library #define robot robot = CamJamKitRobot() #turn on the motors in a forward direction for 2 seconds robot.forward(1) sleep(2)
def initialise_robot(): robot = CamJamKitRobot() return robot
from gpiozero import Robot, CamJamKitRobot, AngularServo from gpiozero.pins.pigpio import PiGPIOFactory #Define the app and window for the servo sliders app = App("Dual Robot Control", layout='grid') servo_window = Window(app, "Servo Movement") servo_window.bg = (51, 165, 255) app.bg = (51, 246, 255) #Define the factories # insert IP addresses of both robots here factory = PiGPIOFactory(host='') # Define both robots linus = Robot(left=(13, 21), right=(17, 27), pin_factory=factory) torvalds = CamJamKitRobot() # Define the servos servo = AngularServo(22, min_angle=-90, max_angle=90, pin_factory=factory) servo_two = AngularServo(23, min_angle=-90, max_angle=90, pin_factory=factory) # Define the functions def direction_one(): linus.forward() def direction_two(): linus.backward()
#import libraries from gpiozero import CamJamKitRobot #if you don't have this board switch this with Robot from contours import get_saturated_colors, setup_camera #import from the contours program #Setup the robot, and camera function #These are the instructions if you don't own the CamJam Edukit 3 #Let's say you use the pins 27 and 17 for left and 24 and 23 for right. Then alter it as such: #robot = Robot(left=(27, 17), right=(24,23)) devastator_robot = CamJamKitRobot() camera, capture_buffer = setup_camera() #Set things up for movement for raw in camera.capture_continuous(capture_buffer, format="bgr"): image = raw.array masked, contours, found_color = get_saturated_colors( image) #This is called from the contours script print( f"Color {found_color}, h value: {found_color[0]}" ) #This will print the color name as well as the value in an RBG array if 5 < found_color[ 0] < 40: #This chooses the first value of the array. This chooses values based on the color wheel print("yellow") devastator_robot.backward() elif 100 < found_color[0] < 135: print("blue") devastator_robot.forward() else: devastator_robot.stop() capture_buffer.truncate(0)
""" MoveGirl with Obstacles""" # Import useful libraries import numpy as np import cv2 import math import time from picamera.array import PiRGBArray from picamera import PiCamera from gpiozero import CamJamKitRobot, DistanceSensor # Distance and motor Variables robot = CamJamKitRobot() hownear = 25.0 reversetime = 0.75 turntime = 0.85 pinTrigger = 17 pinEcho = 18 sensor = DistanceSensor(echo=pinEcho, trigger=pinTrigger) ## Initialize a variable for the explore function last_seen_balloon = 0 time_turned = time.time() turning_left = True # Camera settings # camera = PiCamera() camera.resolution = (160, 120) camera.framerate = 15 rawCapture = PiRGBArray(camera, size=(160, 120)) camera.rotation = 180
#!/usr/bin/env python3 # import libraries from guizero import App, PushButton, Text from picamera import PiCamera from gpiozero import LED, CamJamKitRobot from datetime import datetime #setup the camera, LED and Robot camera = PiCamera() camera.resolution = (640, 480) camera.framerate = 25 devastator_eye = LED(25) devastator_robot = CamJamKitRobot() # Define the functions def capture_camera(): devastator_eye.on() moment = datetime.now() camera.start_recording("/home/pi/video_%02d_%02d_%02d.mjpg" % (moment.hour, moment.minute, moment.second)) def stop_record(): devastator_eye.off() camera.stop_recording() def direction_one(): devastator_robot.forward()
# CamJam EduKit 3 - Robotics # Worksheet 4 - Driving and Turning import time # Import the Time library from gpiozero import CamJamKitRobot # Import the GPIO Zero Library CamJam library robot = CamJamKitRobot() robot.forward() time.sleep(1) # Pause for 1 second robot.backward() time.sleep(1) robot.left() time.sleep(0.5) # Pause for half a second robot.right() time.sleep(0.5) robot.stop()
def main(): global flag flag = 0 robot = CamJamKitRobot() sensor = DistanceSensor(echo=18, trigger=17) # Set speed motorspeed = 0.3 motorForward = (motorspeed, motorspeed) motorBackward = (-motorspeed, -motorspeed) motorLeft = (0.22, 0.17) motorRight = (0.17, 0.22) HOST = '192.168.99.26' PORT = 8080 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((HOST, PORT)) except socket.error: print('Bind failed') s.listen(1) print("Socket awaiting messages") try: while 1: (conn, addr) = s.accept() data = conn.recv(1024) data = data.decode('utf-8') if (data == 'start'): flag = 1 x = threading.Thread(target=run_func, args=( robot, sensor, motorRight, motorLeft, )) x.start() reply = "Started" elif (data == 'stop'): flag = 0 x.join() reply = 'Stopped' elif (data == 'getmotors'): reply = str(robot.value) elif (data == 'getdist'): reply = str(sensor.distance * 100) else: reply = ("Unknown command") # while flag: # sensorOut = sensor.distance * 100 # if sensorOut > 15: # robot.value = motorRight # time.sleep(0.2) # elif sensorOut < 15: # robot.value = motorLeft # time.sleep(0.2) # elif (flag == 0): # robot.value = (0,0) conn.sendall(str.encode(reply)) conn.close() except KeyboardInterrupt: print "Shut down"
# CamJam EduKit 3 - Robotics # Worksheet 7 - Controlling the motors with PWM import time # Import the Time library from gpiozero import CamJamKitRobot # Import the CamJam GPIO Zero Library robot = CamJamKitRobot() # Set the relative speeds of the two motors, between 0.0 and 1.0 leftmotorspeed = 0.5 rightmotorspeed = 0.5 motorforward = (leftmotorspeed, rightmotorspeed) motorbackward = (-leftmotorspeed, -rightmotorspeed) motorleft = (leftmotorspeed, 0) motorright = (0, rightmotorspeed) robot.value = motorforward time.sleep(1) robot.value = motorbackward time.sleep(1) # Pause for 1 second robot.value = motorleft time.sleep(1) # Pause for 1 second robot.value = motorright time.sleep(1) # Pause for 1 second robot.stop()
# CamJam EduKit 3 - Robotics # Worksheet 9 – Obstacle Avoidance GPIO Zero version # by Neil Bizzell (@PiVangelist) from gpiozero import DistanceSensor, CamJamKitRobot # Import DistanceSensor and CamJamKitRobot Classes from the GPIOzero library from time import sleep # Import sleep function from the time library # define the pins for the motor (fixed in the GPIO Zero library) robot = CamJamKitRobot() # Define GPIO pins to use for the ultrasonic sensor sensor = DistanceSensor(echo=18, trigger=17) #define how to avoid the obstacle (simple version, just turn away) def AvoidObstacle(): robot.left() #turn left sleep(0.5) #repeat the next indented block forever while True: robot.forward()#drive forward sleep(0.1) if sensor.distance < 0.3: #check if sensor distance is less than 0.3m robot.stop() #stop the robot AvoidObstacle() #call the AvoidObstacle function
# CamJam EduKit 3 - Robotics # Worksheet 8 - Line Following Robot import time # Import the Time library from gpiozero import CamJamKitRobot, LineSensor # Import the GPIO Zero Library # Set variables for the line detector GPIO pin pinLineFollower = 25 linesensor = LineSensor(pinLineFollower) robot = CamJamKitRobot() # Set the relative speeds of the two motors, between 0.0 and 1.0 leftmotorspeed = 0.5 rightmotorspeed = 0.5 motorforward = (leftmotorspeed, rightmotorspeed) motorbackward = (-leftmotorspeed, -rightmotorspeed) motorleft = (leftmotorspeed, -rightmotorspeed) motorright = (-leftmotorspeed, rightmotorspeed) direction = True # The direction the robot will turn - True = Left isoverblack = True # A flag to say the robot can see a black line linelost = False # A flag that is set if the line has been lost # Define the functions that will be called when the line is # detected or not detected def lineseen(): global isoverblack, linelost print("The line has been found.")
#This is the code used for the robot to move based on the color it sees using the Pi Camera #import needed libraries from gpiozero import CamJamKitRobot #Change this to Robot if you do not have the Cam Jam Edukit 3 robotics kit from contours import setup_camera, get_saturated_colors #import from the contours program #Setup the camjamkit robot. The pins are already defined by the board #The following instructions are for those who do not use the Cam Jam Edukit 3 robotics kit #Let's say you use the pins 27 and 17 for left and 24 and 23 for right. Then alter it as such: #robot = Robot(left=(27, 17), right=(24,23)) devastator_robot = CamJamKitRobot() camera, capture_buffer = setup_camera() #When the robot sees yellow, the robot turns left, when the robot sees blue it turns right. Otherwise it goes forward for raw in camera.capture_continuous(capture_buffer, format="bgr"): image = raw.array masked, contours, found_color = get_saturated_colors(image) print(f"Color {found_color}, h value: {found_color[0]}") if 5 < found_color[0] < 40: #It looks at the first element of the found_color variable. print("yellow") devastator_robot.left() elif 100 < found_color[0] < 135: print("blue") devastator_robot.right() else: devastator_robot.forward() capture_buffer.truncate(0)
from __future__ import division from time import sleep try: # Attempt to import the GPIO Zero library. If this fails, because we're running somewhere # that doesn't have the library, we create dummy functions for set_speeds and stop_motors which # just print out what they'd have done. This is a fairly common way to deal with hardware that # may or may not exist! # Use GPIO Zero implementation of CamJam EduKit robot (thanks Ben Nuttall/Dave Jones!) from gpiozero import CamJamKitRobot print('GPIO Zero found') # Get the robot instance and the independent motor controllers robot = CamJamKitRobot() motor_left = robot.left_motor motor_right = robot.right_motor # Motors are reversed. If you find your robot going backwards, set this to 1 motor_multiplier = -1 def set_speeds(power_left, power_right): """ As we have an motor hat, we can use the motors :param power_left: Power to send to left motor :param power_right: Power to send to right motor, will be inverted to reflect chassis layout
from tweepy.streaming import StreamListener # your Twitter access codes go here ckey = 'YOUR_CONSUMER_KEY_HERE' csecret = 'YOUR_CONSUMER_SECRET_HERE' atoken = 'YOUR_ACCESS_TOKEN_HERE' asecret = 'YOUR_ACCESS_SECRET_HERE' class listener(StreamListener): def on_data(self, data): blow() return True bubbles = CamJamKitRobot() def blow(): bubbles.forward() time.sleep(8) bubbles.stop() def blowshort(): bubbles.forward() time.sleep(1) bubbles.stop() auth = OAuthHandler(ckey, csecret)