0

I'm experimenting with the joystick and the MAX7219 module (8x8 LED display) and i made this program:

#include "LedControl.h"

LedControl lc=LedControl(11,13,10,1);

int Xo = 36;
int Yo = 34;

int xPin = A1;
int yPin = A0;
int buttonPin = 7;

int xPos = 0;
int yPos = 0;

int Xvel = 0;
int Yvel = 0;

int lastMapX = -1;
int lastMapY = 0;

void setup() {
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
  lc.shutdown(0,false);
  lc.setIntensity(0,8);
  lc.clearDisplay(0);
}

void loop() {
  
  Xvel = joystickMap(xPin, Xo);
  Yvel = joystickMap(yPin, Yo);

  if (Xvel == 0 and Yvel == 0) {
    Xvel = lastMapX;
    Yvel = lastMapY;
  }
  
  yPos = yPos + Xvel;
  xPos = xPos + Yvel;

  if (xPos < 0) {
    xPos = 0;
  }else if (yPos < 0) {
    yPos = 0;
  }else if (xPos > 7) {
    xPos = 7;
  }else if (yPos > 7) {
    yPos = 7;
  }
  
  lc.clearDisplay(0);
  lc.setLed(0,xPos,yPos,true);

  Serial.print("x=");
  Serial.print(yPos); 
  Serial.print(" y=");
  Serial.print(xPos); 
  Serial.print(" buttonpress=");
  Serial.print(digitalRead(7)==0);
  Serial.print(" x>7=");
  Serial.println(xPos > 7);

  lastMapX = Xvel;
  lastMapY = Yvel;

  delay(100);
}

int joystickMap(int in, long offset) {
  int firMap = map(analogRead(in), 0, 1023, -102, 100)+offset;
  if (firMap == 0 or firMap == 1 or firMap == -1) {
    return 0;
  }else if (firMap > 0) {
    return 1;
  }else if (firMap < 0) {
    return -1;
  }
}

it should make it for the player impossible to stop. But there is a glitch witch allows you to go off-screen. If you are in any corner and you go diagonally to the opposite corner you just go through. Here is a screenshot with the program and the serial monitor: IMAGE

My Arduino is a UNO R3. How can i fix this glitch?

  • 1
    Read your code where you are printing your values. Read it carefully. It's behaving exactly as you are telling it... – Majenko Jul 7 at 10:33
  • don't you think, that tying the conditions for x and y together with else if is incorrect? x and y are independent coordinates, so why should the limitations on y being only imposed, if the limitations on x weren't imposed? Split your if conditions up into one set for x and one set for y – chrisl Jul 7 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.