So i am using a analog joystick to control a motor with a adafruit motor shield but for some reason the joystick has started working really weird or maybe its my code. I am fairly sure nothing is wrong with the shield or motor. I have connected all the pins on the joystick correctly except i have left the MS pin out.
Anyway the problem is that suddenly instead of the values being from 0 to 1024 on the joystick it has suddenly switched to 0 to roughly 785. Also when i move the joystick in a very precise position a bit to the side it gives full power to the motor even though i am only using the X axis.
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(4);
int VRx = 0; // X direction
int VRy = 0; // Y 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 = map(VRx, 0, 1024, -255, 255); // 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 < -1) {
motorSpeed * -1; // Makes motorSpeed value positive
}
Serial.println(VRx);
if (VRx > 513) {
myMotor->setSpeed(motorSpeed);
myMotor->run(FORWARD);
}
if (VRx < 510){
myMotor->setSpeed(motorSpeed);
myMotor->run(BACKWARD);
}
}