楼主,如果接入三个超声波测距怎么接呢?我做了但是超声测距模块不管用啊,求解- #include <AFMotor.h>
- int inputPin1=15; // 定义超声波Trig
- int outputPin1=14; // 定义超声波Echo
- int inputPin2=16; // 定义超声波Trig
- int outputPin2=17;
- int inputPin3=18; // 定义超声波Trig
- int outputPin3=19;
- float distanceL;
- float distanceR;
- float distanceF;
- AF_DCMotor motor1(1, MOTOR12_64KHZ);// 创建电机#1号,速度是64KHz pwm
- AF_DCMotor motor2(2, MOTOR12_64KHZ);// 创建电机#2号,速度是64KHz pwm
- AF_DCMotor motor3(3, MOTOR34_64KHZ);// 创建电机#3号,速度是64KHz pwm
- AF_DCMotor motor4(4, MOTOR34_64KHZ);// 创建电机#4号,速度是64KHz pwm
- void setup()
- {
- Serial.begin(9600);
- pinMode(inputPin1, INPUT);
- pinMode(outputPin1, OUTPUT);
- pinMode(inputPin2, INPUT);
- pinMode(outputPin2, OUTPUT);
- pinMode(inputPin3, INPUT);
- pinMode(outputPin3, OUTPUT);
- }
- void loop()
- {
- digitalWrite(outputPin1, LOW); // 使发出发出超声波信号接口低电平2μs
- delayMicroseconds(2);
- digitalWrite(outputPin1, HIGH); // 使发出发出超声波信号接口高电平10μs,这里是至少10μs
- delayMicroseconds(10);
- digitalWrite(outputPin1, LOW);
- // 保持发出超声波信号接口低电平
- int distanceL = pulseIn(inputPin1, HIGH); // 读出脉冲时间
- distanceL= distanceL/58; // 将脉冲时间转化为距离(单位:厘米)
- Serial.println(distanceL); //输出距离值
- delay(50);
- digitalWrite(outputPin2, LOW); // 使发出发出超声波信号接口低电平2μs
- delayMicroseconds(2);
- digitalWrite(outputPin2, HIGH); // 使发出发出超声波信号接口高电平10μs,这里是至少10μs
- delayMicroseconds(10);
- digitalWrite(outputPin2, LOW);
- // 保持发出超声波信号接口低电平
- int distanceF= pulseIn(inputPin2, HIGH); // 读出脉冲时间
- distanceF=distanceF/58; // 将脉冲时间转化为距离(单位:厘米)
- Serial.println(distanceF); //输出距离值
- delay(50);
- digitalWrite(outputPin3, LOW); // 使发出发出超声波信号接口低电平2μs
- delayMicroseconds(2);
- digitalWrite(outputPin3, HIGH); // 使发出发出超声波信号接口高电平10μs,这里是至少10μs
- delayMicroseconds(10);
- digitalWrite(outputPin3, LOW);
- // 保持发出超声波信号接口低电平
- int distanceR= pulseIn(inputPin3, HIGH); // 读出脉冲时间
- distanceR=distanceR/58; // 将脉冲时间转化为距离(单位:厘米)
- Serial.println(distanceR); //输出距离值
- delay(50);
- if (distanceL==50&distanceF==50&distanceR==50) //等于50厘米就停止
- {
- motor1.run(RELEASE);// 电机停止
- motor2.run(RELEASE);// 电机停止
- motor3.run(RELEASE);// 电机停止
- motor4.run(RELEASE);// 电机停止
- }
- if (distanceL> 50&distanceF>50&distanceR>50) //大于50厘米就前进
- {
- motor1.run(FORWARD);// 电机前进
- motor1.setSpeed(255);// 设置电机速度,从200/255之间任意
- motor2.run(FORWARD);// 电机前进
- motor2.setSpeed(255);// 设置电机速度,从200/255之间任意
- motor3.run(FORWARD);// 电机前进
- motor3.setSpeed(255);// 设置电机速度,从200/255之间任意
- motor4.run(FORWARD);// 电机前进
- motor4.setSpeed(255);// 设置电机速度,从200/255之间任意
- }
- if (distanceL< 50&distanceF< 50&distanceR< 50) //小于50厘米就后退
- {
- motor1.run(BACKWARD);// 电机后退
- motor1.setSpeed(255);// 设置电机速度,从200/255之间任意
- motor2.run(BACKWARD);// 电机后退
- motor2.setSpeed(255);// 设置电机速度,从200/255之间任意
- motor3.run(BACKWARD);// 电机后退
- motor3.setSpeed(255);// 设置电机速度,从200/255之间任意
- motor4.run(BACKWARD);// 电机后退
- motor4.setSpeed(255);// 设置电机速度,从200/255之间任意
- }
- }
复制代码 |