Restricted optical mouse movement on Arduino

Hi, I have connected an optical mouse to Pro Mini. All works well, monitor displays coordinates. I have restricted x and y to become minimum 1 and max 8 (so 7 steps only). Works! :slight_smile:

Now the issue >:( :

A. if I move the mouse fast, it skips numbers (3,4,…7,8). It has to work that there is ALWAYS an increment of 1 when moving up/right (or-1 for down/left).

B. if mouse is moving up (y coordinate) within +/- 30%, the x coordinate should not count. Likewise with horizontal movement +/- 30%, the y should not change.
How to program that?

Big thanks!

Read the forum guidelines to see how to properly post code. Remove useless white space and format the code with the IDE autoformat tool (ctrl-t or Tools, Auto Format).

#include <PS2Mouse.h>
#define MOUSE_DATA 5
#define MOUSE_CLOCK 3


PS2Mouse mouse(MOUSE_CLOCK, MOUSE_DATA, STREAM);
int x = 0; int x1 = 0;int x2=0;
int y = 0; int y1 = 0;int y2=0;
/**
   Setup
*/
void setup()
{
  Serial.begin(38400);
  mouse.initialize();


}


void loop()
{
  int16_t data[2];
  mouse.report(data);


  x = data[1];
  if (x >= 0) {
    x2 = x2 + 1;
  }
  if (x <= 0) {
    x2 = x2 - 1;
  }


  y = data[2];
  if (y >= 0) {
    y2 = y2+ 1;
  }
  if (y <= 0) {
    y2 = y2 - 1;
  }


  if ((x2 != x1) and (y2 != y1)) {
if(x2>7){x2=7;}
if(x2<1){x2=1;}
if(y2>8){y2=7;}
if(y2<1){y2=1;}


    Serial.print(" X=");
    Serial.print(x2);


    Serial.print(" Y=");
    Serial.println(y2);
    x1 = x2;
    y1 = y2;
  }
  delay(200);


}
  if ((x2 != x1) and (y2 != y1)) {

The ‘and’ means ‘don’t send a report unless BOTH direction have moved’. You want ‘or’ (or ‘||’).

if(x2>7){x2=7;}
if(x2<1){x2=1;}
if(y2>8){y2=7;}
if(y2<1){y2=1;}

You should probably put these BEFORE you check to see if either has moved. Otherwise you will keep sending 1 or 7 over and over when the mouse tries to go past the limit. You could also replace these with:

 x2 = constrain(x2, 1, 7);
 y2 = constrain(y2, 1, 7);

Half as many lines and does the same thing.

Thank you! That was very usefull.