编程语言
首页 > 编程语言> > ARDUINO超声波程序

ARDUINO超声波程序

作者:互联网

电路连接:

超声波传感器Trig -> 7

超声波传感器Echo -> 6

VCC -> VCC     GND -> GND

源代码:

const int pingPin = 7;     
const int echoPin = 6;

void setup() {
  Serial.begin(9600); 
}

void loop() {
  long duration, cm;
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(pingPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  cm = microsecondsToCentimeters(duration);
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(100);

  if(cm < 250){
    for(int i = 250;i <= 500;i++){
      tone(4,i);
      delay(10);
    }
    for(int i = 500;i >= 250;i--){
      tone(4,i);
      delay(10);
    }
  }
  noTone(4);
}

long microsecondsToInches(long microseconds) {
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  return microseconds / 29 / 2;
}

标签:cm,ARDUINO,int,程序,long,microseconds,pingPin,超声波,Serial
来源: https://blog.csdn.net/qq_54865042/article/details/120623808