js.cpp
Go to the documentation of this file.
00001 #include <iostream>
00002 #include <fcntl.h>
00003 #include <sys/ioctl.h>
00004 #include <linux/joystick.h>
00005 #include <unistd.h>
00006 #include <errno.h>
00007 #include <cstdio>
00008 #include "js.h"
00009 
00010 joystick::joystick(const char *dev) : m_fd(-1)
00011 {
00012     if ((m_fd = open(dev, O_RDONLY|O_NONBLOCK)) < 0){
00013         perror("open");
00014         return;
00015     }
00016 
00017     char number_of_axes;
00018     ioctl(m_fd, JSIOCGAXES, &number_of_axes );
00019     std::cout << "number_of_axes = " << (int)number_of_axes << std::endl;
00020     m_axes.resize(number_of_axes);
00021 
00022     char number_of_buttons;
00023     ioctl(m_fd, JSIOCGBUTTONS, &number_of_buttons );
00024     std::cout << "number_of_buttons = " << (int)number_of_buttons << std::endl;
00025     m_buttons.resize(number_of_buttons);
00026 
00027     // read initial state
00028     for (int i=0; i<number_of_axes+number_of_buttons; i++){
00029         readEvent();
00030     }
00031 }
00032 
00033 joystick::~joystick()
00034 {
00035     if (m_fd >= 0){
00036         close(m_fd);
00037     }
00038 }
00039 
00040 bool joystick::readEvent()
00041 {
00042     js_event e;
00043     float       fval;
00044     const float MAX_VALUE_16BIT = 32767.0f;
00045     
00046     // read data of joystick 
00047     int rdlen = read(m_fd, &e, sizeof(js_event) );
00048     
00049     // error
00050     if( rdlen <= 0 ) {
00051         if( errno == EAGAIN ){
00052             
00053         }               
00054         //std::cout<< "event queue is empty"<<std::endl;
00055         return false;
00056     } else if( rdlen < (int)sizeof(js_event) ) {
00057         std::cout<<"ERROR: read"<<std::endl;
00058         return false;
00059     }else{ 
00060         if( e.type & JS_EVENT_AXIS ) {
00061             // axis
00062             // normalize value (-1.0〜1.0)
00063             fval = (float)e.value/MAX_VALUE_16BIT;
00064             //printf("%d:%x\n", e.number, e.value);
00065             m_axes[e.number] = fval;
00066         }else{
00067             // button 
00068             m_buttons[e.number] = e.value==0 ? false : true;
00069         }
00070     }
00071     return true;
00072 }


hrpsys
Author(s): AIST, Fumio Kanehiro
autogenerated on Wed May 15 2019 05:02:18