# Problems with Joystick and Adafruit Motor Shield

I'm kind of new to arduino and c++ so forgive me if the coding is messy.

I have connected a analog joystick and adafruit motor shield to my arduino. The joystick should control the dc motors direction and speed. I have created a formula to translate the value of VRx on a scale of 1024 to 0, to a scale of 255 to -255. A if command then makes the negative value positive. The formula works well on a calculator but is a bit weird on the arduino. In the serial monitor it reads the default value (0) of motorSpeed as 47 and the max as -30 and min as 1. Also for some reason the motor will only move forward when i move the joystick but not backwards. Also for some reason when the joystick is not being touched the motor moves very slowly backwards. I fairly sure that this is not a motor problem as i have tried switching the polarities. Please help as i have no idea what is going on.

Here's my code:

``````#include <Wire.h>

int VRx = 0;     // Y direction
int VRy = 0;     // X direction
int motorSpeed = 0;

void setup() {
// put your setup code here, to run once:
AFMS.begin();
Serial.begin(9600);
myMotor->setSpeed(0);
}

void loop() {
// put your main code here, to run repeatedly:

motorSpeed = 255 * (VRx - 512) / 512;   // Makes the VRx value on a scale from 1024 to 0 translate to a scale from 255 to -255. 512 being 0, 1024 being 255 and -255 being 0.

if (motorSpeed < 0) {
motorSpeed * -1;     // Makes motorSpeed value positive
}

Serial.println(motorSpeed);

if (VRx > 520) {         // Not exactly 512 to give a bit of "Wiggle" room.
myMotor->setSpeed(motorSpeed);
myMotor->run(FORWARD);
}
if (VRx < 515){
myMotor->setSpeed(motorSpeed);
myMotor->run(BACKWARD);
}
}
``````
``````int VRx = 0;     // Y direction
int VRy = 0;     // X direction
``````

``````motorSpeed = 255 * (VRx - 512) / 512;
``````

You will encounter overflows, all operands are 16 bit integers.

``````motorSpeed = 255 * (VRx - 512L) / 512;
``````

The above forces the compiler to use 32 bits for the expression.

Or you could achieve the same result by declaring VRx as a long and leaving the calculation as it is in your code

Personally I think I would use

``````motorSpeed = map(VRx, 0, 1023, -255, 255);
``````

as it is more obvious what is going on (at least to me)