Bill of Material:
直流马达(<9V, 2A) x2, 底盘 x1,9V电池 x1, 电池扣 x1, 摇杆模块 x1, L298N 马达驱动模块 x1, Arduino Uno x1, 面包板线。
.演示视频,拼装教程:
Arduino机器人快速上手经验分享
接线图
程式/代码:
/*
Demonstrates the use of Joystick control with Arduino UNO and L298N Motor Driver MOdule.
Last Edited: Jan.4th.2020 by Mun Kim
*/
int in1 = 3; // Direction Control: Motor 1(Left Hand Side)
int in2 = 4; // Direction Control: Motor 1(Left Hand Side)
int enA = 5; // Power Control: Motor 1
int in3 = 7; // Direction Control: Motor 2 (Right Hand Side)
int in4 = 8; // Direction Control: Motor 2 (Right Hand Side)
int enB = 9; // Power Control: Motor 2
int MotorSpeed1 = 0; // Motor 1 Speed Values - Start at zero
int MotorSpeed2 = 0; // Motor 2 Speed Values - Start at zero
int joyHorz = A0; // Joystick Input: Horizontal(X-axis)
int joyVert = A1; // Joystick Input: Vertical(Y-axis)
// Joystick Values - Start at 512 (middle position)
int joyposVert = 512;
int joyposHorz = 512;
void setup()
{
// Set all the motor control pins to outputs
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
// Start with motors disabled and direction forward
digitalWrite(enA, LOW);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(enB, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
}
void loop() {
// Read the Joystick X and Y positions
joyposVert = analogRead(joyVert);
joyposHorz = analogRead(joyHorz);
// Forward and backward drive
if (joyposVert < 460) //Backward
{
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
joyposVert = -joyposVert +460; // As we are going backwards we need to reverse readings
MotorSpeed1 = map(joyposVert, 0, 460, 0, 255);
MotorSpeed2 = map(joyposVert, 0, 460, 0, 255);
}
else if (joyposVert > 564) //Forward
{
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
MotorSpeed1 = map(joyposVert, 564, 1023, 0, 255);
MotorSpeed2 = map(joyposVert, 564, 1023, 0, 255);
}
else //Stopped
{
MotorSpeed1 = 0;
MotorSpeed2 = 0;
}
//Left and right steering: The horizontal position weights the motor speed
if (joyposHorz < 460) //Leftward
{
joyposHorz = -joyposHorz + 460; // Again, reverse the readings here.
joyposHorz = map(joyposHorz, 0, 460, 0, 255);
MotorSpeed1 = MotorSpeed1 - joyposHorz;
MotorSpeed2 = MotorSpeed2 + joyposHorz;
if (MotorSpeed1 < 0)MotorSpeed1 = 0;
if (MotorSpeed2 > 255)MotorSpeed2 = 255;
}
else if (joyposHorz > 564) //Rightward
{
joyposHorz = map(joyposHorz, 564, 1023, 0, 255);
MotorSpeed1 = MotorSpeed1 + joyposHorz;
MotorSpeed2 = MotorSpeed2 - joyposHorz;
if (MotorSpeed1 > 255)MotorSpeed1 = 255;
if (MotorSpeed2 < 0)MotorSpeed2 = 0;
}
// Adjust to prevent "buzzing" at very low speed
if (MotorSpeed1 < 8)MotorSpeed1 = 0;
if (MotorSpeed2 < 8)MotorSpeed2 = 0;
// Set the motor speeds
analogWrite(enA, MotorSpeed1);
analogWrite(enB, MotorSpeed2);
}
版权声明:本文为robotixworkshop原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。