本站改版新增arduino频道

Micropython
Arduino

arduino 超声波模块2


arduino 超声波模块2

const int trigPin = 1;
const int echoPin = 2;
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

 pinMode(trigPin, OUTPUT);  // 将trigPin设置为输出
 pinMode(echoPin, INPUT);   // 将echoPin设置为输入
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(trigPin, LOW);  
  delayMicroseconds(2);  
  // 将trigPin设置为HIGH状态10微秒
  digitalWrite(trigPin, HIGH);  
  delayMicroseconds(10);  
  digitalWrite(trigPin, LOW);   
//读取echoPin,返回声波传播时间(微秒)  
duration = pulseIn(echoPin, HIGH);    
  //计算距离  
  distanceCm = duration * SOUND_SPEED/2;    
  // 换算成英寸  
  distanceInch = distanceCm * CM_TO_INCH;   
   // 在串行监视器中打印距离  
   Serial.print("Distance (cm): ");  
   Serial.println(distanceCm);  
   Serial.print("Distance (inch): ");  
   Serial.println(distanceInch);  

  Serial.println("超声波感应");
 delay(2000);
}



推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 ESP56.com All Rights Reserved
晋ICP备14006235号-22 晋公网安备14108102001165号

执行时间: 0.0094659328460693 seconds