Ejemplo n.º 1
0
    def event(self, event):
        if self.confirmation:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    self.confirmed = (self.confirmed - 1) % 2
                elif event.key == pygame.K_RIGHT:
                    self.confirmed = (self.confirmed + 1) % 2
                if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    if self.confirmed:
                        globes.Globals.HIGHSCORES.clear_file()
                        self.confirmation = False
                    else:
                        self.confirmation = False
        else:
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                globes.Globals.STATE = menu.Menu(True)
            if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
                self.option = (self.option - 1) % 4
            if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
                self.option = (self.option + 1) % 4

            if event.type == pygame.KEYDOWN and \
                    (event.key == pygame.K_SPACE or
                     event.key == pygame.K_RETURN):
                if self.option == 0:
                    self.confirmation = True
                elif self.option == 1:
                    globes.Globals.STATE = joystick.Joystick()
                elif self.option == 2:
                    globes.Globals.STATE = volume.Volume(True)
                if self.option == 3:
                    globes.Globals.STATE = menu.Menu(True)
def main():
    rospy.init_node('simulate_dynamics')

    dt = 0.05
    Hz = int(1 / dt)
    stateDim = 7
    inputDim = 2
    joy = joystick.Joystick()
    sim = SimulateStep(stateDim, inputDim, dt)
    sim.namespace = rospy.get_namespace()
    # sim.imageLoad('/home/sw/catkin_ws/src/autorally/autorally_control/src/path_integral/params/maps/kaist_costmap/waypoint_image3.png')
    clock = pygame.time.Clock()
    r = rospy.Rate(Hz)
    while not rospy.is_shutdown():
        joy.get_value()
        inputs = np.array([joy.axis[3], -joy.axis[1]])
        sim.toggle = joy.toggle
        sim.one_step_forward(inputs)
        # clock.tick(Hz)
        # sim.render2D()

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        r.sleep()
Ejemplo n.º 3
0
def main():

    drone = tello.Tello('', 8889)
    controller = joystick.Joystick()
    vplayer = TelloUI(drone, controller, "./img/")

    # start the Tkinter mainloop
    vplayer.root.mainloop()
Ejemplo n.º 4
0
    def getJoystick(self, id):
        """Get a joystick object.

        A dummy joystick object is returned if there is no joystick
        with the specified id.
        """
        if id in self._joysticks:
            return self._joysticks[id]
        else:
            return joystick.Joystick(id=id, name="Dummy-Joystick")
Ejemplo n.º 5
0
Archivo: ps4.py Proyecto: LacombeJ/Arlo
    def create(self):
        self._joystick = joystick.Joystick()

        created = self._joystick.create()
        if not created:
            return False

        self._joystick.start()

        return True
Ejemplo n.º 6
0
def from_remote_nunchuk(raw_x, raw_y, raw_z, raw_c, recv_time):
    joy_x, joy_y = _scale_joystick_xy(int(raw_x), int(raw_y))
    magnitude, angle = _get_joystick_vector(joy_x, joy_y)
    button_z = False
    if raw_z == '1':
        button_z = True
    button_c = False
    if raw_c == '1':
        button_c = True
    return joystick.Joystick(magnitude=magnitude,
                             angle=angle,
                             button_z=button_z,
                             button_c=button_c,
                             recv_time=recv_time)
Ejemplo n.º 7
0
def main():
	GPIO.setmode(GPIO.BCM)

	FREQ = 50
	PULSE_MIN = 100 * 0.001 / (1.0 / FREQ)	# 1ms as a % of period
	PULSE_MAX = 100 * 0.002 / (1.0 / FREQ)	# 2ms as a % of period


	def signed_to_duty(v):
		assert -1.0 <= v and v <= 1.0
		return PULSE_MIN + (PULSE_MAX - PULSE_MIN) * (v + 1.0) / 2.0
	
	def pwm_pin(pin, init_val=0.0):
		GPIO.setup(pin, GPIO.OUT)
		rv = GPIO.PWM(pin, FREQ)
		rv.start(signed_to_duty(init_val))
		return rv
	
	# - Configure pins
	pin_throttle = pwm_pin(18)
	pin_steer    = pwm_pin(17)
	pin_mode     = pwm_pin(23)
	
	# Open the joystick and watch for updates
	js = joystick.Joystick('/dev/input/js0')
	for u in js.peek_updates():
		if u.name == "x":
			pass
		elif u.name == "y":
			pass
		elif u.name == "z":
			new_duty = signed_to_duty(u.value)
			print "STEER: %.2f       \r" % (new_duty,), ; sys.stdout.flush()
			pin_steer.ChangeDutyCycle( new_duty )
		elif u.name == "rz":
			new_duty = signed_to_duty(-u.value)
			print "THROTTLE: %.2f    \r" % (new_duty,), ; sys.stdout.flush()
			pin_throttle.ChangeDutyCycle( new_duty )
			pass
		else:
			print u
			continue
	pass
Ejemplo n.º 8
0
    def setup(self):
        self.map = self.world.get_map()

        pygame.init()

        self.size = self.map.get_size().get_pygame().size
        self.screen = pygame.display.set_mode(self.size)

        self.font = pygame.font.Font(None, 20)

        if pygame.joystick.get_count() == 0:
            print "No joystick! Aborting...."
            sys.exit(0)
        else:
            print 'Number of Joysticks:', pygame.joystick.get_count()

        # Callback dictionary for joystick event handling.
        joystick_callbacks = {
                'direction' : self.world.get_sight(0).accelerate,
                'shoot' : self.world.get_sight(0).shoot }

        self.joystick = joystick.Joystick(joystick_callbacks)
Ejemplo n.º 9
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import joystick

J = joystick.Joystick()
J.open("/dev/input/js0")
print(J)
time.sleep(2)
J.start()

J.onButtonClick('trigger', lambda x: print('trigger', x))
J.onButtonClick('thumb', lambda x: print('thumb', x))
J.onButtonClick("thumb2", lambda x: print("thumb2", x))
J.onButtonClick("top", lambda x: print("top", x))
J.onButtonClick("top2", lambda x: print("top2", x))

while True:
    print(J.axis['z'])
    time.sleep(0.05)
Ejemplo n.º 10
0
 def __init__(self, root, queue, endCommand):
     self.queue = queue
     # Set up the GUI
     self.j = joystick.Joystick(parent=root)
Ejemplo n.º 11
0
    def __init__(self, parent, config, enable_mqtt=True):
        tk.Frame.__init__(self, parent)
        self.config = config

        # Setup the Comm and Joysticks
        self.setup_mqtt(enable_mqtt)
        self.bot_status0 = self.bot_status1 = ("", 0
                                               )  # Last two bot status msg
        # Get joystick devices
        self.joysticks = []
        if self.config.number_of_joysticks < 1 or self.config.number_of_joysticks > 2:
            print("Invalid number of joysticks (%d). Only 1 or 2 allowed." %
                  self.config.number_of_joysticks)
            print("Please fix configuration file.")
            sys.exit()
        if self.config.joystick_port_1 == "Logitech":
            self.joysticks.append(joystick.Joystick(LOGITECH, 0))
        elif self.config.joystick_port_1 == "XBox":
            self.joysticks.append(joystick.Joystick(XBOX, 0))
        else:
            print(
                "Invalid joystick on port 1 (%s). Valid joysticks are: Logitech or XBox."
                % self.config.joystick_port_1)
            print("Please fix configuration file.")
            sys.exit()
        if self.config.number_of_joysticks == 2:
            if self.config.joystick_port_2 == "Logitech":
                instance = 0
                if self.config.joystick_port_1 == "Logitech": instance = 1
                self.joysticks.append(joystick.Joystick(LOGITECH, instance))
            elif self.config.joystick_port_2 == "XBox":
                instance = 0
                if self.config.joystick_port_1 == "XBox": instance = 1
                self.joysticks.append(joystick.Joystick(XBOX, instance))
            else:
                print(
                    "Invalid joystick on port 2 (%s). Valid joysticks are: Logitech or XBox."
                    % self.config.joystick_port_2)
                print("Please fix configuration file.")
                sys.exit()

        # Setup runtime variables...
        self.ping_setup()
        self.last_cmd_send_time = time.monotonic() - 100.0
        self.last_arduino_status = time.monotonic() - 100.0
        self.last_arduino_ui_update = time.monotonic() - 100.0
        self.arduino_data = None
        self.arduino_reset_flag = False
        self.run_loop_cnt = 0
        self.quitbackgroundtasks = False
        self.bg_count = 0
        self.last_btns = [[], []]
        self.last_axes = [[], []]
        self.last_pov = [(0, 0), (0, 0)]

        # Setup the GUI...
        self.titlefont = tkFont.Font(family="Copperplate Gothic Bold", size=24)
        self.namefont = tkFont.Font(family="Copperplate Gothic Light", size=20)
        self.titlelabel = tk.Label(self,
                                   text=self.config.title,
                                   anchor="center",
                                   font=self.titlefont)
        self.namelabel = tk.Label(self,
                                  text=self.config.teamname,
                                  anchor="center",
                                  font=self.namefont)
        self.hwstatus = hardwarestatuswidget.HardwareStatusWidget(self)
        self.gameclock = gameclockwidget.GameClockWidget(self)
        self.commstatus = commstatuswidget.CommStatusWidget(self)
        self.botstatus = botstatuswidget.BotStatusWidget(
            self, reset_callback=self.do_arduino_reset)
        self.arduinostatus = arduinostatuswidget.ArduinoStatusWidget(self)
        self.joystick_widgets = []
        for joy in self.joysticks:
            if joy.get_name() == LOGITECH:
                self.joystick_widgets.append(
                    joystick_logitech.JoystickWidget(self))
            elif joy.get_name() == XBOX:
                self.joystick_widgets.append(
                    joystick_xbox.JoystickWidget(self))
            else:
                print(
                    "Unknown joystick detected. Defaulting to Logitech widget."
                )
                self.joystick_widgets.append(
                    joystick_logitech.JoystickWidget(self))
        if len(self.joystick_widgets) < 1:
            raise ("Internal Consistancy Check Error.  Programming Problem.")
        if self.config.number_of_joysticks == 1:
            self.layout_for_one_joystick()
        elif self.config.number_of_joysticks == 2:
            self.layout_for_two_joysticks()
        else:
            print("Invalid Number of Joysticks!  Fix configuration file.")
            sys.exit()
        self.set_mqtt_fields_off()
Ejemplo n.º 12
0
import joystick
import vulcan
import eventprocessor
import logging
import argparse
import sys


def main(processor):
    processor.run()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Control program for Nerf Vulcan")
    parser.add_argument("--vulcan",
                        default="/dev/ttyACM0",
                        help="Path to vulcan ardiuno")
    parser.add_argument("--joystick",
                        default="/dev/input/js0",
                        help="Path to joystick")
    args = parser.parse_args()

    new_vulcan = vulcan.Vulcan(args.vulcan)
    new_joystick = joystick.Joystick(args.joystick)

    processor = eventprocessor.EventProcessor(new_joystick, new_vulcan)

    main(processor)
Ejemplo n.º 13
0
__author__ = 'zackory'

import time
import servo
import joystick

joy = joystick.Joystick(0)

servo1 = servo.Servo(17)
servo2 = servo.Servo(18)
servo3 = servo.Servo(22)
servo4 = servo.Servo(23)
mastServo = servo.Servo(24, 300)

done = False
while not done:
    joy.processEvents()
    done = joy.get(joy.RBumper)

    # Update servo speed based on joystick

    LThumbY = joy.get(joy.LThumbY)
    if LThumbY <= -0.1 or LThumbY >= 0.1:
        # Update head position by moving center mast
        mastServo.setPosition(LThumbY)
    else:
        mastServo.setPosition(0)

    RThumbX = joy.get(joy.RThumbX)
    RThumbY = joy.get(joy.RThumbY)
    if RThumbX <= -0.1 or RThumbX >= 0.1:
Ejemplo n.º 14
0
    serial = [i2c(port=1, address=0x3C), i2c(port=1, address=0x3D)]

    try:
        pad_display = pad_display.PadDisplay(ssd1306(serial[1]))
    except DeviceNotFoundError:
        pad_display = pad_display.PadDisplay(None)
    pad_handler = pad_handler.PadHandler(display=pad_display)

    try:
        status_display = statusdisplay.StatusDisplay(ssd1306(serial[0]))
    except DeviceNotFoundError:
        status_display = statusdisplay.StatusDisplay(None)

    pygame.init()
    joystick = joystick.Joystick(bHandler, pad_handler)
    joystick.init()

    while True:
        s = wait_for_server()
        print("Connected to camera controller")
        stop_all_axis(s)

        # configure axis acceleration -> 0 - 100 per axis
        s.sendall(bytearray([0x01, 0xB0, 70, 40]))

        # TODO: add mechanism to support multiple cams
        cam = statusdisplay.CameraInfo(1)
        status_display.update(cam, joystick.max_speed)
        pad_handler.startup()
Ejemplo n.º 15
0
import serial
import threading
import numpy as np
from rx import Observable
from rx.subjects import Subject
from rx.concurrency import NewThreadScheduler

FEEDRATE = 400  # mm / minute
MAX_REACH = 0.2  # mm / feedrate
MIN_NORM = 0.2

device_fn = sys.argv[1] if len(
    sys.argv) > 1 else joystick.Joystick.available_sticks()[0]
print("Using input device: {0}".format(device_fn))

in_stick = joystick.Joystick(device_fn)
tty = serial.Serial('/dev/ttyUSB0', 250000)


def send_gcode(s):
    tty.flushInput()
    tty.write(s + b'\n')
    return tty.readline().strip()


def poll_joystick(_):
    poll_result = in_stick.poll()
    x, y = None, None
    if poll_result.changed_axis is not None:
        axis = poll_result.changed_axis
        if axis.number == 0: