def __init__(self): self.lcd = LS027B4DH01(spi=SPI(2, baudrate=2_000_000, polarity=0, phase=0, bits=8, firstbit=SPI.LSB, sck=Pin(18), mosi=Pin(23), miso=Pin(19)), scs=Pin(32, Pin.OUT), extcomin=Pin(33, Pin.OUT), disp=Pin(25, Pin.OUT)) self.button = Joystick(x=Pin(34), y=Pin(35), s=Pin(26, Pin.IN)) self.mpu9250 = MPU9250(I2C(scl=Pin(21), sda=Pin(22), freq=100000)) self.mpu9250.setting(self.mpu9250.GFS_1000, self.mpu9250.AFS_16G) self.states = { 'home': Ui_home(self), 'acceleration': Ui_acceleration(self), 'gyro': Ui_gyro(self), 'geomagnetism': Ui_geomagnetism(self) } self.state = 'home'
def main(): # global exit_flag js_lock = threading.Lock() arm_lock = threading.Lock() js = Joystick(1, "Thread - Joystick", js_lock) arm = None screen = Screen() hotas = HOTAS_Arm(1, "Thread - HOTAS", js, arm, js_lock, arm_lock, screen) js.start() hotas.start() screen.start() screen.join() js.stop() print("Joystick asked to stop...") hotas.stop() print("Program asked to stop...") hotas.join() print("Main Ended") print("Please press a key on the joystick to end the program...") js.join() print("Program ended...")
def __init__(self): self.lcd = LS027B4DH01( SPI(2, baudrate=2_000_000, polarity=0, phase=0, bits=8, firstbit=SPI.LSB, sck=Pin(18), mosi=Pin(23), miso=Pin(19)), Pin(32, Pin.OUT), Pin(33, Pin.OUT), Pin(25, Pin.OUT)) self.button = Joystick(Pin(34), Pin(35), Pin(26, Pin.IN)) self.mpu9250 = MPU9250(I2C(scl=Pin(21), sda=Pin(22), freq=100000)) self.mpu9250.setting(self.mpu9250.GFS_1000, self.mpu9250.AFS_16G) self.states = { 'home': Home(self), 'record': Record(self), 'settings': Settings(self) } self.state = 'home'
def setup(): global joystick, mouse_control, scroll_control, distance_sensor GPIO.setmode(GPIO.BOARD) joystick = Joystick(7, 0, 1) mouse_control = Potentiometer(2) scroll_control = Potentiometer(3) distance_sensor = DistanceSensor(35, 37)
def __init__(self): # create simulation (GUI) self.urdfRootPath = pybullet_data.getDataPath() p.connect(p.GUI) p.setGravity(0, 0, -9.81) # set up camera self._set_camera() # load some scene objects p.loadURDF(os.path.join(self.urdfRootPath, "plane.urdf"), basePosition=[0, 0, -0.65]) p.loadURDF(os.path.join(self.urdfRootPath, "table/table.urdf"), basePosition=[0.5, 0, -0.65]) # example YCB object obj1 = YCBObject('003_cracker_box') obj1.load() p.resetBasePositionAndOrientation(obj1.body_id, [0.7, -0.2, 0.1], [0, 0, 0, 1]) # load a panda robot self.panda = Panda() # connect to joystick for control self.joystick = Joystick(scale=0.01)
def init_ui(self): QtGui.QMainWindow.__init__(self, None) ###Joystick Interpret StoryTelling and Nao_Manager #### self.joystick = Joystick(self) self.interpret1 = Interpret(1) self.interpret2 = Interpret(2) self.story = StoryTelling() self.manager = Nao_manager() #Timer, updating nao battery level, and connection self.timerNao = QtCore.QTimer(self) self.connect(self.timerNao, QtCore.SIGNAL("timeout()"), self.manager.nao_getStatus) self.timerNao.start(3000) self.timerStory = QtCore.QTimer(self) self.connect(self.timerStory, QtCore.SIGNAL("timeout()"), self.story.update_clock) self.timerStory.start(200) ########### Connect ###### self.joystick.joy_event1.connect(self.interpret1.translate) self.joystick.view_event1.connect(self.interpret1.changeView) self.interpret1.interpret_event.connect(self.story.transmit_msg) self.joystick.joy_event2.connect(self.interpret2.translate) self.joystick.view_event2.connect(self.interpret2.changeView) self.interpret2.interpret_event.connect(self.story.transmit_msg) self.story.storytelling_event.connect(self.manager.transmit_msg) self.joystick.second_joy_detected.connect(self.add_joystick) #### GUI###### self.setWindowTitle("Multiple Nao xbox controller") self.layout_main = QtGui.QGridLayout() self.group_ManagerStory = QtGui.QGroupBox("Nao Control Joystick") self.layout_ManagerStory = QtGui.QVBoxLayout() self.layout_ManagerStory.addWidget(self.manager) self.layout_ManagerStory.addWidget(self.story) self.group_ManagerStory.setLayout(self.layout_ManagerStory) #set layout QGridBox self.layout_main.addWidget(self.group_ManagerStory, 0, 1) self.layout_main.addWidget(self.interpret1, 0,0) self.setLayout(self.layout_main) self.show() #### Nao Manager #### LUCAS PUIS MAMA PUIS LUCY #self.manager.addNao("Timide", "10.0.1.20", 9559, 1 ) self.manager.addNao("Lucas", "10.0.1.11", 9559, 2 ) #self.manager.addNao("Mama", "10.0.1.12", 9559 , 2) #self.manager.addNao("Lucy", "10.0.1.13", 9559 , 2) self.manager.init_manager()
def get_joystick(): while True: try: joystick = Joystick() break except Exception: print('Error happened while recognizing the joystick. Retrying in 1 second...') Joystick.reinit() sleep(1) return joystick
def main(amybot=True, camjambot=False): joystick = Joystick() # if elsing this because the init methods of both classes do stuff with hardware, so best to only intiailise deliberately if amybot: bot = AmyBot() else: bot = CamJamBot() # Re-direct our output to standard error, we need to ignore standard out to hide some nasty print statements from pygame sys.stdout = sys.stderr interval = 0.0 # Power settings voltage_in = 6.0 # Total battery voltage to the PicoBorg Reverse voltage_out = 5.0 #* 0.95 # Maximum motor voltage, we limit it to 95% to allow the RPi to get uninterrupted power # Setup the power limits if voltage_out > voltage_in: max_power = 1.0 else: max_power = voltage_out / float(voltage_in) # Setup pygame and wait for the joystick to become available try: LOGGER.info('Press CTRL+C to quit') running = True # Loop indefinitely while running: # Get the latest events from the system had_event = False events = pygame.event.get() # Handle each event individually for event in events: if event.type == pygame.QUIT: # User exit running = False break elif event.type == pygame.JOYBUTTONDOWN: # A button on the joystick just got pushed down had_event = True elif event.type == pygame.JOYAXISMOTION: # A joystick has been moved had_event = True if had_event: # Read axis positions (-1 to +1) + determine how much to move by left_drive, right_drive = joystick.get_reading() bot.move(left_drive, right_drive) time.sleep(interval) except KeyboardInterrupt: # CTRL+C exit, disable all drives #LeftMotor.speed(0) #RightMotor.speed(0) LOGGER.debug('Motors off')
def __init__(self, joystick_port=0, serial_port='/dev/ttyACM0', publish_rate=10.0): self.joystick = Joystick(joystick_port) self.serial_port = serial_port self.publish_rate = publish_rate self.xbee = Packet() self.arm_car = False self.last_data = None self.arm_display_count = 0 self.safety_check_done = False
def __init__(self) -> None: self._joystick = Joystick(FORWARD_PIN, REVERSE_PIN, LEFT_PIN, RIGHT_PIN) self._left_ramp = Ramp(RAMP_SIZE, RAMP_BREAK_FACTOR) self._right_ramp = Ramp(RAMP_SIZE, RAMP_BREAK_FACTOR) self._left_motor_controler = MotorControler(LEFT_MOTOR_PWM, LEFT_MOTOR_A, LEFT_MOTOR_B) self._right_motor_controler = MotorControler(RIGHT_MOTOR_PWM, RIGHT_MOTOR_A, RIGHT_MOTOR_B)
def __init__(self, master=None): super().__init__(master) self.joystick = Joystick() self.master = master self.grid() self.acelerador = tk.StringVar() self.re = tk.StringVar() self.esquerda = tk.StringVar() self.direita = tk.StringVar() self.cam_v = tk.StringVar() self.cam_h = tk.StringVar() self.criar_componentes() self.txt_acelerador.focus_set() self.atual = self.acelerador
def __init__(self): #channel numbers self.errorLightOut = 4 self.errorLightLow = 18 self.switchOut = 13 self.switchDetect = 20 #constants self.rs_stopped = 0 self.rs_forward = 1 self.rs_reverse = 2 self.ss_nothing = 0 #nothing has happened yet self.ss_start = 1 #both eyes open complete self.ss_forward1 = 2 #one eye open complete self.ss_forward2 = 3 #both eyes closed complete self.ss_reverse1 = 4 #both eyes closed complete self.redFac = .75 self.addFac = 1 - self.redFac self.maxSwitchTime = 7 #leave room for waiting and messing up self.maxReverseTime = 5 self.defaultPrevX = 0 self.defaultPrevY = -.5 #vars self.runState = self.rs_stopped self.runTime = 0 self.switchState = self.ss_nothing self.switchTime = 0 self.prevX = self.defaultPrevX self.prevY = self.defaultPrevY self.joystick = Joystick() io.setmode(io.BCM) io.setup(self.errorLightOut, io.OUT, initial=io.LOW) io.setup(self.errorLightLow, io.OUT, initial=io.LOW) io.setup(self.switchOut, io.OUT, initial=io.HIGH) io.setup(self.switchDetect, io.IN, pull_up_down=io.PUD_DOWN) time.sleep(.2) #wait for io to definitely turn on before attempting to sense if self.should_shut_down(): print("waiting for switch on") io.wait_for_edge(self.switchDetect, io.RISING) #wait for switch to turn on. self.set_led(io.HIGH) #indicate success time.sleep(.3) #wait so people know for sure that its working
def __init__(self, device: Device) -> None: self.device = device self.type = device.type self.binds: Dict[str, Callable] = dict() if device.type == "keyboard": self.keyboard = Keyboard() for action, how in device.actions.items(): if type(how) is str: self.keyboard.bind(Input.str_to_key(how), action) elif type(how) is list and "repeat" in how: self.keyboard.bind(Input.str_to_key(how[0]), action, True) else: raise Exception("invalid binding: {}".format(how)) elif device.type == "joystick": self.joystick = Joystick(device.joystick) for action, how in device.actions.items(): invalid = True if type(how) is int: self.joystick.bind_button(how, action) invalid = False elif type(how) is list: if ( len(how) >= 3 and type(how[0]) is str and how[0] == "axis" ): repeat = "repeat" in how axis = int(how[1]) direction = 0 if how[2] in ("+", "-"): if how[2] == "-": direction = -1 elif how[2] == "+": direction = 1 invalid = False self.joystick.bind_axis( axis, direction, action, repeat ) if invalid: raise Exception("invalid binding: {}".format(how))
def main(): lm = LedMatrix() pygame.init() pygame.joystick.init() joy = Joystick(0) gameMain = LifeGameMain(lm, joy) try: gameMain.start() except KeyboardInterrupt: pass except: print(traceback.format_exc()) if lm != None: lm.term()
def update_from_joystick(rov_movement): print("Thrade oluşturuldu") # Joystick variables are creating joystick_values = {} Joy_obj = Joystick() joystick_values.update(Joy_obj.shared_obj.ret_dict) # Joystick variables are created global arayuz_running while arayuz_running: Joy_obj.while_initializer() if Joy_obj.joystick_count: Joy_obj.for_initializer() Joy_obj.joysticks() joystick_values = Joy_obj.shared_obj.ret_dict if rov_movement: # Robotik kol hareketi arm_status = joystick_values["robotik_kol"] arm_status = True if arm_status == 1 else ( False if arm_status == -1 else None) rov_movement.toggle_arm(arm_status) # XYZ hareketi pf = joystick_values["power_factor"] zpf = joystick_values["zpf"] xy_power = joystick_values["xy_plane"]["magnitude"] * pf * 100 z_power = joystick_values["z_axes"] * pf * zpf * 60 turn_power = joystick_values["turn_itself"] * pf * 100 tilt_degree = joystick_values["tilt_degree"] if tilt_degree: rov_movement.go_xyz_with_tilt(xy_power, z_power, turn_power, tilt_degree=tilt_degree) else: xy_angle = joystick_values["xy_plane"]["angel"] rov_movement.go_xy_and_turn(xy_power, xy_angle, turn_power) rov_movement.go_z_bidirectional(z_power) sleep(0.04) Joy_obj.clock.tick(50)
def __init__(self, amybot=True, cambot=False, fourtronix=False, straight=False): Sonar.__init__(self) # Rainbow.__init__(self) print("Hello!") self.last_text = "Bleurgh!" self.joystick = Joystick() # if elsing this because the init methods of both classes do stuff with hardware, so best to only intiailise deliberately if amybot: self.bot = AmyBot() LOGGER.info('Enable AmyBot') elif cambot: self.bot = CamJamBot() LOGGER.info('Enable CamJamBot') elif fourtronix: self.bot = FourTronix() LOGGER.info('Enable FourTronixBot') else: print("Unknown Robot Type") sys.exit(0) self.straight_line_start = False if straight: self.mode = R2_BUTTON self.straight_line_start = True # Re-direct our output to standard error, we need to ignore standard out to hide some nasty print statements from pygame sys.stdout = sys.stderr interval = 0.0 self.modes = { # L1_BUTTON: self.rainbow, R1_BUTTON: self.remote, L2_BUTTON: self.maze, R2_BUTTON: self.straight } super().__init__()
def __init__(self, parent=None): super(MainDialog, self).__init__(parent) self.setupUi(self) # set up the heartbeat callback self.heartBeat = HeartBeat() self.heartBeat.heartBeat.connect(self.ServiceHeartBeat) self.heartBeat.start() # start the heartbeat thread! # set up the joystick thread self.lockJoystick = QtCore.QMutex() self.joystick = Joystick(self.lockJoystick) self.joystick.start() # This is the embedcreativity API self.API = PalmettoAPI() self.status = -1 self.voltage = -1 self.current = -1 # Status variables to keep track of what we've sent the board self.motorPowerOn = False self.slowMo = True self.ledDecButtonDown = False self.ledIncButtonDown = False self.pwrLED = ledDefault # Security Cam Mode variables self.hatXDown = False self.hatYDown = False self.securityCamMode = False self.securityCamLeftPos = 650 self.securityCamRightPos = 690 self.securityCamDirectionIncreasing = True self.securityCamPositionLast = 670 self.securityCamIncAmount = 2 self.securityCamIncAmountMin = 1 self.securityCamIncAmountMax = 10 self.chargerDockOpen = False self.chargerDockOpenPos = 550 self.chargerDockClosedPos = 1200
def pause(self): self.__flag.clear() # set False def resume(self): self.__flag.set() # set True def stop(self): self.__flag.set() # resume from pause self.__running.clear() def running(self): return self.__flag.isSet() if __name__ == '__main__': js = Joystick() car = Car() camera = Camera() camera.start() try: while True: map = js.run() x = map.rx car.turn(x) # y = map.ly # car.turn(y) if map.menu == 1:
def createTank(controllerId): joystick = Joystick(controllerId) playerTank = Tank(tankColours[controllerId], screenWidth, screenHeight, joystick, obstacles) return playerTank
def __init__(self): self.udp_client = UDPClient() self.joystick = Joystick() self.auto = False
def ampMoveDiscon(input): i = input * 2 return i**3 * -1 class Printer: def start(self, topot): topot.registerOutput("print", self.printer) def printer(self, input, prefix = ""): def prnt(): print prefix, input.value return OutputSignal(prnt, input) t.add(Printer()) t.add(Ticker(20)) t.add(Joystick("/dev/input/js0"), "j0_") t.add(MidiInput()) t.add(MidiOutput()) t.connect("note", 48, t.get("j0_button",0)) t.connect("print", "note 48", t.get("note", 48)) t.connect("print", "escape:", t.get("key", 9)) t.connect("click", 1, t.get("j0_button", 4)) t.connect("click", 2, t.get("j0_button", 5)) t.connect("click", 3, t.get("j0_button", 6)) t.connect("mousemove", pair(transform(t.get("j0_axis", 2), ampMove), transform(t.get("j0_axis", 3), ampMove))) t.connect("key", 98, t.get("j0_axis", 4)) t.connect("print", primitive(repeat(t.get("tick"), transform(t.get("j0_axis", 1), ampMoveDiscon)), 0, 0, 127)) t.connect("note", 50, primitive(repeat(t.get("tick"), transform(t.get("j0_axis", 1), ampMoveDiscon)), 0, 0, 127))
def __init__(self): PM.pre_init(44100, -16, 1, 1024) PG.init() ###(Screen stuff)#### Globals.SCREEN.fill((255, 255, 255)) PD.set_caption("Master Chef's wicked adventure " + "with his ice cream buddies") ###(Declare interface)##### self.font = PF.SysFont('Arial', 25) #Win/Lose items self.end_time = 100 self.win_image = PI.load("FPGraphics/" + "specialEffects/UWIN.png").convert_alpha() self.lose_image = PI.load("FPGraphics/" + "specialEffects/ULOSE.png").convert_alpha() self.MAX_LEVEL = 4 self.MAX_STAGE = 2 #items self.pill_img = PI.load("FPGraphics/tiles/" + "lactasePill.png").convert_alpha() ######(Initialize objects on screen)#### ##draw map/background ##draw sprites self.character = Player(Globals.DELTA) self.INVINCIBILITY_TIME = Globals.DEFAULT_INVINCIBILITY self.player_group = PS.GroupSingle(self.character) # adding extra since cutscene bug deletes one # self.remainingEnemies = self.num_enemies #create icecream group self.icecream_list = PS.Group() self.burger_list = PS.Group() self.egg_list = PS.Group() self.lettuce_list = PS.Group() self.cupcake_list = PS.Group() self.enemy_list = PS.Group() # all enemies self.pad_list = PS.Group() self.trap_group = PS.Group() self.item_group = PS.Group() self.projectile_group = PS.Group() self.enemies = None #allsprites has all dirty sprites (player, enemies, traps, pads) self.allsprites = PS.LayeredDirty(self.trap_group, self.pad_list, self.item_group, self.player_group, self.icecream_list, self.burger_list, self.egg_list, self.lettuce_list, self.cupcake_list, self.projectile_group) #variables to be handled in change_level method self.objective = None self.objectiveBlit = True self.updated_obj = False self.map = None self.num_enemies = 0 self.background = None self.end_time = 100 self.end_image_position = (100, 178) self.block_group = None ####(Level variables)#### Globals.INVINCIBILITY_COUNT = 0 # player's invinicibility frame time #what kind of enemy by ID (-1 means no enemy) used for collisions self.enemy_ID = -1 #if true, tells map to redraw self.map_modified = False # self.level = 1 # self.stage = 1 self.level = 1 self.stage = 1 self.change_level(self.level, self.stage) self.burn_player = False ####Joystick######### self.joy = Joystick() self.use_joy = str(inbx.ask(Globals.SCREEN, 'Joystick? y/n')) self.score_health_background = PI.load( "FPGraphics/specialEffects/ScoreHealth.png").convert_alpha() self.items_table = PI.load( "FPGraphics/specialEffects/ItemsTable.png").convert_alpha()
def __init__(self, scene): super().__init__(scene) self.joystick = Joystick()
#from writer import UDP_Writer from joystick import Joystick import time #writer = UDP_Writer("127.0.0.1") joystick = Joystick(0) m = [0, 0, 0] while True: # get each axis strength s0, s1, s2, s3, brake = joystick.get_sticks() print(s0) print(s3) # convert to thrust inputs # vertical m[0] = s0 # left m[1] = s3 m[2] = brake msg = "" msg = msg + str(m[0]) + "," msg = msg + (str(m[1])) + "," msg = msg + (str(m[2])) # writer.send(msg) time.sleep(0.01)
for j in range(p.getNumJoints(boxId)): # p.changeDynamics(boxId, j, linearDamping=0, angularDamping=0) info = p.getJointInfo(boxId, j) print(info) jointName = info[1] jointType = info[2] jointIds.append(j) footFR_index = 3 footFL_index = 7 footBR_index = 11 footBL_index = 15 pybulletDebug = pybulletDebug() robotKinematics = robotKinematics() joystick = Joystick('/dev/input/event18') #need to specify the event route arduino = ArduinoSerial('/dev/ttyACM1') #need to specify the serial port trot = trotGait() #robot properties """initial safe position""" #angles targetAngs = np.array([ 0, np.pi / 4, -np.pi / 2, 0, #BR 0, np.pi / 4, -np.pi / 2, 0, #BL 0,
def main(): print("Initialising joystick...") joystick = Joystick() joystick.initJoystick() if (joystick.initalised): print("Setting up pygame window...") pygame.init() screen = pygame.display.set_mode((960, 720)) pygame.display.set_caption("OpenCV camera stream on Pygame") screen.fill([0, 0, 0]) noConnImage = pygame.image.load(r'.\No_Connection_Error.png') screen.blit(noConnImage, (0, 0)) print("Initialising connection to drone...") drone = Tello() # Send command message to initiate the drone drone.send_command("command") # Enable the stream drone.send_command("streamon") drone.receive_telemetry() stabilized = True takeoff = False startTime = time.time() # Start video capture drone.get_video() while True: drone_feed = pygame.surfarray.make_surface(drone.get_frame()) #Rotate image - Issue with OpenCV drone_feed = pygame.transform.rotate(drone_feed, 270) drone_feed = pygame.transform.flip(drone_feed, True, False) screen.blit(drone_feed, (0, 0)) currentTime = time.time() eventType = None axisX = None # Axis 0 = X axisY = None # Axis 1 = Y axisZ = None # Axis 2 = Rotational Z height = None # Axis 3 = Height for event in pygame.event.get(): axisX = joystick.getDevice().get_axis(0) axisY = joystick.getDevice().get_axis(1) axisZ = joystick.getDevice().get_axis(2) height = joystick.getDevice().get_axis(3) try: if (axisX != None or axisY != None or axisZ != None): if (axisX == None): axisX = 0 if (axisY == None): axisY = 0 if (axisZ == None): height = 0 if ((currentTime - startTime) >= DEBOUNCE): startTime = time.time() print("rc " + str(int(axisX * 100)) + " " + str(int(-1 * axisY * 100)) + " " + str(int(-1 * height * 100)) + " " + str(int(axisZ * 100))) drone.send_command("rc " + str(int(axisX * 100)) + " " + str(int(-1 * axisY * 100)) + " " + str(int(-1 * height * 100)) + " " + str(int(axisZ * 100))) stabilized = False else: if (not stabilized): drone.send_command("rc 0 0 0 0") stabilized = True if (joystick.getDevice().get_button(0) == 1): print("LAND") drone.send_command("land") if (joystick.getDevice().get_button(1) == 1): print("TAKEOFF") drone.send_command("takeoff") except KeyboardInterrupt: # print ('\n . . .\n') drone.send_command("land") break pygame.display.update() else: print('Joystick failed to initalise... Exiting...') exit(1)
def __init__(self, fps=1): # Call the parent class (Sprite) constructor PS.DirtySprite.__init__(self) self.image = PI.load("FPGraphics/MC/MCwalk/MCFront.png") \ .convert_alpha() self.rect = self.image.get_rect() self.rect_copy = self.rect self.rect.x = 100 self.rect.y = 100 self.face = 'd' self.load_images() # self.speed both determines the speed of the player & # ensures the the player moves at an integer distance # during play (arbitrary value) self.speed = 1 self.time = 0.0 self.frame = 0 self.got_key = False # will turn to True once you've run into the yellow block # collision conditions, if true, we will not move in that direction self.health = 20 self.dmg_count = 0 self.invincibility_frame = PI.load("FPGraphics/emptyImg.png") \ .convert_alpha() self.weapon = Weapon() self.moved = False self.interval = 0 self.modified_map = False self.banner = -1 #holds the ID of the sign that the player just read self.pill = False self.at_door_num = -1 # allows player to open door if player has key self.at_sign_num = -1 # if player is at a sign, allow sign msg to appear on space self.attack_pose = False #eating sound # self.eatEffect = PM.Sound("music/soundeffects/eating.mod") # self.eated = False self.EatR = PI.load("FPGraphics/MC/MCwalk/MCRightEat.png")\ .convert_alpha() self.EatL = PI.load("FPGraphics/MC/MCwalk/MCLeftEat.png")\ .convert_alpha() self.EatF = PI.load("FPGraphics/MC/MCwalk/MCFrontEat.png")\ .convert_alpha() self.EatB = PI.load("FPGraphics/MC/MCwalk/MCBackEat.png")\ .convert_alpha() self.items_of_killed = [] # Item Variables self.grab_item = False self.item = False self.item_img = None self.item_use_count = 0 self.item_type = 0 self.item_health = 0 #projectile movement self.pdx = 0 self.pdy = 0 self.player_items = [] self.player_traps = [] self.player_projectiles = [] self.can_eat = True self.eat_item = False #consider changing this for MC general img poses...? self.eat_time = 50 self.eat_timer = 0 self.effect_time = -1 self.change_invincibility = False # self.burger_capacity = random.randint(1, 15) self.burger_capacity = 1 self.enemy_ID = -1 self.can_attack = True ##joystick## self.joy = Joystick() self.joyOn = False # self.mvJoy = (0, 0) self.mvD = False self.mvR = False self.mvL = False self.mvU = False
import time import numpy as np from joystick import Joystick from pan_tilt import PanTilt if __name__ == "__main__": j = Joystick() # These values are specific to individual motors, change them for yours! p = PanTilt([140, 385, 630], [240, 450, 670]) print('Targeting Demo!\n') print('Use joystick to move pan-tilt') X_SPEED = 0.01 Y_SPEED = -0.01 # Invert Y x, y = 0, 0 p.pan(x) p.tilt(y) while True: x_ctrl, y_ctrl = j.state x = np.clip(x + X_SPEED * x_ctrl, -1, 1) y = np.clip(y + Y_SPEED * y_ctrl, -1, 1) p.pan(x) p.tilt(y) time.sleep(0.01)
from joystick import Joystick # defines for what serial port motor interface is connected to + baud rate motor_com_port = '/dev/ttyACM0' sensor_com_port = '/dev/ttyACM1' baud = 9600 motor_ser = serial.Serial(motor_com_port, baud) motor_ser.close() motor_ser.open() sensor_ser = serial.Serial(sensor_com_port, baud) sensor_ser.close() sensor_ser.open() joystick = Joystick() prev_dir = -1 prev_speed = -1 while True: #speed = int(input("speed:")) #print("speed:", speed) #dir_input = int(input("direction:")) #direction = 0 #if dir_input == 1: # direction = 1 #elif dir_input == 0: # direction = 0 #print("dir:",direction)
print(str(err)) sys.exit(2) host = '127.0.0.1' port = 6666 device = "/dev/input/js0" for current_argument, current_value in arguments: if current_argument in ("-a", "--ip"): host = current_value elif current_argument in ("-p", "--port"): port = int(current_value) elif current_argument in ("-d", "--device"): device = current_value js1 = Joystick(device) js1.openDevice() deviceName = js1.getDeviceName() num_axes = js1.getNumberAxes() num_buttons = js1.getNumberButtons() axis_map = js1.getAxisMap() button_map = js1.getButtonMap() axis_mapHex = js1.getAxisMapHex() button_mapHex = js1.getButtonMapHex() deviceData = { "deviceName": deviceName, "num_axes": num_axes, "num_buttons": num_buttons, "axis_mapHex": axis_mapHex, "button_mapHex": button_mapHex