Accessing changing variables won't work (Johnny-Five Joystick)

92 Views Asked by At

I'm working on an Arduino game with a joystick. I have 4 LED lights and every 2 seconds, 1 of them will light up. With the joystick, you have to react as fast as possible to turn off the LED light. So for example, if the left LED is lighting up, you have to go left on the joystick to turn it off.

This is the code for my joystick:

var joystick = new five.Joystick({
  pins: ["A0", "A1"],
 });

joystick.on("change", function() {
  let x = this.x;
  let y = this.y
 });

So every time that the position of the joystick changes, let x and let y will get an update.

Now I will show you the code of the function. This function will restart every 2 seconds. The problem is that I need the let x and let y from the joystick to make this function work, but I don't know how to access them.

const playGame = () => {
  setInterval(() => {
    console.log(x, y);
  }, 2000);
};

The console.log(x, y) results in undefined.

1

There are 1 best solutions below

0
On BEST ANSWER

you need to define x and y OUTSIDE of change event so you can access it

let x, y
var joystick = new five.Joystick({
  pins: ["A0", "A1"],
 });

joystick.on("change", function() {
  x = this.x;
  y = this.y
 });
const playGame = () => {
  setInterval(() => {
    console.log(x, y);
  }, 2000);
};

this is to fix your example, but there is an even more J5 way (taken from the docs

let x, y
var joystick = new five.Joystick({
  pins: ["A0", "A1"],
  freq: 100 // this limit the joystick sample rate tweak to your needs
});


joystick.on("change", function() { // only fire as the sample rate freq
  x = this.x;
  y = this.y
});