Arduino小车代码前后左右控制
作者:互联网
#include<Servo.h> 标签:前后左右,rightMotor1,rightMotor2,Arduino,小车,leftMotor1,HIGH,LOW,digitalWrite
来源: https://blog.csdn.net/qq_63524713/article/details/122502197
//有以下几种运动状态
#define STOP 0 //暂停stop
#define FORWARD 1 //前进
#define BACKWARD 2 //后退
#define TURNLEFT 3 //左转
#define TURNRIGHT 4 //右转
//需要用到的引脚
//定义电机的输入引脚分别为4,5,6,7,这些引脚是arduino开发板上的数字输入输出引脚,用于数字信号的读写,控制小车的执行//该小车是四个轮子,一共有四个电机
int leftMotor1=4;//左侧电机
int leftMotor2=5;//左侧电机
int rightMotor1=6;//右侧电机
int rightMotor2=7;//右侧电机
void setup()
{
//put yoursetup code here ,to run once: //设置控制电机的引脚为输出状态 pinMode(leftMotor1,OUTPUT); pinMode(leftMotor2,OUTPUT); pinMode(rightMotor1,OUTPUT); pinMode(rightMotor2,OUTPUT);
}
void loop()
{
//put your maincode here,to run repeatedly:int i;for(i=0;i<5;i++)
//依次执行前进,后退,左转,右转,暂停这5种运动状态
{
motorRun(i);
delay(3000);
//每个指令执行3s
}
}
//运动状态的控制函数如下
void motorRun(int i)
{
switch(i)
{
case FORWARD:
digitalWrite(leftMotor1,LOW);
//定义电机的输入引脚高低电平,可以更改此处来测试小车的运转 digitalWrite(leftMotor2,HIGH); digitalWrite(rightMotor1,LOW); digitalWrite(rightMotor2,HIGH); break;
case BACKWARD: digitalWrite(leftMotor1,HIGH); digitalWrite(leftMotor2,LOW); digitalWrite(rightMotor1,HIGH); digitalWrite(rightMotor2,LOW); break; case TURNLEFT: digitalWrite(leftMotor1,HIGH); digitalWrite(leftMotor2,LOW); digitalWrite(rightMotor1,LOW); digitalWrite(rightMotor2,HIGH); break; case TURNRIGHT: digitalWrite(leftMotor1,LOW); digitalWrite(leftMotor2,HIGH); digitalWrite(rightMotor1,HIGH); digitalWrite(rightMotor2,LOW); break; default: digitalWrite(leftMotor1,LOW); digitalWrite(leftMotor2,LOW); digitalWrite(rightMotor1,LOW); digitalWrite(rightMotor2,LOW); break;
}
}
代码亲测有效,不知道能不能实现上面的功能,感谢大家指点,你的鼓励也支持,是我不断更新创作的动力