martes, 15 de marzo de 2016

Utilizar GUI gmoccapy_lcd7 con Control de Xbox 360.

Se necesita instalar unas librerías para que la Beaglebone Black pueda detectar el control del Xbox 360.

//Instalar xboxdrv, para simular el control de Xbox 360 en Linux.

sudo apt-get install xboxdrv

//Instalar evtest, para visualizar los eventos generados por cada uno de los botones del
//control de Xbox 360

sudo apt-get install evtest

//Al finalizar se debe correr el programa de xboxdrv para detectar el control de Xbox 360

sudo xboxdrv --silent --detach-kernel-driver


//Identificar el control de xbox 360
nano /proc/bus/input/devices
//Identificar el tipo de evento (js0 event1)
ctrl+X


//Al ejecutar el siguiente comando sale cuales son los tipos de eventos soportados e ira
// cambiando el valor de acuerdo a los botones que se hayan presionado. 

sudo evtest /dev/input/event1

ctrl+C


Dar permisos para poder acceder a los eventos del control desde machinekit.

//90-Xbox.rules es el nombre que le he dado al archivo, pero se puede usar cualquier
//nombre (myname.rules).

sudo nano /etc/udev/rules.d/90-Xbox.rules

//Copiar esto en el archivo

SUBSYSTEM=="input", GROUP="plugdev", MODE=="0660"

//Salir del editor
ctrl+O
ctrl+X

//Reiniciar las reglas para que inicie 90-Xbox.rules con el cambio realizado.

sudo udevadm trigger

//Comprobar que los eventos (dispositivos) se han cargado

sudo udevadm trigger





Comprobar control de Xbox 360 con halrun.

//halrun

halrun

//Iniciar el evento del control con halrun, en este caso el control del Xbox 360
// se puede usar con cualquier nombre con el que haya reconocido. Siendo el nombre
// reconocido "Xbox Gamepad (userspace driver)" se puedes usar Xbox o Gamepad.

loadusr -W hal_input -KRAL Gamepad

//Mantener pulsado cualquier botón, en este caso se ha pulsado el botón A y al 
// correr show pin se visualizarán los cambios.

show pin 

//Para salir
exit



AL pulsar el boton A del control de Xbox 360 cambia a TRUE input.0.btn-a

Nota: Realizar el paso de pulsar cualquier botón y visualizar, para poder identificar a que botón pertenece cada evento "input.0...".



Integrar archivo joypad.hal a Gui gmoccapy_lcd7.

El archivo .hal fue descargado de LinuxCNC Joypads y se ha realizado algunas modificaciones para adaptarlo al control de Xbox 360.

Probar el funcionamiento del control, ejecutando:

sudo evtest /dev/input/event1

En este caso la palanca izquierda del mando, reacciona cuando se pulsa a la izquierda con valores negativos y a la derecha con valores positivos; pero cuando se mueve de arriba a bajo funciona de forma inversa, dando valores negativos cuando se pulsa hacia arriba y valores positivos pulsando hacia abajo. Algo parecido ocurre en la palanca derecha del mando.


Componente joyhandle.
Código del Componente joyhandle.

Se inicializa el componente.

loadusr -W hal_input -KRAL Xbox

# load joyhandle component and attach to threads (in this case 3 instances)
loadrt joyhandle count=3
addf joyhandle.0 servo-thread   # x
addf joyhandle.1 servo-thread   # y
addf joyhandle.2 servo-thread   # z

Se configura la velocidad (máxima). Los valores de power varían de acuerdo a la sensibilidad, al aumentarlo se recomienda aumentar el valor de de deadband (0-0.99). La escala al ser negativa, invierte la dirección; al tener valores menores a 1 disminuye la velocidad y viceversa.

setp halui.jog-speed   1500 # desired maximum jog speed mm/min

# --Start-- These parameters ara used to set up joyhandle
setp halui.jog-deadband   0. # important: default value is 0.2, that would override joyhandle.deadband
setp joyhandle.0.power 3. # select nonlinearity to handele low jog values
setp joyhandle.1.power 3.
setp joyhandle.2.power 4. # in my case the z-axis is set up more sensitive
setp joyhandle.0.deadband 0.1
setp joyhandle.1.deadband 0.1
setp joyhandle.2.deadband 0.1
setp joyhandle.0.scale  1. 
setp joyhandle.1.scale -1. # negative values invert jogging
setp joyhandle.2.scale -0.75    # invert jogging and the z-axis is scaled to lower speed
# --End--

Se configura el componente joyhandle con las palancas del mando.

# connect hal_input to halui via joyhandle (in case use your own axes-names)

#left stick -> left-rigth (X jogging)
net velX input.0.abs-x-position => joyhandle.0.in
net velXout joyhandle.0.out => halui.jog.0.analog
#left stick -> up-down (Y jogging)
net velY input.0.abs-y-position => joyhandle.1.in
net velYout joyhandle.1.out => halui.jog.1.analog
#rigth stick -> up-down (Z jogging)
net velZ input.0.abs-ry-position => joyhandle.2.in
net velZout joyhandle.2.out => halui.jog.2.analog 

Se configura los botones del mando a las acciones que se requiera dar. Importate revisar la guía de comandos de la herramienta halui (HAL User Interface).

# [BUTTON-SAMPLES] use your own joypad pin-names
#One button sample
net spindleOff input.0.btn-x => halui.spindle.stop
net spindleOn input.0.btn-y => halui.spindle.start
net estopActivate input.0.btn-start => halui.estop.activate
net estopNotActivate input.0.btn-start-not => halui.estop.reset

#    Hal configuration file to move a cnc machine using a joypad using joyhandle component

#    Copyright 2008 Paul Willutzki <paul[at]willutzki[dot]de>

#    Licence: GPL

#    Version 3

#    This Hal-File needs the joyhandle component.
#    This uses the following formula for a non linear joypad movements:
#    y = (scale * (a*x^power + b*x)) + offset  
#
#    The parameters a and b are adjusted in such a way, that the function starts at (deadband,offset) and ends at (1,scale+offset).
#    Negative values will be treated point symetrically to origin. Values -deadband < x < +deadband will be set to zero.
#    Values x > 1 and x < -1 will be skipped to +-scale+offset. Negative scale values invert the movement.
#    With power one can adjust the nonlinearity (default = 2).
#    Default for deadband is 0.
#    Valid values are: power >= 1.0 (reasonable values are 1.x .. 4-5), 0 <= deadband < 0.99 (reasonable 0.1). If you use high deadbands (>0.5) you need higher power values to smoothly start at (deadband,offset). 
#    The additional offset component can be set in special cases (default = 0).
#    All values can be adjusted for each instance (joypad axis) separately.

#    Please take also a look at the manpages for johandle.

#    Insert the following lines in the INI-File (section [HAL])
#    HALUI = halui
#    HALFILE = joypad_V3.hal

# Load the hal_input component that creates pins for axes and buttons
# See man hal_input for details and finding input devices
loadusr -W hal_input -KRAL Xbox

# load joyhandle component and attach to threads (in this case 3 instances)
loadrt joyhandle count=3
addf joyhandle.0 servo-thread   # x
addf joyhandle.1 servo-thread   # y
addf joyhandle.2 servo-thread   # z

setp halui.jog-speed   1500 # desired maximum jog speed mm/min

# --Start-- These parameters ara used to set up joyhandle
setp halui.jog-deadband   0. # important: default value is 0.2, that would override joyhandle.deadband
setp joyhandle.0.power 3. # select nonlinearity to handele low jog values
setp joyhandle.1.power 3.
setp joyhandle.2.power 4. # in my case the z-axis is set up more sensitive
setp joyhandle.0.deadband 0.1
setp joyhandle.1.deadband 0.1
setp joyhandle.2.deadband 0.1
setp joyhandle.0.scale 1. 
setp joyhandle.1.scale -1. # negative values invert jogging
setp joyhandle.2.scale -0.75    # in my case the z-axis is scaled to lower speed
# --End--

# connect hal_input to halui via joyhandle (in case use your own axes-names)

#left stick -> left-rigth (X jogging)
net velX input.0.abs-x-position => joyhandle.0.in
net velXout joyhandle.0.out => halui.jog.0.analog
#left stick -> up-down (Y jogging)
net velY input.0.abs-y-position => joyhandle.1.in
net velYout joyhandle.1.out => halui.jog.1.analog
#rigth stick -> up-down (Z jogging)
net velZ input.0.abs-ry-position => joyhandle.2.in
net velZout joyhandle.2.out => halui.jog.2.analog


# connect hal_joypad directly to halui without joyhandle (in case use your own axes-names)
#net velX joypad.axis.3 => halui.jog.0.analog
#net velY joypad.axis.2 => halui.jog.1.analog
#net velZ joypad.axis.1 => halui.jog.2.analog


# [BUTTON-SAMPLES] use your own joypad pin-names
#One button sample
net spindleOff       input.0.btn-x                => halui.spindle.stop
net spindleF         input.0.btn-a                => halui.spindle.forward
net spindleR         input.0.btn-b                => halui.spindle.reverse
net spindleSlow      input.0.abs-hat0x-is-neg     => halui.spindle.decrease
net spindleFast      input.0.abs-hat0x-is-pos     => halui.spindle.increase
net homeAllAxis      input.0.btn-mode             => halui.home-all
net increasePosA     input.0.btn-tr               => halui.jog.3.plus
net decreasePosA     input.0.btn-tl               => halui.jog.3.minus
net estopActivate    input.0.btn-start            => halui.estop.activate
net estopNotActivate input.0.btn-start-not        => halui.estop.reset

Para visualizar el incremento y decremento de la velocidad del husillo, se va utilizar el archivo spindle_sim.hal de la configuración de gmoccapy y en el archivo postgui.hal, se va unir las señales incluyendo las que pertenecen a gmoccapy.

#archivo potgui.hal
loadrt abs names=abs_spindle_feedback
addf abs_spindle_feedback servo-thread

net spindle-speed-limited  =>  abs_spindle_feedback.in
net spindle-abs  abs_spindle_feedback.out  =>  gmoccapy.spindle_feedback_bar

net spindle-at-speed      gmoccapy.spindle_at_speed_led
net boton-info       input.0.btn-select           => gmoccapy.v-button-7

Si se desea se podrían reemplazar las señales de halui con las de gmoccapy.




Parte del código del archivo gmoccapy encargado de conectar los botones verticales. No hay que cambiar nada solo es una breve explicación de como funcionan los botones verticales y horizontales de gmoccapy.

Se guardan los botónes en la variable v_tabs y se da un número a cada uno para poder buscarlos.

self.v_tabs = [(0, "tbtn_estop"), (1, "tbtn_on"), (2, "rbt_manual"), (3, "rbt_mdi"),
                       (4, "rbt_auto"), (5, "tbtn_setup"), (6, "tbtn_user_tabs"), (7, "tbtn_info")
                      ]


Se define la función que se encarga de detectar si se ha presionado algún botón.

def _on_v_button_changed(self, pin):
        self._add_alarm_entry("got v_button_signal %s" % pin.name)
        if not pin.get():
            return
        btn = str(pin.name)
        nr = int(btn[-1])
        tab = self.v_tabs # see in the __init__ section for the declaration of self.tabs
        button = None
        for index in tab:
            if int(index[0]) == nr:
                # this is the name of the button
                button = index[1]
        if button:
            # only emit a signal if the button is sensitive, otherwise
            # running actions may be interupted
            if self.widgets[button].get_sensitive() == False:
                print("%s not_sensitive" % button)
                self._add_alarm_entry("%s not_sensitive" % button)
                return
            button_pressed_list = ("rbt_manual", "rbt_mdi", "rbt_auto")
            button_toggled_list = ("tbtn_setup")
            if button in button_pressed_list:
                self.widgets[button].set_active(True)
                self.widgets[button].emit("pressed")
            elif button in button_toggled_list:
                self.widgets[button].set_active(not self.widgets[button].get_active())
            else:
                self.widgets[button].emit("clicked")
        else:
            print("No button found in v_tabs from %s" % pin.name)
            self._add_alarm_entry("No button found in v_tabs from %s" % pin.name)

Se encarga de crear las conexiones hal para poder usar los botones en archivos .hal.

     # generate the vertical button pins
        for v_button in range(0, 8):
            pin = self.halcomp.newpin("v-button-%s" % v_button, hal.HAL_BIT, hal.HAL_IN)
            hal_glib.GPin(pin).connect("value_changed", self._on_v_button_changed)

Nota: Se actualizado la conexión del botón de info en gmoccapy_lcd7 para que se pueda controlar con pulsadores.

El botón start del control de Xbox 360 simula el comportamiento de un botón de emergencia. Al tenerlo pulsado se activa estop, caso contrario mantiene activada la máquina.



El botón Guide (btn-mode), se encarga de mover los ejes al origen. Debe estar configurado el archivo .ini para hacer un "home-all" a los ejes que se quiera.


El botón Back (btn-mode), activa y desactiva el toggled button de info.



Activa, desactiva y cambia la dirección el husillo.






Aumenta y disminuye la velocidad del husillo.



Incrementa y decrementa la posición del eje A.







Movimiento de ejes X, Y y Z.






Descargar archivos


MF5-LCD7-mill