Joystick Controls DC Motor
From Microduino Wiki
Language: | English • 中文 |
---|
ContentsObjectiveTo control rotation of DC motor by Joystick. PrincipleBy detecting Joystick analog values in X- and Y-axes, you can control the rotation and direction of the DC motor. Equipment
Hardware Buildup
Software Debugging
#define PI 3.1415926
#define JoystickX_PIN A1 //Joystick X-axis output
#define JoystickY_PIN A0 //Joystick Y-axis output
#define PIN_MOTORA 5 //Motor output
#define PIN_MOTORB 6 // Motor output pin
valueX = (float)(analogRead(JoystickX_PIN)-512);
valueY = (float)(analogRead(JoystickY_PIN)-512);
valueL = sqrt(sq(valueX)+sq(valueY));
angle = asin(valueX/valueL)*180/PI; // Calculate the angle of Joystick by inverse trigonometric function
motorSpeed = (int)(angle*255/180); // Calculate rotation speed according to the angle.
if(motorSpeed > 0) // If the angle is positive, then the motor rotates clockwise.
{
digitalWrite(PIN_MOTORA, LOW);
analogWrite(PIN_MOTORB, motorSpeed);
}
else if(motorSpeed < 0) //If the angle is negative, then the motor rotates anti-clockwise.
{
digitalWrite(PIN_MOTORB, LOW);
analogWrite(PIN_MOTORA, abs(motorSpeed));
}
else //If the angle is zero, then the motor stops rotation.
{
digitalWrite(PIN_MOTORA, LOW);
digitalWrite(PIN_MOTORB, LOW);
}
delay(500); ProgramResultPush Joystick to different angle, you can see the rotation speed and direction will change accordingly. Video |