I tried to build a pretty basic script for controlling my DC motor with a joystick. The code works partially, but when the motor is supposed to be at speed 255 when X = 1023, it is going more like speed 75-100. I know it can't be a problem with the motor, because it has no problem getting to top speed when I put in the command flatly. The joystick also works, because I recently used it to control some LED lights. Does anyone know what my problem is?
Here is my code:
int xPin = A1;
int yPin = A0;
int buttonPin = 2;
int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
const int motorPin = 9;
void setup() {
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(motorPin, OUTPUT);
}
void loop() {
xPosition = analogRead(xPin);
yPosition = analogRead(yPin);
buttonState = digitalRead(buttonPin);
checkX();
switch (xPosition) {
case 1023:
analogWrite(motorPin, 200);
break;
case 0:
analogWrite(motorPin, 0);
break;
default:
analogWrite(motorPin, 0);
break;
}
}
void checkX(){
analogRead(xPin);
I took into account your advise, and my code was not what is was originally as I spent some time looking for functions and code that might work. Now the motor goes faster with the serial commands I added, but still not full speed.
int xPin = A1;
int yPin = A0;
int buttonPin = 2;
int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
const int motorPin = 9;
void setup() {
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(motorPin, OUTPUT);
}
void loop() {
xPosition = analogRead(xPin);
yPosition = analogRead(yPin);
buttonState = digitalRead(buttonPin);
Serial.print("X: ");
Serial.print(xPosition);
Serial.print(" | Y: ");
Serial.print(yPosition);
Serial.print(" | Button: ");
Serial.println(buttonState);
if (xPosition >1020) {
analogWrite(motorPin, 255);
}
else{
analogWrite(motorPin, 0);
}
}
Again thank your for all the help. When I set xPosition to be 1023, the motor is up to full power and works fine. Also, I believe this is the diagram you are looking for. It is a 5 pin joystick I got from an Elegoo kit.
Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?
This is becoming essential to make sure your input is configured right.
Do you have each of the joystick pots wired as potential dividers.