I am using an Arduino Nano to control a dc motor using a joystick module. I want to use the yAxis of joystick module to control the motor in both directions. But the motor only moves in 1 direction.
This is the code i used.
#define enA 9
#define in1 5
#define in2 6
int xAxis, yAxis;
int jPin1=A1;
int jPin2=A2;
int motorSpeedA = 0;
int motorSpeedB = 0;
void setup() {
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
Serial.begin(9600);
}
void loop() {
xAxis=analogRead(jPin1);
yAxis=analogRead(jPin2);
Serial.println(yAxis);
Serial.println(xAxis);
if (yAxis < 470) {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
motorSpeedA = map(yAxis, 470, 0, 0, 255);
}
else if (yAxis > 550) {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
motorSpeedA = map(yAxis, 550, 1023, 0, 255);
}
else {
motorSpeedA = 0;
}
analogWrite(enA, motorSpeedA); // Send PWM signal to motor A
}