Joystick控制直流电机
Language | English |
---|
目的通过Joystick摇杆来控制直流电机的转动。 原理通过检测Joystick摇杆在水平和垂直两个方向上的模拟量来做出控制。在水平方向上控制电机的速度,用PWM来调节速度。在垂直方向上控制电机的方向,通过控制高低电平信号。 设备
准备
调试
#define Pin_X A1
#define Pin_Y A0
//D6,D8控制1A,1B的电机
#define OUT1A 6
#define OUT1B 8
//D5,D7控制2A,2B的电机
#define OUT2A 5
#define OUT2B 7
int value, data;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); //串口初始化
pinMode(Pin_X, INPUT);
pinMode(Pin_Y, INPUT);
pinMode(OUT1A, OUTPUT);
pinMode(OUT1B, OUTPUT);
pinMode(OUT2A, OUTPUT);
pinMode(OUT2B, OUTPUT);
}
int uiStep() //切歌
{
if (analogRead(Pin_Y) < 100) //Y-up
{
delay(50);
if (analogRead(Pin_Y) < 100)
return 1;
}
if (analogRead(Pin_Y) > 900) //Y-down
{
delay(50);
if (analogRead(Pin_Y) > 900)
return 2;
}
if (analogRead(Pin_X) < 100)
{
delay(50);
if (analogRead(Pin_X) < 100) //X-Right
return 3;
}
if (analogRead(Pin_X) > 900) //X-Left
{
delay(50);
if (analogRead(Pin_X) > 900)
return 4;
}
return 0;
}
void loop() {
if (uiStep() == 1)
{
value += 5;
if (value > 255)
value = 255;
}
else if (uiStep() == 2)
{
value -= 5;
if (value < 0)
value = 0;
}
else if (uiStep() == 3)
data = 0;
else if (uiStep() == 4)
data = 1;
motor_sta(data, value);
Serial.print(data);
Serial.print(" ");
Serial.println(value);
}
void motor_sta(int num, int fadeValue)
{
if (num == 0)
{
analogWrite(OUT1A, fadeValue);
digitalWrite(OUT1B, LOW);
analogWrite(OUT2A, fadeValue);
digitalWrite(OUT2B, LOW);
}
else if (num == 1)
{
digitalWrite(OUT1A, LOW);
analogWrite(OUT1B, fadeValue);
digitalWrite(OUT2A, LOW);
analogWrite(OUT2B, fadeValue);
}
}
软件调试
#define Pin_X A1
#define Pin_Y A0
//D6,D8控制1A,1B的电机
#define OUT1A 6
#define OUT1B 8
//D5,D7控制2A,2B的电机
#define OUT2A 5
#define OUT2B 7
if (uiStep() == 1)
{
value += 5;
if (value > 255)
value = 255;
}
else if (uiStep() == 2)
{
value -= 5;
if (value < 0)
value = 0;
}
else if (uiStep() == 3)
data = 0;
else if (uiStep() == 4)
data = 1;
结果将Joystick的摇杆推到不同方向,可以看到电机的转速及方向也会跟着变化。
|