AlanChatham / UnoJoy

UnoJoy! allows you to easily turn an Arduino Uno (or Mega or Leonardo) into a PS3-compatible USB game controller
GNU General Public License v3.0
482 stars 130 forks source link

Rotary Encoder on UnoJoy With SimpleRotary Library #37

Open premudeshi opened 3 years ago

premudeshi commented 3 years ago

Hello,

I know this has been asked several times before however I am new to UnoJoy and would like some help. I would like to connect a simple rotary encoder (EC11) as a axis. The code works when I test it in Serial Monitor however when I bootload the UnoJoy things, it doesn't work. I am using the SimpleRotary Library. I have attached my code below. What should I change? If you have better ideas than the way I am coding it, please let me know.

/*

#include <SimpleRotary.h>
#include "UnoJoy.h"
int degree = 127;
int newDegree = 127;

// Pin A, Pin B, Button Pin
SimpleRotary rotary(6, 5, 7);

void setup() {
  //Serial.begin(9600);
  setupUnoJoy();
}

void loop() {
  getData();

  dataForController_t controllerData = getControllerData();
  setControllerData(controllerData);
}
void getData()
{
    byte i;

  // 0 = not turning, 1 = CW, 2 = CCW
  i = rotary.rotate();

  if ( i == 1 ) {
    //Serial.println("CW");
    newDegree = degree + 5;
    if (newDegree < 255)
    {
      degree = degree + 5;
      //Serial.println(degree);
      return degree;
      //analogWrite(9, degree);
    }

  }

  if ( i == 2 ) {
    //Serial.println("CCW");
    newDegree = degree - 5;
    if (newDegree > 0)
    {
      degree = degree - 5;
      //Serial.println(degree);
      //analogWrite(9, degree);
      return degree;
    }
  }
}

dataForController_t getControllerData(void){

  // Set up a place for our controller data
  //  Use the getBlankDataForController() function, since
  //  just declaring a fresh dataForController_t tends
  //  to get you one filled with junk from other, random
  //  values that were in those memory locations before
  dataForController_t controllerData = getBlankDataForController();

  // Set the analog sticks
  //  Since analogRead(pin) returns a 10 bit value,
  //  we need to perform a bit shift operation to
  //  lose the 2 least significant bits and get an
  //  8 bit number that we can use  
  controllerData.leftStickX = getData();

  // And return the data!
  return controllerData;
}