const int TrigPin = 36;
const int EchoPin = 37;
float distance;
int PWM1=2; //连接电机1调速端口到数字接口2
int CW1=35; //连接电机1转向端口到数字接口35
int PWM2=3; //连接电机2调速端口到数字接口3
int CW2=34; //连接电机2转向端口到数字接口34
int PWM3=4; //连接电机1调速端口到数字接口4
int CW3=33; //连接电机1转向端口到数字接口33
int PWM4=5; //连接电机2调速端口到数字接口5
int CW4=32; //连接电机2转向端口到数字接口32
int PWM5=6; //连接电机1调速端口到数字接口6
int CW5=31; //连接电机1转向端口到数字接口31
int PWM6=7; //连接电机2调速端口到数字接口7
int CW6=30; //连接电机2转向端口到数字接口30
void setup()
{
// 初始化串口通信及连接SR04的引脚
Serial.begin(9600);
pinMode(TrigPin, OUTPUT);
// 要检测引脚上输入的脉冲宽度,需要先设置为输入状态
pinMode(EchoPin, INPUT);
Serial.println("Ultrasonic sensor:");
pinMode(PWM1, OUTPUT); //定义PWM输出
pinMode(CW1, OUTPUT); //定义CW输出
pinMode(PWM2, OUTPUT); //定义PWM输出
pinMode(CW2, OUTPUT); //定义CW输出
pinMode(PWM3, OUTPUT); //定义PWM输出
pinMode(CW3, OUTPUT); //定义CW输出
pinMode(PWM4, OUTPUT); //定义PWM输出
pinMode(CW4, OUTPUT); //定义CW输出
pinMode(PWM5, OUTPUT); //定义PWM输出
pinMode(CW5, OUTPUT); //定义CW输出
pinMode(PWM6, OUTPUT); //定义PWM输出
pinMode(CW6, OUTPUT); //定义CW输出
}
void advance()//前进
{
digitalWrite(PWM1,HIGH);
digitalWrite(PWM2,HIGH);
digitalWrite(CW1,LOW);
digitalWrite(CW2,LOW);
digitalWrite(PWM3,HIGH);
digitalWrite(PWM4,HIGH);
digitalWrite(CW3,LOW);
digitalWrite(CW4,LOW);
digitalWrite(PWM5,HIGH);
digitalWrite(PWM6,HIGH);
digitalWrite(CW5,LOW);
digitalWrite(CW6,LOW);
}
void back()//后退
{
digitalWrite(PWM1,HIGH);
digitalWrite(PWM2,HIGH);
digitalWrite(CW1,HIGH);
digitalWrite(CW2,HIGH);
digitalWrite(PWM3,HIGH);
digitalWrite(PWM4,HIGH);
digitalWrite(CW3,HIGH);
digitalWrite(CW4,HIGH);
digitalWrite(PWM5,HIGH);
digitalWrite(PWM6,HIGH);
digitalWrite(CW5,HIGH);
digitalWrite(CW6,HIGH);
}
void zuozhuan()//左转
{
digitalWrite(PWM1,HIGH);
digitalWrite(PWM2,HIGH);
digitalWrite(CW1,LOW);
digitalWrite(CW2,HIGH);
digitalWrite(PWM3,HIGH);
digitalWrite(PWM4,HIGH);
digitalWrite(CW3,LOW);
digitalWrite(CW4,HIGH);
digitalWrite(PWM5,HIGH);
digitalWrite(PWM6,HIGH);
digitalWrite(CW5,LOW);
digitalWrite(CW6,HIGH);
}
void youzhuan()//右转
{
digitalWrite(PWM1,HIGH);
digitalWrite(PWM2,HIGH);
digitalWrite(CW1,HIGH);
digitalWrite(CW2,LOW);
digitalWrite(PWM3,HIGH);
digitalWrite(PWM4,HIGH);
digitalWrite(CW3,HIGH);
digitalWrite(CW4,LOW);
digitalWrite(PWM5,HIGH);
digitalWrite(PWM6,HIGH);
digitalWrite(CW5,HIGH);
digitalWrite(CW6,LOW);
}
void loop()
{
// 产生一个10us的高脉冲去触发TrigPin
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
// 检测脉冲宽度,并计算出距离
distance = pulseIn(EchoPin, HIGH) / 58.00;
Serial.print(distance);
Serial.print("cm");
Serial.println();
delay(50);
if (distance < 80) //等于50厘米就左转
{
zuozhuan();//小车左转
delay( 500);//延迟1秒
}
if (distance < 3400 ) //小于120厘米就前进
{
advance();//小车前进
}
if (distance < 70 ) //小于120厘米就前进
{
back();//小车前进
delay(100);//延迟1秒
}
} |