請問...如果想要用一個joystick來控制兩顆直流馬達的動作
讓一台玩具車前進、後退、前左轉、前右轉、後左轉、後右轉等
目前我前近跟後退這邊可以說是成功了...
但是轉彎方面老是想不通...
int JXin = 0; // XMotorPower input
int JYin = 1; // YMotorPower input
int XMotor_OutPin = 5; // Xout
int XMOTAspeed = 3;
int YMotor_OutPin = 6; // Yout
int YMOTAspeed = 4;
int JX_Value = 0; // Xprint
int JY_Value = 0; // Yprint
int XMotor_Value = 0; //FB
int YMotor_Value = 0;
int JX = 0;
int Xspeed;
int Yspeed;
int dirX ;
int dirY ;
void setup()
{
Serial.begin(9600);
pinMode(XMotor_OutPin, OUTPUT);
pinMode(XMOTAspeed, OUTPUT);
pinMode(YMotor_OutPin, OUTPUT);
pinMode(YMOTAspeed, OUTPUT);
Yspeed = 0;
Xspeed = 0;
dirX = 1;
dirY = 1;
}
void MOTORDRIVE(int Xspeed , int dirX , int Yspeed , int dirY)
{
analogWrite(XMOTAspeed,Xspeed);
analogWrite(YMOTAspeed,Yspeed);
if(dirX == 0 , dirY == 0 )
{
digitalWrite(XMOTAspeed,LOW);
digitalWrite(YMOTAspeed,LOW);
}
else
{
digitalWrite(XMOTAspeed, HIGH);
digitalWrite(YMOTAspeed, HIGH);
}
if(dirX == 1, dirY == 0 )
{
digitalWrite(XMOTAspeed,HIGH);
digitalWrite(YMOTAspeed,LOW);
}
else
{
digitalWrite(XMOTAspeed, LOW);
digitalWrite(YMOTAspeed, HIGH);
if(dirX == 0 , dirY == 1 )
{
digitalWrite(XMOTAspeed,LOW);
digitalWrite(YMOTAspeed,HIGH);
}
else
{
digitalWrite(XMOTAspeed, HIGH);
digitalWrite(YMOTAspeed, LOW);
}
}
}
void loop()
{
//讀取滑桿式可變電阻的電壓值 範圍:0 - 1023
int JX_Value = analogRead(JXin);//依據不同的電壓值-起動馬達的各種動作
int JY_Value = analogRead(JXin);
MOTORDRIVE(Xspeed , dirX, Yspeed , dirY);
if(JX_Value<500)
{
dirX = 0;
dirY = 0;
XMotor_Value = map(JX_Value, 0, 500 , 250, 0) ;
YMotor_Value = map(JY_Value, 0, 500 , 250, 0) ;
}
if(JX_Value>=500 && JX_Value <=520)
{
dirX =1;
dirY =1;
XMotor_Value = 0;
YMotor_Value = 0;
}
if(JX_Value>521)
{
dirX = 1;
dirY = 1;
XMotor_Value = map(JX_Value, 521, 1023, 0, 250);
YMotor_Value = map(JY_Value, 521, 1023, 0, 250);
}
analogWrite(XMotor_OutPin, XMotor_Value); // change the analog out value:
analogWrite(YMotor_OutPin, YMotor_Value);
Serial.print("XMotor = " );
Serial.print(XMotor_Value );
Serial.print("\t YMotor = " );
Serial.println(YMotor_Value );
} |