Shop OBEX P1 Docs P2 Docs Learn Events
Question/Issue with the Mouse Sensor Kit — Parallax Forums

Question/Issue with the Mouse Sensor Kit

MouseSensorHelpMouseSensorHelp Posts: 1
edited 2013-01-20 14:39 in Accessories
I'm working on a robotics project and we were hoping to use the Mouse Sensor Kit as an encoder. The sensor does work, but encounters two issues. First, sometimes movement is not picked up; the position (x or y) will freeze until the sensor is stops moving and begins again. Second, sometimes moving either direction will be read as moving the same distance. (Moving the sensor back and forth, the X value continues to grow constantly rather then oscilate). The freezing is especially common if you move the sensor fast, but can happen at relatively mild speeds too.

Note, these speeds are slower then a normal computer mice can operate. I really have no idea if this is just some hardware limitation or represents some error with our setup or code.

We are using this with an Arduino Mega, I'll put the code below. Thanks for any help.
]#define sclk 21 //Define pin 5 as clock
#define sdio 20 //Define pin 6 as data
//Mouse sensor register addresses
#define CHNG 0x80

byte stat;
byte readx; //Vallue from sensor: 255 = -1, 128 = 1
byte ready; //Vallue from sensor: 255 = -1, 128 = 1
byte quality;

int dx;
int dy;
int x;
int y;

byte WriteNeg(byte data)
{
pinMode(sdio,OUTPUT);
for(int i = 0; i < 8; i++)
{
digitalWrite(sdio,bitRead(data,7));
digitalWrite(sclk,LOW);
delayMicroseconds(50);
digitalWrite(sclk,HIGH);
delayMicroseconds(50);
data = data << 1;
}
pinMode(sdio,INPUT);
}

byte ReadNeg()
{
byte data = 0;
for(int i = 0; i < 8; i++)
{
digitalWrite(sclk,LOW);
delayMicroseconds(50);
digitalWrite(sclk,HIGH);
delayMicroseconds(50);
bitWrite(data,i,digitalRead(sdio));
}
return data;
}

void WriteAddr(byte address, byte data)
{
WriteNeg(address|0x80);
WriteNeg(data);
}

int ReadAddr(byte address)
{
WriteNeg(address);
delayMicroseconds(100);
return ReadNeg();
}

void setup()
{
delay(2000);
Serial.begin(9600);
Serial.print("Program Initializing");
pinMode(sclk,OUTPUT);
digitalWrite(sclk,HIGH);
Serial.print("\nClock pin set high");
delay(100);
WriteAddr(0xB1,0x80); //Sets resolution to 500 dpi
Serial.print("\nResolution set to 500 dpi");
Serial.print("\nMain program starting\n");
}

void loop()
{
stat = ReadAddr(0x16);
if (stat & CHNG != 0)
{
readx = ReadAddr(0x03);
switch (readx)
{
case 255:
dx = -1;
break;
case 128:
dx = 1;
break;
case 0:
dx = 0;
break;
}
x = x + dx;
Serial.print(x,DEC);
Serial.print("\t");
ready = ReadAddr(0x02);
switch (ready)
{
case 255:
dy = -1;
break;
case 128:
dy = 1;
break;
case 0:
dy = 0;
break;
}
y = y + dy;
Serial.println(y,DEC);
}
}
Sign In or Register to comment.