读取一个超声波代码
Mixly
Arduino代码
volatile float dist;
float checkdistance_4_7() {
digitalWrite(4, LOW);
delayMicroseconds(2);
digitalWrite(4, HIGH);
delayMicroseconds(10);
digitalWrite(4, LOW);
float distance = pulseIn(7, HIGH) / 58.00;
delay(10);
return distance;
}
void setup(){
Serial.begin(9600);
dist = 0;
pinMode(4, OUTPUT);
pinMode(7, INPUT);
}
void loop(){
dist = checkdistance_4_7();
Serial.println(String(dist) + String("cm"));
}
需要知道的就是trig(4输出)引脚和Echo(7输入)引脚要接的位置,这个根据自己需要设置。
读取两个超声波代码
volatile float dist1;
volatile float dist2;
float checkdistance_4_7() {
digitalWrite(4, LOW);
delayMicroseconds(2);
digitalWrite(4, HIGH);
delayMicroseconds(10);
digitalWrite(4, LOW);
float distance1 = pulseIn(7, HIGH) / 58.00;
delay(10);
return distance1;
}
float checkdistance_2_3() {
digitalWrite(2, LOW);
delayMicroseconds(2);
digitalWrite(2, HIGH);
delayMicroseconds(10);
digitalWrite(2, LOW);
float distance2 = pulseIn(3, HIGH) / 58.00;
delay(10);
return distance2;
}
void setup(){
Serial.begin(9600);
dist1 = 0;
dist2 = 0;
pinMode(4, OUTPUT);
pinMode(7, INPUT);
pinMode(2, OUTPUT);
pinMode(3, INPUT);
}
void loop(){
dist1 = checkdistance_4_7();
dist2 = checkdistance_2_3();
Serial.println(dist1);
Serial.println("-----");
Serial.println(dist2);
// if ( Serial.available())
// {
// if('s' == Serial.read())
// Serial.println(dist);
// }
}
需要声明两个变量
volatile float dist1; volatile float dist2;
其他位置进行对应更改。