class Bot: def __init__(self): self.wheels = Wheels() pass def move(self, left, right, time): self.wheels.move(left, right, time)
def __init__(self, scanInterval=0.1): self.sensors = DistanceSensors() self.robot = Wheels() self.previousDistance = -1.0 self.previousDirection = Direction.Stop self.stuckCount = 0 # start distance scanning if not (self.sensors.StartScanner(scanInterval, True)): raise SensorException("Distance sensors not working")
def start_wheels(self): """Start the Wheels Process""" self.ns.target_steering = SteeringDirection.NONE self.ns.target_throttle = 0 # Create class and process self.wheels = Wheels(self.ns) self._start_process("wheels")
def __init__(self, manufacturer): # the names list contains model from Specialized bikes as I am a huge fan of its bikes (I own one! :-)) names = [ "Pitch", "Epic", "Source", "Enduro", "Fatboy", "Status", "Demo", "Tarmac", "Allez", "Venge", "Shiv", "Roubaix", "Secteur", "Diverge", "Awol", "Crux", "Langster", "Sirrus", "Daily", "Crosstail", "CossRoads", "Expedition" ] self.frame = Frames(1) self.wheels = Wheels(1) self.manufacturer = manufacturer self.model_name = choice(names) self.weight = (self.frame.frame_weight + 2 * self.wheels.wheel_weight) / 1000.0 self.cost = self.frame.frame_cost + 2 * self.wheels.wheel_cost
def __init__(self): self.wheels = Wheels() pass
import sys import RPi.GPIO as GPIO from wheels import Wheels GPIO.setmode(GPIO.BCM) robot = Wheels() robot.Stop() GPIO.cleanup()
return self.age def getSpeed(self): return self.speed #A method to increase/decrease speed. Time is in seconds #Amount is the speed increase per second in km/h def accelerate(self, time, amount): i = 0 #increase speed as time X amount while i < time: self.speed += amount if (self.speed >= self.maxSpeed): self.speed = self.maxSpeed break i += 1 newTreds = Wheels() newTreds.changeTire(0, 10) newTreds.changeTire(1, 10) newTreds.changeTire(2, 10) newTreds.changeTire(3, 10) lancer = Car("lancer", newTreds, "LPG", "2L", "Auto", "Burgandy", 145) print(lancer) lancer.accelerate(10, 20) print(lancer.getSpeed()) print(lancer.wheels) newTreds.changeTire(0, -1) print(lancer.wheels)
from boat import Boat from car import Car from engine import Engine from gas_tank import GasTank from solar_car import SolarCar from wheels import Wheels def drive(driveable): driveable.get_wheels_count() driveable.turn('Right') driveable.accelerate() driveable.turn('Right') driveable.brake() if __name__ == '__main__': car = Car(GasTank(60), Engine(80), Wheels(4)) solarCar = SolarCar(GasTank(50), Engine(120), Wheels(8)) boat = Boat(GasTank(900), Engine(200), Wheels(0)) for i in [boat, car, solarCar]: drive(i)
class AutoRobot: def __init__(self, scanInterval=0.1): self.sensors = DistanceSensors() self.robot = Wheels() self.previousDistance = -1.0 self.previousDirection = Direction.Stop self.stuckCount = 0 # start distance scanning if not (self.sensors.StartScanner(scanInterval, True)): raise SensorException("Distance sensors not working") def GetDistanceToNextObstacle(self): ''' Returns the remaining direction, distance in CMs in the current direction of travel Returns space in forward direction if stopped or rotating ''' distance = -1.0 if self.robot.direction == Direction.Forward or self.robot.direction == Direction.Stop or \ self.robot.direction == Direction.SpinLeft or self.robot.direction == Direction.SpinRight: distance = self.sensors.frontDistance[ServoDirection.Ahead] elif self.robot.direction == Direction.Reverse: distance = self.sensors.backDistance[ServoDirection.Ahead] elif self.robot.direction == Direction.ForwardRight: distance = self.sensors.frontDistance[ServoDirection.OffRight] elif self.robot.direction == Direction.ForwardLeft: distance = self.sensors.frontDistance[ServoDirection.OffLeft] elif self.robot.direction == Direction.ReverseLeft: distance = self.sensors.backDistance[ServoDirection.OffLeft] elif self.robot.direction == Direction.ReverseRight: distance = self.sensors.backDistance[ServoDirection.OffRight] elif self.robot.direction == Direction.MoveRight: distance = self.sensors.frontDistance[ServoDirection.Right] elif self.robot.direction == Direction.MoveLeft: distance = self.sensors.frontDistance[ServoDirection.Left] return self.robot.direction, distance def GetFurthestEnd(self): ''' Returns direction, distance Work out if there is more space infront or behind and ignore sides ''' if self.sensors.backDistance[ ServoDirection.Ahead] > self.sensors.frontDistance[ ServoDirection.Ahead]: print("Furthest = Reverse", self.sensors.backDistance[ServoDirection.Ahead]) return Direction.Reverse, self.sensors.backDistance[ ServoDirection.Ahead] else: print("Furthest = Forward", self.sensors.frontDistance[ServoDirection.Ahead]) return Direction.Forward, self.sensors.frontDistance[ ServoDirection.Ahead] def GetMaxDistanceDirection(self): ''' Returns servo end, servo direction, distance Returns the sensor direction with the most space and what that distance is ''' maxRearDistance = max(self.sensors.backDistance.values()) maxFrontDistance = max(self.sensors.frontDistance.values()) if maxRearDistance > maxFrontDistance: res = [ key for key in self.sensors.backDistance if self.sensors.backDistance[key] >= maxRearDistance ] if abs(self.sensors.backDistance[ServoDirection.Ahead] - maxRearDistance) < 10: return ServoEnd.Back, ServoDirection.Ahead, self.sensors.backDistance[ ServoDirection.Ahead] else: return ServoEnd.Back, res[0], maxRearDistance else: res = [ key for key in self.sensors.frontDistance if self.sensors.frontDistance[key] >= maxFrontDistance ] if abs(self.sensors.frontDistance[ServoDirection.Ahead] - maxFrontDistance) < 10: return ServoEnd.Front, ServoDirection.Ahead, self.sensors.frontDistance[ ServoDirection.Ahead] else: return ServoEnd.Front, res[0], maxFrontDistance def GetMinDistanceDirection(self): ''' Returns servo end, servo direction, distance Returns the sensor direction with the most space and what that distance is ''' minRearDistance = min(self.sensors.backDistance.values()) minFrontDistance = min(self.sensors.frontDistance.values()) if minRearDistance < minFrontDistance: res = [ key for key in self.sensors.backDistance if self.sensors.backDistance[key] <= minRearDistance ] return ServoEnd.Back, res[0], minRearDistance else: res = [ key for key in self.sensors.frontDistance if self.sensors.frontDistance[key] <= minFrontDistance ] return ServoEnd.Front, res[0], minFrontDistance def SetSpeedBasedOnDistance(self, distance): ''' Set speed based on space infront of us Return the current speed ''' if distance < 20.0: self.robot.Stop() elif distance < 40.0: self.robot.Speed(40) elif distance < 60.0: self.robot.Speed(50) elif distance < 100.0: self.robot.Speed(80) else: self.robot.Speed(100) return self.robot.robotspeed def RotateToBiggestSpace(self): ''' Returns direction, distance in new direction of travel Rotates so either front or rear is pointing to biggests space. ''' attempts = 5 preferredDirection = self.GetMaxDistanceDirection() while attempts > 0: # repeat until the front or back is pointing to the biggest space print("rotating, biggest space is ", preferredDirection) self.robot.Speed(70) # work out whether to spin right or left if (preferredDirection[0] == ServoEnd.Front and (preferredDirection[1] == ServoDirection.OffRight or preferredDirection[1] == ServoDirection.Right)) or \ (preferredDirection[0] == ServoEnd.Back and (preferredDirection[1] == ServoDirection.OffLeft or preferredDirection[1] == ServoDirection.Left)): print("spin right") self.robot.SpinRight() else: print("spin left") self.robot.SpinLeft() if ServoDirection.OffLeft or ServoDirection.OffRight: time.sleep(0.5) # rotate a bit else: time.sleep(1.0) # rotate a lot self.robot.Stop() # reassess where the biggest space is preferredDirection = self.GetMaxDistanceDirection() # if the best direction is forward or reverse don't spin and return if preferredDirection[1] == ServoDirection.Ahead or \ preferredDirection[1] == ServoDirection.OffLeft or \ preferredDirection[1] == ServoDirection.OffRight: print("direction chosen", preferredDirection) if preferredDirection[0] == ServoEnd.Front: return Direction.Forward, preferredDirection[2] else: return Direction.Reverse, preferredDirection[2] # wait to get new set of distance readings time.sleep(1) attempts -= 1 raise StuckException("cannot rotate out of trouble giving up") def AreWeStuck(self, direction, distance): ''' Returns True if we haven't moved in the last four checks for being stuck ''' if abs( distance - self.previousDistance ) < 1.0 and direction == self.previousDirection and direction != Direction.Stop: self.stuckCount += 1 if self.stuckCount == 4: print("Stuck!") return True else: self.stuckCount = 0 return False def UpdatePosition(self, direction, distance): ''' Record our current location we we can determine later if we are stuck ''' self.previousDirection = direction self.previousDistance = distance def GetNearestObstacleInDirectionOfTravel(self, currentDirection): ''' Find out how far away we are from any obstacle directly infront of our direction of travel ''' nearestObstacle = self.GetMinDistanceDirection() if nearestObstacle[0] == ServoEnd.Front: obstacleGeneralDirection = Direction.Forward else: obstacleGeneralDirection = Direction.Reverse if obstacleGeneralDirection != currentDirection: return 1000.0 return nearestObstacle[2]
from boat import Boat from car import Car from engine import Engine from gas_tank import GasTank from solar_car import SolarCar from wheels import Wheels def test_drive(driveable): driveable.get_wheels_count() driveable.turn('Ліво') driveable.accelerate() driveable.turn('Ліво') driveable.brake() if __name__ == '__main__': car = Car(GasTank(29), Engine(35), Wheels(4)) solarCar = SolarCar(GasTank(10), Engine(25), Wheels(4)) boat = Boat(GasTank(58), Engine(36), Wheels(0)) vehicles = [boat, car, solarCar] for i in vehicles: test_drive(i)
class Car: engine = Engine() # подключаем двигатель transmission = Transmission() # подключаем КП wheels = Wheels() # подключаем колёса def __init__(self): self.path = 0 self.power = False self.gasoline = 0.0 self.oil = 0.0 self.speed = 0.0 self.__time_start = 0 def __repr__(self): self.transforms() return "Данные автомобиля и поездки:\n" \ "\tзапущен = %s\n" \ "\tуровень топлива = %s л.\n" \ "\tуровень масла = %s %%\n" \ "\tскорость = %s км/ч\n" \ "\tпройденый путь = %s км" % (self.power, self.gasoline, self.oil, self.speed, self.path) def transforms(self): # соединение классов, получение данных для вывода self.engine.time = self.power * (time.time() - self.__time_start) self.transmission.turns_engine = self.engine.turns_engine() self.wheels.turns_wheels = self.transmission.clutch_pedal() self.power = self.engine.power self.gasoline = self.engine.gasoline self.oil = self.transmission.oil * 100 self.get_speed() self.path = self.wheels.transform_path() def turn_on(self): # включить двигатель, начинаем отсчёт времени try: self.engine.start_engine() except Exception as e: print("Авто не поедет, пока есть проблемы:\n %s" % e) else: self.__time_start = time.time() print("Вжжжжжжжж-чух-чух-чух-чух") def turn_off(self): # выключить двигатель self.engine.stop_engine() print("Двигатель выключен") def add_gasoline(self, litres): # добавить топлива self.engine.add_gasoline(litres) print("Машина заправлена. Всего в баке %s литров бензина" % self.engine.gasoline) def add_oil(self): # восстановить масло self.transmission.add_oil() print("Ты зашёл на ближайшую СТО и поменял масло. Какой молодец ^_^ ") def change_speed(self, gas=engine.gas, gear=transmission.gear): # изменить скорость self.transmission.gear = gear self.engine.gas = gas print( "Теперь ты едешь на %s передаче и нажал газ на %s градусов. Какой молодец ^_^ " % (self.transmission.gear, self.engine.gas)) def get_speed(self): # расчитать скорость try: self.speed = self.engine.rpm * self.transmission.gear * self.wheels.wheel * 60 except Exception: self.speed = 0 return self.speed
pig = pigpio.pi() def input_char(message): try: win = curses.initscr() win.addstr(0, 0, message) while True: ch = win.getch() if ch in range(32, 127): break time.sleep(0.05) except: raise finally: curses.endwin() return chr(ch) wheels = Wheels(pig, left_servo_pin, right_servo_pin) s = 22 def forward(): set_speeds(s,s) def backward(): set_speeds(-s, -s) def left(): set_speeds(0, s) def right(): set_speeds(s, 0)
from sensors import Sensor from sensors import Sensors from wheels import Wheel from wheels import MockWheel from wheels import Wheels import RPi.GPIO as GPIO from runtime import Runtime from processor import Processor GPIO.setmode(GPIO.BOARD) sensor1 = Sensor(11, 13) sensor3 = Sensor(15, 16) sensor5 = Sensor(18, 19) sensor6 = Sensor(21, 22) sensor8 = Sensor(23, 24) sensor10 = Sensor(26, 29) leftMotor = Wheel(5, 3, 7, 7) rightMotor = Wheel(8, 10, 12, 1) # rightMotor = MockWheel("rightWheel") zrobot_runtime = Runtime( Sensors([sensor1, sensor3, sensor5, sensor6, sensor8, sensor10]), Processor(), Wheels(leftMotor, rightMotor)) zrobot_runtime.start()
import sys import RPi.GPIO as GPIO from wheels import Wheels from ultrasonic import DistanceSensors GPIO.setmode(GPIO.BCM) sensors = DistanceSensors() sensors.StartScanner(0.2) robot = Wheels() x = 's' try: while x != 'e': x=input() if x =='f': robot.Forward() elif x == 'b': robot.Backward() elif x == 's' or x == '0': robot.Stop() elif x == 'l': robot.SpinLeft() elif x == 'r': robot.SpinRight() elif x == 'mr': robot.MoveRight() elif x == 'ml': robot.MoveLeft() elif x == 'fr':