Arduino Nano小车7种状态控制

这是之前写的代码。
使用到的主要的硬件材料:
1.12v可充电锂电池(给L298N和Nano供电)
2.Arduino nano开发板
3.L298N电机驱动模块

代码:

//Arduino小车控制-实现小车的前进、后退、左转、右转、加速、减速、停止
//ENA-9,  IN1-3,  IN2-4,  IN3-5,  IN4-6,  ENB-10

//引脚对应
int ENA = 9;
int IN1 = 3;
int IN2 = 4;
int IN3 = 5;
int IN4 = 6;
int ENB = 10;

int PWM = 0;
int speeds = 0;//全局变量,范围:0-255,50速度适中
int ChangeSteps = 5;//加速或减速的变化步长


//函数定义
void forward();//小车前进
void backward();//小车后退
void left();//小车左转
void right();//小车右转
void stops();//小车停止
void speed_up();//加速
void speed_down();//减速


void setup() {
  pinMode(ENA,OUTPUT);  //ENA
  pinMode(IN1,OUTPUT);  //IN1
  pinMode(IN2,OUTPUT);  //IN2
  pinMode(IN3,OUTPUT);  //IN3
  pinMode(IN4,OUTPUT);  //IN4
  pinMode(ENB,OUTPUT);  //ENB

  speeds = 60;//初始速度
}

void loop() {
     forward();
     delay(1000);
     backward();
     delay(1000);
     left();
     delay(1000);
     right();
     delay(1000);
     speed_up();
     delay(1000);
     speed_down();  
     delay(1000);       
     stops();
     delay(1000);
}

/*小车前进*/
void  forward()
{ 
  analogWrite(ENA,speeds);//ENA
  analogWrite(ENB,speeds);//ENB
  
  digitalWrite(IN1,HIGH);//左电机正转
  digitalWrite(IN2,LOW);
  
  digitalWrite(IN3,LOW);//右电机正转
  digitalWrite(IN4,HIGH);

}

/*小车后退*/
void  backward()
{ 
  analogWrite(ENA,speeds);//ENA
  analogWrite(ENB,speeds);//ENB
  
  digitalWrite(IN1,LOW);//左电机反转
  digitalWrite(IN2,HIGH);
  
  digitalWrite(IN3,HIGH);//右电机反转
  digitalWrite(IN4,LOW);
}

/*小车左转*/
void  left()
{ 
  analogWrite(ENA,0);//ENA
  analogWrite(ENB,speeds);//ENB
  
  digitalWrite(IN3,HIGH);//右电机正转
  digitalWrite(IN4,LOW);
  digitalWrite(IN1,LOW);//左电机不转
  digitalWrite(IN2,LOW);

}

/*小车右转*/
void  right()
{ 
  analogWrite(ENA,speeds);//ENA
  analogWrite(ENB,0);//ENB
  
  digitalWrite(IN1,HIGH);//左电机正转
  digitalWrite(IN2,LOW);
  digitalWrite(IN3,LOW);//右电机不转
  digitalWrite(IN4,LOW);
}

/*小车停止*/
void  stops()
{ 
  analogWrite(ENA,0);//ENA
  analogWrite(ENB,0);//ENB
}

void speed_up()//加速
{
  if(speeds >= 90)//设置一个最大速度,可以根据需要是否设置最大速度
    speeds = 90;
  else
    speeds += ChangeSteps;
}

void speed_down()//减速
{
  if(speeds <= 0)
    speeds = 0;
  else  
    speeds -= ChangeSteps;
}

你可能感兴趣的:(Arduino,单片机,嵌入式硬件)