Câmbio H-Sifther Standalone

Olá para todos.

Sou iniciante e preciso de ajuda quanto a programação para meu "unojoy".

O problema é o seguinte:

Eu preciso que a partir de uma leitura analógica seja acionado um pino digital , segue exemplo:

Quando o eixo x for 303 e o eixo y for 886 seja acionado um botão digital 1 .

preciso fazer isso com valores diferentes para que sejam acionados 12 botões diferentes.

Tenho um câmbio H-SHIFTER com 2 potenciômetros e um botão de profundidade e cada posição dessas 3 entradas representa uma marcha. Todavia preciso alterar isso no Sketch do big joy para que seja possível este reconhecimento e que cada combinação seja reconhecida de forma adequada.

Em anexo segue configuração atual do câmbio. O eixo x é reconhecido como direcional , variando da esquerda pra direita e o eixo Y como profundidade , variando de norte à sul.

Alguém pode me ajudar?

Agradeço desde agora .

Não sei se percebi bem o que é pretendido (estou em Portugal, por isso nem sabia o que era um H-SHIFTER).
Você tem uma alavanca de mudanças (H-SHIFTER) para um jogo, mas ela envia o valor analógico X e Y para o PC em cada mudança. Como isso não funciona no jogo que você quer jogar, quer alterar isso através do "unojoy" (que eu também não sabia o que era, mas entretanto já fui pesquisar) para que em cada mudança indique (e envie para o PC) que está premido um botão digital. É isso?

Olá.
Isso mesmo, muito obrigado pela atenção.

O que preciso é que os valores dos eixos x e y, comandandos por potenciometros, seja convertido em digital como se estivesse pressionando um push botton.

Utilizo o código base (sterck) do unojoy. Neste código o meu trocador de marcha é reconhecido como eixo x e y.

Poderia me ajudar?

Não me parece muito complicado. Pode disponibilizar o código que tem neste momento e os valores X e Y das várias marchas?

Olá, muito obrigado pela atenção e peço desculpa pela demora. Assim que estiver em casa mandarei o código.

Este é o código base do UnoJoy

//Variável que armazena a posição lida
//nos eixos do joystick
int joystick = 0;
int eixoX = A1;
int eixoY = A2;
int eixoZ = 2;
int bot1 = 8;
int bot2 = 9;
int bot3 = 10;
int bot4 = 11;
int led = 7;
void setup() {
//Definindo eixoZ como um pino de entrada
pinMode(eixoZ, INPUT);
pinMode(bot1, INPUT);
pinMode(bot2, INPUT);
pinMode(bot3, INPUT);
pinMode(bot4, INPUT);
pinMode(led, OUTPUT);

//Ativando o Serial Monitor que exibirá os
//valores lidos no Joystick
Serial.begin(9600);
}

void loop() {
//Lê o valor do eixoX
joystick = analogRead(eixoX);

//imprime o valor do eixoX
Serial.print(" X=");
Serial.print(joystick);

//Lê o valor do eixoY
joystick = analogRead(eixoY);

//imprime o valor do eixoY
Serial.print(" Y=");
Serial.print(joystick);

joystick = digitalRead(eixoZ);
Serial.print(" Z=");
Serial.println(joystick);

delay(100);

}

Estas aqui são as posições refentes à cada marcha:

Neutro:

X:> 510 < 550
Y:> 430 < 470

1ª Marcha:

X:> 280 < 320
Y:> 860 < 900

2ª Marcha:

X:>280 < 320
Y:>10 < 50

3ª: Marcha:
X:> 520 < 550
Y:> 860 < 900

4ª Marcha:
X:> 520 < 550
Y:> 10 < 50

5ª Marcha:
X:>680 < 720
Y:>860 < 900

6ª Marcha:
X:>680 < 720
Y:>10 <50


X:>680 < 720
Y:>10 < 50
Z:1

É importente observar que o eixo "z" em todas as marchas fica variando de 0 a 1, só ficando fixo na marcha à ré.

Esdrasrk:
Este é o código base do UnoJoy

//Variável que armazena a posição lida
//nos eixos do joystick
int joystick = 0;
int eixoX = A1;
int eixoY = A2;
int eixoZ = 2;
int bot1 = 8;
int bot2 = 9;
int bot3 = 10;
int bot4 = 11;
int led = 7;
void setup() {
//Definindo eixoZ como um pino de entrada
pinMode(eixoZ, INPUT);
pinMode(bot1, INPUT);
pinMode(bot2, INPUT);
pinMode(bot3, INPUT);
pinMode(bot4, INPUT);
pinMode(led, OUTPUT);

//Ativando o Serial Monitor que exibirá os
//valores lidos no Joystick
Serial.begin(9600);
}

void loop() {
//Lê o valor do eixoX
joystick = analogRead(eixoX);

//imprime o valor do eixoX
Serial.print(" X=");
Serial.print(joystick);

//Lê o valor do eixoY
joystick = analogRead(eixoY);

//imprime o valor do eixoY
Serial.print(" Y=");
Serial.print(joystick);

joystick = digitalRead(eixoZ);
Serial.print(" Z=");
Serial.println(joystick);

delay(100);

}

Estas aqui são as posições refentes à cada marcha:

Neutro:

X:> 510 < 550
Y:> 430 < 470

1ª Marcha:

X:> 280 < 320
Y:> 860 < 900

2ª Marcha:

X:>280 < 320
Y:>10 < 50

3ª: Marcha:
X:> 520 < 550
Y:> 860 < 900

4ª Marcha:
X:> 520 < 550
Y:> 10 < 50

5ª Marcha:
X:>680 < 720
Y:>860 < 900

6ª Marcha:
X:>680 < 720
Y:>10 <50


X:>680 < 720
Y:>10 < 50
Z:1

É importente observar que o eixo "z" em todas as marchas fica variando de 0 a 1, só ficando fixo na marcha à ré.

Não sei o que é isto que publicou, mas certamente não será "código base do UnoJoy", como diz. Por outro lado, também deveria ter lido as regras do fórum antes de fazer o primeiro post para conhecer a regras do fórum. Uma das questões que lá está descrita é a forma correcta de postar código.

Olá meu amigo. Desculpe-me pelo post anterior. Segue o código certo e também de acordo com as regras do fórum. Estou muito ansioso para isso e conto com sua ajuda. Até mais.

#undef DEBUG

#define NUM_BUTTONS  40             // you don't need to change this value
#define NUM_AXES  8        // 6 axes to UNO, and 8 to MEGA. If you are using UNO, don't need to change this value.

typedef struct joyReport_t {
 int16_t axis[NUM_AXES];
 uint8_t button[(NUM_BUTTONS + 7) / 8]; // 8 buttons per byte
} joyReport_t;

joyReport_t joyReport;

uint8_t btn[12];
int fulloff = 0;
void setup(void);
void loop(void);
void setButton(joyReport_t *joy, uint8_t button);
void clearButton(joyReport_t *joy, uint8_t button);
void sendJoyReport(joyReport_t *report);


void setup()
{
 //set pin to input Button
 for ( int portId = 02; portId < 13; portId ++ )
 {
   pinMode( portId, INPUT_PULLUP);
 }
 Serial.begin(115200);
 delay(200);


 for (uint8_t ind = 0; ind < 8; ind++) {
   joyReport.axis[ind] = ind * 1000;
 }
 for (uint8_t ind = 0; ind < sizeof(joyReport.button); ind++) {
   joyReport.button[ind] = 0;
 }
}

// Send an HID report to the USB interface
void sendJoyReport(struct joyReport_t *report)
{
#ifndef DEBUG
 Serial.write((uint8_t *)report, sizeof(joyReport_t));
#else
 // dump human readable output for debugging
 for (uint8_t ind = 0; ind < NUM_AXES; ind++) {
   Serial.print("axis[");
   Serial.print(ind);
   Serial.print("]= ");
   Serial.print(report->axis[ind]);
   Serial.print(" ");
 }
 Serial.println();
 for (uint8_t ind = 0; ind < NUM_BUTTONS / 8; ind++) {
   Serial.print("button[");
   Serial.print(ind);
   Serial.print("]= ");
   Serial.print(report->button[ind], HEX);
   Serial.print(" ");
 }
 Serial.println();
#endif
}

// turn a button on
void setButton(joyReport_t *joy, uint8_t button)
{
 uint8_t index = button / 8;
 uint8_t bit = button - 8 * index;

 joy->button[index] |= 1 << bit;
}

// turn a button off
void clearButton(joyReport_t *joy, uint8_t button)
{
 uint8_t index = button / 8;
 uint8_t bit = button - 8 * index;

 joy->button[index] &= ~(1 << bit);
}

/*
  Read Digital port for Button
  Read Analog port for axis
*/
void loop()
{
 // Create Matriz with value off switch button
 for (int bt = 1; bt < 13; bt ++)
 {
   btn[bt] = digitalRead(bt + 1);
 }
 // Power ON button if it is press. buton 17 at 28
 for (int on = 01; on < 13; on++)
 {
   if (btn[on] == LOW)
   {
     setButton(&joyReport, on + 16);
     //  Serial.println("botao ON");
     //  Serial.println(on+16);
     delay(1);
   }
   for (int on = 01; on < 13; on++)
   {
     if (btn[on] == HIGH)
     {
       clearButton(&joyReport, on + 16);
     }
     //  Serial.println("Every buttons is off");
   }
 }

 /* Move all of the Analogic axis */
 /* Arduino UNO have only 6 port. Will be necessary set to 0; the not used port */
 /* In this example, i will use just 3 axis. X, Y, Z */
 /* if you will use all 6 analog ports, set axis < 3, to axis < 5 */


 for (uint8_t axis = 0; axis < 2; axis++) // 1 - A0 == Wheel == X axis
 {
   joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768, 32767 );
 }


 for (uint8_t axis = 1; axis < 3; axis++) // 2 - A3 = Gas Pedal  
 {

   joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768, 32767 );

 }

 for (uint8_t axis = 2; axis < 4; axis++)  // 3 - A2 == Brake Pedal
 {
   joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768, 32767 );
 }

 //Set to 0; the not used analog port.
 //if you will use all 6 analog ports, exclude the lines, axis[3] at axis [5] */
 //Report.axis[3] = 0;

// You need to ground A1 pin, because its the Y axis and if you dont use it, need to ground.

  joyReport.axis[4] = A0;
 joyReport.axis[5] = A3;
 joyReport.axis[6] = A2;
 joyReport.axis[7] = 0;
 joyReport.axis[8] = 0;

 //Send Data to HID
 sendJoyReport(&joyReport);

 delay(35);
 fulloff = 0;
}

Há algumas coisas que não entendo.
Está dizendo que a posição "Neutro" é quando as os valores sejam:

Neutro:

X:> 510 < 550
Y:> 430 < 470

Esta posição não deveria ser quando nenhuma das outras posições está seleccionada? Se não for assim, as posições X=300 e Y=850 qual é a "marcha" que está seleccionada (uma vez nem é a 1ª nem é neutro)?
Esta questão leva a uma outra que é no caso de a posição "Neutro" ser uma "marcha" deva haver um botão digital para ela? (penso que a posição "neutro" deverá ser a ausência de qualquer uma das outras posições, mas como são dadas as coordenadas fico com essa dúvida).
Outra questão prende-se com a origem dos valores X e Y que foram listados. Isto foi lido no PC ou no Arduino e de que forma? Esta questão deve ser esclarecida, uma vez que os valores lidos pelo Arduino são diferentes dos valores enviados para o PC (pelo programa Arduino Bi Joystick).

Isso mesmo, essas leituras foram feitas pelo próprio Arduino com aquele código anterior. A posição neutro se faz quando a alavanca fica no meio e até para esta posição existe um valor de x e de y ( o que foi escrito no outro post). Todavia os valores oscilam entre os mencionados e por isso escrevi um valor entre cada sequência para que não seja acionada outra marcha por engano.
Sim, a minha ideia é que com cada coordenada dessa seja acionado um botão digital para que seja reconhecido no programa como botão e não como eixo. O maior problema disso é justamente o trocador de marcha ser movido por potenciômetros sendo necessário a leitura analógica.

Esdrasrk:
Isso mesmo, essas leituras foram feitas pelo próprio Arduino com aquele código anterior.

OK.

Esdrasrk:
A posição neutro se faz quando a alavanca fica no meio e até para esta posição existe um valor de x e de y ( o que foi escrito no outro post). Todavia os valores oscilam entre os mencionados e por isso escrevi um valor entre cada sequência para que não seja acionada outra marcha por engano.

OK. Eu isso tinha percebido, no entanto, não foi bem isso que eu perguntei.

Esdrasrk:
Sim, a minha ideia é que com cada coordenada dessa seja acionado um botão digital para que seja reconhecido no programa como botão e não como eixo. O maior problema disso é justamente o trocador de marcha ser movido por potenciômetros sendo necessário a leitura analógica.

Isto já tinha sido indicado no primeiro post, e para alem disso não tinha sido perguntado nada relacionado com isto.

Há questões que ficaram sem resposta, outras foram respondidas de forma vaga.

Aqui está então o que consegui fazer. O botão que activa o "Z=1" deve ser ligado à entrada digital N.º8 (que é activado a ZERO). Atenção que não foi nada testado e por isso poderá não funcionar como é pedido.

/* Arduino USB Joystick HID demo */

/* Author: Darran Hunt
  Released into the public domain.
  Update by RICLAMER in 25/03/2014 to use Analog ports and digital ports
  This code is to be used with Arduino UNO (6 axis and 13 Button )
  This code is compatible with Arduino Mega.
*/

/* INSTALATION
 Just install POT in each analog port. Using the _Grnd _Analog _5V Arduino.
 Like this image: http://arduino.cc/en/uploads/Tutorial/joy_sch_480.jpg
 To setup the buttons, just install you prefered button switch under GND and Port Digital 02~13.
 Use Flip to erease and burn this firmware DFU: https://github.com/harlequin-tech/arduino-usb/blob/master/firmwares/Arduino-big-joystick.hex
 I used Arduino R3 with Atmega 16U2.
*/

#undef DEBUG

#define NUM_BUTTONS  40             // you don't need to change this value
#define NUM_AXES  8        // 6 axes to UNO, and 8 to MEGA. If you are using UNO, don't need to change this value.

typedef struct joyReport_t {
 int16_t axis[NUM_AXES];
 uint8_t button[(NUM_BUTTONS + 7) / 8]; // 8 buttons per byte
} joyReport_t;

joyReport_t joyReport;

uint8_t btn[12];
int fulloff = 0;

int16_t Xaxis;
int16_t Yaxis;

void setup(void);
void loop(void);
void setButton(joyReport_t *joy, uint8_t button);
void clearButton(joyReport_t *joy, uint8_t button);
void sendJoyReport(joyReport_t *report);


void setup()
{
 //set pin to input Button
 for ( int portId = 02; portId < 13; portId ++ )
 {
   pinMode( portId, INPUT_PULLUP);
 }
 Serial.begin(115200);
 delay(200);


 for (uint8_t ind = 0; ind < 8; ind++) {
   joyReport.axis[ind] = ind * 1000;
 }
 for (uint8_t ind = 0; ind < sizeof(joyReport.button); ind++) {
   joyReport.button[ind] = 0;
 }
}

// Send an HID report to the USB interface
void sendJoyReport(struct joyReport_t *report)
{
#ifndef DEBUG
 Serial.write((uint8_t *)report, sizeof(joyReport_t));
#else
 // dump human readable output for debugging
 for (uint8_t ind = 0; ind < NUM_AXES; ind++) {
   Serial.print("axis[");
   Serial.print(ind);
   Serial.print("]= ");
   Serial.print(report->axis[ind]);
   Serial.print(" ");
 }
 Serial.println();
 for (uint8_t ind = 0; ind < NUM_BUTTONS / 8; ind++) {
   Serial.print("button[");
   Serial.print(ind);
   Serial.print("]= ");
   Serial.print(report->button[ind], HEX);
   Serial.print(" ");
 }
 Serial.println();
#endif
}

// turn a button on
void setButton(joyReport_t *joy, uint8_t button)
{
 uint8_t index = button / 8;
 uint8_t bit = button - 8 * index;

 joy->button[index] |= 1 << bit;
}

// turn a button off
void clearButton(joyReport_t *joy, uint8_t button)
{
 uint8_t index = button / 8;
 uint8_t bit = button - 8 * index;

 joy->button[index] &= ~(1 << bit);
}

/*
  Read Digital port for Button
  Read Analog port for axis
*/
void loop()
{
 // Create Matriz with value off switch button
 for (int bt = 1; bt < 13; bt ++)
 {
   btn[bt] = digitalRead(bt + 1);
 }
 // Power ON button if it is press. buton 17 at 28
 for (int on = 01; on < 13; on++)
 {
   if (btn[on] == LOW)
   {
     setButton(&joyReport, on + 16);
     //  Serial.println("botao ON");
     //  Serial.println(on+16);
     delay(1);
   }
   for (int on = 01; on < 13; on++)
   {
     if (btn[on] == HIGH)
     {
       clearButton(&joyReport, on + 16);
     }
     //  Serial.println("Every buttons is off");
   }
 }

 /* Move all of the Analogic axis */
 /* Arduino UNO have only 6 port. Will be necessary set to 0; the not used port */
 /* In this example, i will use just 3 axis. X, Y, Z */
 /* if you will use all 6 analog ports, set axis < 3, to axis < 5 */


 for (uint8_t axis = 0; axis < 2; axis++) // 1 - A0 == Wheel == X axis
 {
   joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768, 32767 );
 }


 for (uint8_t axis = 1; axis < 3; axis++) // 2 - A3 = Gas Pedal  
 {

   joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768, 32767 );

 }

 for (uint8_t axis = 2; axis < 4; axis++)  // 3 - A2 == Brake Pedal
 {
   joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768, 32767 );
 }

 //Set to 0; the not used analog port.
 //if you will use all 6 analog ports, exclude the lines, axis[3] at axis [5] */
 //Report.axis[3] = 0;

// You need to ground A1 pin, because its the Y axis and if you dont use it, need to ground.

 joyReport.axis[4] = A0;
 joyReport.axis[5] = A3;
 joyReport.axis[6] = A2;
 joyReport.axis[7] = 0;
 joyReport.axis[8] = 0;

 
 Xaxis = analogRead(0);
 Yaxis = analogRead(1);
 btn[8] = digitalRead(1);

 if (Yaxis >= 860 && Yaxis <=900) {
   if (Xaxis >= 280 && Xaxis <= 320) { 
     btn[1] = 1;
   }
   else if (Xaxis >= 520 && Xaxis <= 560) { 
     btn[3] = 1;
   }   
   else if (Xaxis >= 680 && Xaxis <= 720) { 
     btn[5] = 1;
   }
 }
 else if (Yaxis >= 10 && Yaxis <=50) {
   if (Xaxis >= 280 && Xaxis <= 320) { 
     btn[2] = 1;
   }
   else if (Xaxis >= 520 && Xaxis <= 560) { 
     btn[4] = 1;
   }   
   else if (Xaxis >= 680 && Xaxis <= 720) { 
     if (btn[8] == HIGH) {
       btn[6] = 1;
     }
     else {
       btn[7] = 1;
     }
   }
 }

 for (int on = 1; on < 8; on++)
 {
   if (btn[on] == 1)
   {
     setButton(&joyReport, on);
     delay(1);
   }
 }
 
 //Send Data to HID
 sendJoyReport(&joyReport);

 delay(35);
 fulloff = 0;
 for (int bt = 0; bt < 13; bt ++)
 {
   btn[bt] = 0;
 }
}

Não funcionou. Pesquisando na web descobri algumas coisas que podem nos ajudar.

Este código é baseado no Tensy 2.0

Serial possível usar no Arduino Uno ?
Consegue modificá-lo para isso?

As diferenças básicas são que não possuo a ligação original do shifter e liguei os eixos diretamente.

Este código foi criado para utilizar todas as funções do shifter , que incluem botões e até direcionais. Não faço questão de utilizar tudo isso, somente o shifter está bom pra mim.

Na minha conexão o eixo x ficou com o fio vermelho , o eixo y com o marrom e o botão da marcha ré ficou laranja. O amarelo é o 5v e o preto o GND.

//
//  G27 shifter to USB interface
//  based on a Teensy++ 2.0
//  Original by pascalh from insidesimracing.tv
//  http://insidesimracing.tv/forums/topic/13189-diy-g25-shifter-interface-with-h-pattern-sequential-and-handbrake-modes/


//  1 operating mode
//  - H-pattern shifter
//
//
//  G27 shifter pinout
//
//  DB9  Color    Shifter Description       Teensy
//  1    Purple    1      Button Clock      pin 2
//  2    Grey     7       Button Data       pin 3
//  3    Yellow   5       Button !CS & !PL  pin 4
//  4    Orange   3       Shifter X axis    pin 38 (A0)
//  5    White      2       SPI input 
//  6    Black    8       GND               GND
//  7    Red   6       +5V               VCC
//  8    Green    4       Shifter Y axis    pin 39 (A1)
//  9    Red    1       +5V

// Teensy pin definitions
#define LED_PIN            11
#define DATA_IN_PIN        44
#define MODE_PIN           43
#define CLOCK_PIN          42
#define X_AXIS_PIN         39
#define Y_AXIS_PIN         38

// H-shifter mode analog axis thresholds
#define HS_XAXIS_12        400 //Gears 1,2
#define HS_XAXIS_56        600 //Gears 5,6, R
#define HS_YAXIS_135       750 //Gears 1,3,5
#define HS_YAXIS_246       300 //Gears 2,4,6, R

// Digital inputs definitions
#define DI_REVERSE         1


byte NESButtonData;
// Called at startup
// Must initialize hardware and software modules
void setup()
{
  // G27 shifter analog inputs configuration 
  pinMode(X_AXIS_PIN, INPUT_PULLUP);   // X axis
  pinMode(Y_AXIS_PIN, INPUT_PULLUP);   // Y axis
  
  // G27 shift register interface configuration 
  pinMode(DATA_IN_PIN, INPUT);         // Data in
  pinMode(MODE_PIN, OUTPUT);           // Parallel/serial mode
  pinMode(CLOCK_PIN, OUTPUT);          // Clock
  
  // Virtual joystick configuration 
  Joystick.useManualSend(true);        // Joystick output is synchronized
}

// Called in a loop after initialization
void loop() 
{
  // Reading of button states from G27 shift register
  int b[2];
  digitalWrite(MODE_PIN, LOW);         // Switch to parallel mode: digital inputs are read into shift register
  delayMicroseconds(10);               // Wait for signal to settle
  digitalWrite(MODE_PIN, HIGH);        // Switch to serial mode: one data bit is output on each clock falling edge
  
  for(int i=0; i<2; i++)              // Reading registers
  {
    digitalWrite(CLOCK_PIN, LOW);      // Generate clock falling edge
    delayMicroseconds(10);             // Wait for signal to settle
  
    b[i]=digitalRead(DATA_IN_PIN);     // Read data bit and store it into bit array
    
    digitalWrite(CLOCK_PIN, HIGH);     // Generate clock rising edge
    delayMicroseconds(10);             // Wait for signal to settle
  }
  
  // Reading of shifter position
  int x=analogRead(0);                 // X axis
  int y=analogRead(1);                 // Y axis
  
  // Current gear calculation
  int gear=0;                          // Default value is neutral

    if(x<HS_XAXIS_12)                  // Shifter on the left?
    {
      if(y>HS_YAXIS_135) gear=1;       // 1st gear
      if(y<HS_YAXIS_246) gear=2;       // 2nd gear
    }
    else if(x>HS_XAXIS_56)             // Shifter on the right?
    {
      if(y>HS_YAXIS_135) gear=5;       // 5th gear
      if(y<HS_YAXIS_246) gear=6;       // 6th gear
    }
    else                               // Shifter is in the middle
    {
      if(y>HS_YAXIS_135) gear=3;       // 3rd gear
      if(y<HS_YAXIS_246) gear=4;       // 4th gear
    }
  
  if(gear!=6) b[DI_REVERSE]=0;         // Reverse gear is allowed only on 6th gear position
  if(b[DI_REVERSE]==1) gear=0;         // 6th gear is deactivated if reverse gear is engaged
  
  // Release virtual buttons for all gears
  Joystick.button(1, LOW);
  Joystick.button(2, LOW);
  Joystick.button(3, LOW);
  Joystick.button(4, LOW);
  Joystick.button(5, LOW);
  Joystick.button(6, LOW);
  Joystick.button(7, b[DI_REVERSE]);
  // Depress virtual button for current gear
  if(gear>0) Joystick.button(gear, HIGH);
    
  // Write new virtual joystick state
  Joystick.send_now();

  // Write inputs and outputs (remove comments to debug)
 /*
  Serial.print(" X axis: ");
  Serial.print(x);
  Serial.print(" Y axis: ");
  Serial.print(y);
  Serial.print(" Digital inputs: ");
  for(int i=0; i<2; i++)Serial.print(b[i]);
  Serial.print(" ");
  Serial.print(" Gear: ");
  Serial.print(gear);
  */ 
  
  delay(10);                                // Wait for 10ms
}

O que significa "Não funcionou"? Não aparece nenhum botão premido no PC? Estão trocados? O que aparece em modo DEBUG?
Nota: para que o programa compilado em modo DEBUG deverá substituir a linha:

#undef DEBUG

para

#define DEBUG

Após isso deverá descarregar o programa novamente para o Arduino e abrir o "Monitor da Porta Série" do IDE. Deverão aparecer no monitor da porta série mensagens que indicam quais o botões que estão a ser premidos (assim como o vaçlor dos potenciómetros).

Foi feita a substituição e nada aparece no monitor da porta serial.

Segue também print de como ficou depois de ser feito tudo. Os botões são pressionados sem serem selecionados.

Este é o novo código:

/* Arduino USB Joystick HID demo */

/* Author: Darran Hunt
  Released into the public domain.
  Update by RICLAMER in 25/03/2014 to use Analog ports and digital ports
  This code is to be used with Arduino UNO (6 axis and 13 Button )
  This code is compatible with Arduino Mega.
*/

/* INSTALATION
 Just install POT in each analog port. Using the _Grnd _Analog _5V Arduino.
 Like this image: http://arduino.cc/en/uploads/Tutorial/joy_sch_480.jpg
 To setup the buttons, just install you prefered button switch under GND and Port Digital 02~13.
 Use Flip to erease and burn this firmware DFU: https://github.com/harlequin-tech/arduino-usb/blob/master/firmwares/Arduino-big-joystick.hex
 I used Arduino R3 with Atmega 16U2.
*/

#define DEBUG

#define NUM_BUTTONS  40             // you don't need to change this value
#define NUM_AXES  8        // 6 axes to UNO, and 8 to MEGA. If you are using UNO, don't need to change this value.

typedef struct joyReport_t {
 int16_t axis[NUM_AXES];
 uint8_t button[(NUM_BUTTONS + 7) / 8]; // 8 buttons per byte
} joyReport_t;

joyReport_t joyReport;

uint8_t btn[12];
int fulloff = 0;

int16_t Xaxis;
int16_t Yaxis;

void setup(void);
void loop(void);
void setButton(joyReport_t *joy, uint8_t button);
void clearButton(joyReport_t *joy, uint8_t button);
void sendJoyReport(joyReport_t *report);


void setup()
{
 //set pin to input Button
 for ( int portId = 02; portId < 13; portId ++ )
 {
   pinMode( portId, INPUT_PULLUP);
 }
 Serial.begin(115200);
 delay(200);


 for (uint8_t ind = 0; ind < 8; ind++) {
   joyReport.axis[ind] = ind * 1000;
 }
 for (uint8_t ind = 0; ind < sizeof(joyReport.button); ind++) {
   joyReport.button[ind] = 0;
 }
}

// Send an HID report to the USB interface
void sendJoyReport(struct joyReport_t *report)
{
#ifndef DEBUG
 Serial.write((uint8_t *)report, sizeof(joyReport_t));
#else
 // dump human readable output for debugging
 for (uint8_t ind = 0; ind < NUM_AXES; ind++) {
   Serial.print("axis[");
   Serial.print(ind);
   Serial.print("]= ");
   Serial.print(report->axis[ind]);
   Serial.print(" ");
 }
 Serial.println();
 for (uint8_t ind = 0; ind < NUM_BUTTONS / 8; ind++) {
   Serial.print("button[");
   Serial.print(ind);
   Serial.print("]= ");
   Serial.print(report->button[ind], HEX);
   Serial.print(" ");
 }
 Serial.println();
#endif
}

// turn a button on
void setButton(joyReport_t *joy, uint8_t button)
{
 uint8_t index = button / 8;
 uint8_t bit = button - 8 * index;

 joy->button[index] |= 1 << bit;
}

// turn a button off
void clearButton(joyReport_t *joy, uint8_t button)
{
 uint8_t index = button / 8;
 uint8_t bit = button - 8 * index;

 joy->button[index] &= ~(1 << bit);
}

/*
  Read Digital port for Button
  Read Analog port for axis
*/
void loop()
{
 // Create Matriz with value off switch button
 for (int bt = 1; bt < 13; bt ++)
 {
   btn[bt] = digitalRead(bt + 1);
 }
 // Power ON button if it is press. buton 17 at 28
 for (int on = 01; on < 13; on++)
 {
   if (btn[on] == LOW)
   {
     setButton(&joyReport, on + 16);
     //  Serial.println("botao ON");
     //  Serial.println(on+16);
     delay(1);
   }
   for (int on = 01; on < 13; on++)
   {
     if (btn[on] == HIGH)
     {
       clearButton(&joyReport, on + 16);
     }
     //  Serial.println("Every buttons is off");
   }
 }

 /* Move all of the Analogic axis */
 /* Arduino UNO have only 6 port. Will be necessary set to 0; the not used port */
 /* In this example, i will use just 3 axis. X, Y, Z */
 /* if you will use all 6 analog ports, set axis < 3, to axis < 5 */


 for (uint8_t axis = 0; axis < 2; axis++) // 1 - A0 == Wheel == X axis
 {
   joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768, 32767 );
 }


 for (uint8_t axis = 1; axis < 3; axis++) // 2 - A3 = Gas Pedal  
 {

   joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768, 32767 );

 }

 for (uint8_t axis = 2; axis < 4; axis++)  // 3 - A2 == Brake Pedal
 {
   joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768, 32767 );
 }

 //Set to 0; the not used analog port.
 //if you will use all 6 analog ports, exclude the lines, axis[3] at axis [5] */
 //Report.axis[3] = 0;

// You need to ground A1 pin, because its the Y axis and if you dont use it, need to ground.

 joyReport.axis[4] = A0;
 joyReport.axis[5] = A3;
 joyReport.axis[6] = A2;
 joyReport.axis[7] = 0;
 joyReport.axis[8] = 0;

 
 Xaxis = analogRead(0);
 Yaxis = analogRead(1);
 btn[8] = digitalRead(1);

 if (Yaxis >= 860 && Yaxis <=900) {
   if (Xaxis >= 280 && Xaxis <= 320) { 
     btn[1] = 1;
   }
   else if (Xaxis >= 520 && Xaxis <= 560) { 
     btn[3] = 1;
   }   
   else if (Xaxis >= 680 && Xaxis <= 720) { 
     btn[5] = 1;
   }
 }
 else if (Yaxis >= 10 && Yaxis <=50) {
   if (Xaxis >= 280 && Xaxis <= 320) { 
     btn[2] = 1;
   }
   else if (Xaxis >= 520 && Xaxis <= 560) { 
     btn[4] = 1;
   }   
   else if (Xaxis >= 680 && Xaxis <= 720) { 
     if (btn[8] == HIGH) {
       btn[6] = 1;
     }
     else {
       btn[7] = 1;
     }
   }
 }

 for (int on = 1; on < 8; on++)
 {
   if (btn[on] == 1)
   {
     setButton(&joyReport, on);
     delay(1);
   }
 }
 
 //Send Data to HID
 sendJoyReport(&joyReport);

 delay(35);
 fulloff = 0;
 for (int bt = 0; bt < 13; bt ++)
 {
   btn[bt] = 0;
 }
}

forum.PNG

Em primeiro lugar, a última imagem foi feita com a última versão do programa ou com a primeira? (a ideia da versão em modo de DEBUG é servir apenas para verificação e não para funcionamento normal)
Em segundo lugar é normal que no monitor serial não apareça nada. O monitor está configurado para uma velocidade de 9600 (pode verificar isto no canto inferior direito da janela do monitor serial), enquanto o programa está configurado para uma velocidade de 115200 (pode verificar isto na função setup() na linha Serial.begin(115200)). Deve alterar a velocidade do monitor serial para a que está configurada no programa (isto é, 115200).

A última imagem foi feita com o primeiro código que me passou ( sem usar o debug).

Foram feitas as alterações que pediu e ainda sim nada é exibido no monitor da porta serial. Segue as imagens.

Aparentemente o programa que forneceu estava alterado. Consegui encontrar o programa original aqui. O resultado é o que se segue.

/* Arduino USB Joystick HID demo */

/* Author: Darran Hunt
 * Released into the public domain.
 * Update by RICLAMER in 25/03/2014 to use Analog ports and digital ports
 * This code is to be used with Arduino UNO (6 axis and 13 Button )
 * This code is compatible with Arduino Mega. 
 */
 
 /* INSTALATION
Just install POT in each analog port. Using the _Grnd _Analog _5V Arduino.
Like this image: http://arduino.cc/en/uploads/Tutorial/joy_sch_480.jpg
To setup the buttons, just install you prefered button switch under GND and Port Digital 02~13.
Use Flip to erease and burn this firmware DFU: https://github.com/harlequin-tech/arduino-usb/blob/master/firmwares/Arduino-big-joystick.hex
I used Arduino R3 with Atmega 16U2.
 */

#undef DEBUG

#define NUM_BUTTONS	40             // you don't need to change this value
#define NUM_AXES	8	       // 6 axes to UNO, and 8 to MEGA. If you are using UNO, don't need to change this value.

typedef struct joyReport_t {
    int16_t axis[NUM_AXES];
    uint8_t button[(NUM_BUTTONS+7)/8]; // 8 buttons per byte
} joyReport_t;

joyReport_t joyReport;

uint8_t btn[12];
int fulloff = 0;
void setup(void);
void loop(void);
void setButton(joyReport_t *joy, uint8_t button);
void clearButton(joyReport_t *joy, uint8_t button);
void sendJoyReport(joyReport_t *report);


void setup() 
{ 
  //set pin to input Button  
  for( int portId = 02; portId < 13; portId ++ )
	{
          pinMode( portId, INPUT_PULLUP);
	}
    Serial.begin(115200);
    delay(200);

    for (uint8_t ind=0; ind<8; ind++) {
	joyReport.axis[ind] = ind*1000;
    }
    for (uint8_t ind=0; ind<sizeof(joyReport.button); ind++) {
        joyReport.button[ind] = 0;
    }
}

// Send an HID report to the USB interface
void sendJoyReport(struct joyReport_t *report)
{
#ifndef DEBUG
    Serial.write((uint8_t *)report, sizeof(joyReport_t));
#else
    // dump human readable output for debugging
    for (uint8_t ind=0; ind<NUM_AXES; ind++) {
	Serial.print("axis[");
	Serial.print(ind);
	Serial.print("]= ");
	Serial.print(report->axis[ind]);
	Serial.print(" ");
    }
    Serial.println();
    for (uint8_t ind=0; ind<NUM_BUTTONS/8; ind++) {
	Serial.print("button[");
	Serial.print(ind);
	Serial.print("]= ");
	Serial.print(report->button[ind], HEX);
	Serial.print(" ");
    }
    Serial.println();
#endif
}

// turn a button on
void setButton(joyReport_t *joy, uint8_t button)
{
    uint8_t index = button/8;
    uint8_t bit = button - 8*index;

    joy->button[index] |= 1 << bit;
}

// turn a button off
void clearButton(joyReport_t *joy, uint8_t button)
{
    uint8_t index = button/8;
    uint8_t bit = button - 8*index;

    joy->button[index] &= ~(1 << bit);
}

/* 
 * Read Digital port for Button
 * Read Analog port for axis
  */
void loop() 
{ 
  // Create Matriz with value off switch button  
  for(int bt = 1; bt < 13; bt ++)
	{
          btn[bt]= digitalRead(bt+1);
	} 

   // Power ON button if it is press. buton 17 at 28
   for(int on=01; on < 13; on++)
   {
       if (btn[on] == LOW)
       {
         setButton(&joyReport, on+16);
      //  Serial.println("botao ON");
      //  Serial.println(on+16);
       }else{
         fulloff = fulloff++;
       }   //Power off all Button, if all button are not press
       
      if(fulloff == 13)
         {
           for(uint8_t cont=0; cont<40; cont++)
             {  
               clearButton(&joyReport, cont);
             }
            //  Serial.println("Every buttons is off");
          }
   }
      
    /* Move all of the Analogic axis */
    /* Arduino UNO have only 6 port. Will be necessary set to 0; the not used port */
    /* In this example, i will use just 3 axis. X, Y, Z */
    /* if you will use all 6 analog ports, set axis < 3, to axis < 5 */
    for (uint8_t axis = 0; axis < 4; axis++) {
      joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768,32767 );
    }
    //Set to 0; the not used analog port.
    //if you will use all 6 analog ports, exclude the lines, axis[3] at axis [5] */
    //joyReport.axis[3] = 0;
    joyReport.axis[4] = 0;
    joyReport.axis[5] = 0;
    joyReport.axis[6] = 0;
    joyReport.axis[7] = 0;
    joyReport.axis[8] = 0;
    
    Xaxis = analogRead(0);
    Yaxis = analogRead(1);
    btn[8] = digitalRead(1);
    
    if (Yaxis >= 860 && Yaxis <=900) {
      if (Xaxis >= 280 && Xaxis <= 320) { 
        btn[1] = 1;
      }
      else if (Xaxis >= 520 && Xaxis <= 560) { 
        btn[3] = 1;
      }   
      else if (Xaxis >= 680 && Xaxis <= 720) { 
        btn[5] = 1;
      }
    }
    else if (Yaxis >= 10 && Yaxis <=50) {
      if (Xaxis >= 280 && Xaxis <= 320) { 
        btn[2] = 1;
      }
      else if (Xaxis >= 520 && Xaxis <= 560) { 
        btn[4] = 1;
      }   
      else if (Xaxis >= 680 && Xaxis <= 720) { 
        if (btn[8] == HIGH) {
          btn[6] = 1;
        }
        else {
          btn[7] = 1;
        }
      }
    }
    
    for (int on = 1; on < 8; on++)
    {
      if (btn[on] == 1)
      {
        btn[on] = 0;
        setButton(&joyReport, on);
      }
      else {
        clearButton(&joyReport, on);
      }
      delay(1);
    }
     
    
    //Send Data to HID
    sendJoyReport(&joyReport);

    delay(100);
    fulloff = 0;
}

Meu amigo, quando fui carregar para o Arduino apareceu a mensagem dizendo que a variável não foi declarada.

/* Arduino USB Joystick HID demo */

/* Author: Darran Hunt
 * Released into the public domain.
 * Update by RICLAMER in 25/03/2014 to use Analog ports and digital ports
 * This code is to be used with Arduino UNO (6 axis and 13 Button )
 * This code is compatible with Arduino Mega. 
 */
 
 /* INSTALATION
Just install POT in each analog port. Using the _Grnd _Analog _5V Arduino.
Like this image: http://arduino.cc/en/uploads/Tutorial/joy_sch_480.jpg
To setup the buttons, just install you prefered button switch under GND and Port Digital 02~13.
Use Flip to erease and burn this firmware DFU: https://github.com/harlequin-tech/arduino-usb/blob/master/firmwares/Arduino-big-joystick.hex
I used Arduino R3 with Atmega 16U2.
 */

#undef DEBUG

#define NUM_BUTTONS	40             // you don't need to change this value
#define NUM_AXES	8	       // 6 axes to UNO, and 8 to MEGA. If you are using UNO, don't need to change this value.

typedef struct joyReport_t {
    int16_t axis[NUM_AXES];
    uint8_t button[(NUM_BUTTONS+7)/8]; // 8 buttons per byte
} joyReport_t;

joyReport_t joyReport;

uint8_t btn[12];
int fulloff = 0;

int16_t Xaxis;
int16_t Yaxis;

void setup(void);
void loop(void);
void setButton(joyReport_t *joy, uint8_t button);
void clearButton(joyReport_t *joy, uint8_t button);
void sendJoyReport(joyReport_t *report);


void setup() 
{ 
  //set pin to input Button  
  for( int portId = 02; portId < 13; portId ++ )
	{
          pinMode( portId, INPUT_PULLUP);
	}
    Serial.begin(115200);
    delay(200);

    for (uint8_t ind=0; ind<8; ind++) {
	joyReport.axis[ind] = ind*1000;
    }
    for (uint8_t ind=0; ind<sizeof(joyReport.button); ind++) {
        joyReport.button[ind] = 0;
    }
}

// Send an HID report to the USB interface
void sendJoyReport(struct joyReport_t *report)
{
#ifndef DEBUG
    Serial.write((uint8_t *)report, sizeof(joyReport_t));
#else
    // dump human readable output for debugging
    for (uint8_t ind=0; ind<NUM_AXES; ind++) {
	Serial.print("axis[");
	Serial.print(ind);
	Serial.print("]= ");
	Serial.print(report->axis[ind]);
	Serial.print(" ");
    }
    Serial.println();
    for (uint8_t ind=0; ind<NUM_BUTTONS/8; ind++) {
	Serial.print("button[");
	Serial.print(ind);
	Serial.print("]= ");
	Serial.print(report->button[ind], HEX);
	Serial.print(" ");
    }
    Serial.println();
#endif
}

// turn a button on
void setButton(joyReport_t *joy, uint8_t button)
{
    uint8_t index = button/8;
    uint8_t bit = button - 8*index;

    joy->button[index] |= 1 << bit;
}

// turn a button off
void clearButton(joyReport_t *joy, uint8_t button)
{
    uint8_t index = button/8;
    uint8_t bit = button - 8*index;

    joy->button[index] &= ~(1 << bit);
}

/* 
 * Read Digital port for Button
 * Read Analog port for axis
  */
void loop() 
{ 
  // Create Matriz with value off switch button  
  for(int bt = 1; bt < 13; bt ++)
	{
          btn[bt]= digitalRead(bt+1);
	} 

   // Power ON button if it is press. buton 17 at 28
   for(int on=01; on < 13; on++)
   {
       if (btn[on] == LOW)
       {
         setButton(&joyReport, on+16);
      //  Serial.println("botao ON");
      //  Serial.println(on+16);
       }else{
         fulloff = fulloff++;
       }   //Power off all Button, if all button are not press
       
      if(fulloff == 13)
         {
           for(uint8_t cont=0; cont<40; cont++)
             {  
               clearButton(&joyReport, cont);
             }
            //  Serial.println("Every buttons is off");
          }
   }
      
    /* Move all of the Analogic axis */
    /* Arduino UNO have only 6 port. Will be necessary set to 0; the not used port */
    /* In this example, i will use just 3 axis. X, Y, Z */
    /* if you will use all 6 analog ports, set axis < 3, to axis < 5 */
    for (uint8_t axis = 0; axis < 4; axis++) {
      joyReport.axis[axis] = map(analogRead(axis), 0, 1023, -32768,32767 );
    }
    //Set to 0; the not used analog port.
    //if you will use all 6 analog ports, exclude the lines, axis[3] at axis [5] */
    //joyReport.axis[3] = 0;
    joyReport.axis[4] = 0;
    joyReport.axis[5] = 0;
    joyReport.axis[6] = 0;
    joyReport.axis[7] = 0;
    joyReport.axis[8] = 0;
    
    Xaxis = analogRead(0);
    Yaxis = analogRead(1);
    btn[8] = digitalRead(1);
    
    if (Yaxis >= 860 && Yaxis <=900) {
      if (Xaxis >= 280 && Xaxis <= 320) { 
        btn[1] = 1;
      }
      else if (Xaxis >= 520 && Xaxis <= 560) { 
        btn[3] = 1;
      }   
      else if (Xaxis >= 680 && Xaxis <= 720) { 
        btn[5] = 1;
      }
    }
    else if (Yaxis >= 10 && Yaxis <=50) {
      if (Xaxis >= 280 && Xaxis <= 320) { 
        btn[2] = 1;
      }
      else if (Xaxis >= 520 && Xaxis <= 560) { 
        btn[4] = 1;
      }   
      else if (Xaxis >= 680 && Xaxis <= 720) { 
        if (btn[8] == HIGH) {
          btn[6] = 1;
        }
        else {
          btn[7] = 1;
        }
      }
    }
    
    for (int on = 1; on < 8; on++)
    {
      if (btn[on] == 1)
      {
        btn[on] = 0;
        setButton(&joyReport, on);
      }
      else {
        clearButton(&joyReport, on);
      }
      delay(1);
    }
     
    
    //Send Data to HID
    sendJoyReport(&joyReport);

    delay(100);
    fulloff = 0;
}