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>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
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:
VRx = analogRead(0);
VRy = analogRead(1);
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);
}
}