Encoders in EV3 motor problem

Hello everyone, I have been playing around with combining a LEGO EV3 motor and an Arduino because, I have a broken EV3 I was able to take the wire ports off of to use with the arduino. I have a code which is supposed to move the motor backward and forward a certain distance. The code is actually successful at doing this the problem is that the code is very unreliable because for some reason if the motor is shaken to much it will send a value of either -1, -2, or -3. I'm unsure why this is happening and was wondering if anyone had any ideas on how to solve this problem. I believe the motor uses a quadrature encoder to get these values.