js.cpp
Go to the documentation of this file.
1 #include <iostream>
2 #include <fcntl.h>
3 #include <sys/ioctl.h>
4 #include <linux/joystick.h>
5 #include <unistd.h>
6 #include <errno.h>
7 #include <cstdio>
8 #include "js.h"
9 
10 joystick::joystick(const char *dev) : m_fd(-1)
11 {
12  if ((m_fd = open(dev, O_RDONLY|O_NONBLOCK)) < 0){
13  perror("open");
14  return;
15  }
16 
17  char number_of_axes;
18  ioctl(m_fd, JSIOCGAXES, &number_of_axes );
19  std::cout << "number_of_axes = " << (int)number_of_axes << std::endl;
20  m_axes.resize(number_of_axes);
21 
22  char number_of_buttons;
23  ioctl(m_fd, JSIOCGBUTTONS, &number_of_buttons );
24  std::cout << "number_of_buttons = " << (int)number_of_buttons << std::endl;
25  m_buttons.resize(number_of_buttons);
26 
27  // read initial state
28  for (int i=0; i<number_of_axes+number_of_buttons; i++){
29  readEvent();
30  }
31 }
32 
34 {
35  if (m_fd >= 0){
36  close(m_fd);
37  }
38 }
39 
41 {
42  js_event e;
43  float fval;
44  const float MAX_VALUE_16BIT = 32767.0f;
45 
46  // read data of joystick
47  int rdlen = read(m_fd, &e, sizeof(js_event) );
48 
49  // error
50  if( rdlen <= 0 ) {
51  if( errno == EAGAIN ){
52 
53  }
54  //std::cout<< "event queue is empty"<<std::endl;
55  return false;
56  } else if( rdlen < (int)sizeof(js_event) ) {
57  std::cout<<"ERROR: read"<<std::endl;
58  return false;
59  }else{
60  if( e.type & JS_EVENT_AXIS ) {
61  // axis
62  // normalize value (-1.0〜1.0)
63  fval = (float)e.value/MAX_VALUE_16BIT;
64  //printf("%d:%x\n", e.number, e.value);
65  m_axes[e.number] = fval;
66  }else{
67  // button
68  m_buttons[e.number] = e.value==0 ? false : true;
69  }
70  }
71  return true;
72 }
std::vector< bool > m_buttons
Definition: js.h:21
int m_fd
Definition: js.h:19
bool readEvent()
Definition: js.cpp:40
png_uint_32 i
joystick(const char *dev)
Definition: js.cpp:10
~joystick()
Definition: js.cpp:33
typedef int
std::vector< float > m_axes
Definition: js.h:20


hrpsys
Author(s): AIST, Fumio Kanehiro
autogenerated on Thu May 6 2021 02:41:50