const int EchoPin = 2//超声波信号输入
const int TrigPin = 3//超声波控制信号输出
int currDist = 0
void setup(){
pinMode(EchoPin, INPUT)
for (int pinindex = 3pinindex <8pinindex++) {
pinMode(pinindex, OUTPUT)// set pins 3 to 10 as outputs
}
pinMode(A0,OUTPUT)
pinMode(A1,OUTPUT)
pinMode(A2,OUTPUT)
pinMode(A3,OUTPUT)
digitalWrite(A0,LOW)
digitalWrite(A1,LOW)
digitalWrite(A2,LOW)
digitalWrite(A3,LOW)
Serial.begin(9600)
}
void loop(){
currDist = MeasuringDistance()//读取前端距离
//Serial.println(currDist)
if(currDist >25){
}
//power开关看个人需要,这里没有启用
//else if(currDist <8){
// mpower()
// }
else if(currDist <7){
mpause()
}
else if(currDist <15){
mnext()
}
else if(currDist <25){
mprev()
}
}
long MeasuringDistance() {
long duration
digitalWrite(TrigPin, LOW)
delayMicroseconds(2)
digitalWrite(TrigPin, HIGH)
delayMicroseconds(10)
digitalWrite(TrigPin, LOW)
duration = pulseIn(EchoPin, HIGH)
return duration / 29 / 2
}
//mplay播放
void mplay() {
digitalWrite(A0, HIGH)
delay(100)
digitalWrite(A0, LOW)
Serial.println("mplay")
}
//mprev上一首
void mprev() {
digitalWrite(A1, HIGH)
delay(1000)
digitalWrite(A1, LOW)
Serial.println("mprev")
}
//mnext下一首
void mnext() {
digitalWrite(A2, HIGH)
//return
delay(1000)
digitalWrite(A2, LOW)
Serial.println("mnext")
}
//mpause暂停
void mpause() {
digitalWrite(A0, HIGH)
delay(1000)
digitalWrite(A0, LOW)
Serial.println("mpause")
}
//mpower
//void mpower() {
// digitalWrite(A3, HIGH)
// delay(500)
//digitalWrite(A3, LOW)
// Serial.println("mpower")
//}
#include <Wire.h>#include "MPU6050.h"
#include <Ultrasonic.h>
#include "I2Cdev.h"
#define LED_PIN 13 //指示灯
//MPU6050陀螺仪
//MPU6050 my_gyro(3)
//使用ax, rx来获取二轮车姿态
//x轴加速度 &偏转角
short ax,rx
//short = int16_t
//HC-SRO4超声波传感器
//TRIG_PIN &ECHO_PIN
Ultrasonic my_hcsr(5,6)
float distance
int startTime
void setup() {
pinMode(LED_PIN,LOW)
//加入I2C总线
Wire.begin()
//初始化串口通信频道
Serial.begin(9600)
//初始化模块
//my_gyro.initialize()
my_hcsr.measure()
startTime = millis()
//初始化完成后指示灯常亮
pinMode(LED_PIN,HIGH)
}
void loop() {
//获取车身姿态
//ax=my_gyro.getAccelerationX()
//rx=my_gyro.getRotationX()
//获取前方障碍物距离
my_hcsr.measure()
distance=millis()-startTime
distance/=1000
distance=my_hcsr.get_cm()
Serial.print(distance,3)
Serial.println("cm")
delay(50)
}
这是因为你程序里距离变量没改变,也就是说你上次进入if时距离变量一直保存着,所以程序自动一直进入if语句,改下程序,以前做小车也遇到过,就是只要进入设定距离,小车就一直停在那里没有动作,距离显示一直定格在当前距离,这个程序你用keil调试不了,因为你的超声波回波信号模拟不出来,那个一直停留在while(!echo)或者while(echo)里面,所以只有实践,调试,再实践欢迎分享,转载请注明来源:内存溢出
评论列表(0条)