arduino控制SR04超声波模块的脉冲宽度测量函数及超声波测距

pulseln()

检测指定引脚上的脉冲信号宽度。

语法:

pulseIn(pin,value)

pulseIn(pin,value,timeout)

value为所需读取的是HIGH or LOW

timeout为超时时间,数据类型为无符号的长整型,单位:us

换行显示脉冲宽度,单位:us,若在指定时间内未检测到则退出pulseIn()函数并返回值为0;没有设置超时时间默认为1。

超声波:频率高于20000HZ的声波,指向性强,能量损耗慢,在介质之间传播距离较远,故经常用来测距。

距离=340m/s*t/2

SR04超声波模块:

Vcc:5v

Trig:触发引脚

Echo:回馈引脚

Gnd:地

给Trig引脚至少10us的高电平信号,触发SR04模块的测距功能,自动发送8个40kHZ的超声波脉冲,此时若有信号返回则Echo会输出高电平,高电平持续的时间就是超声波和从发射到返回的时间。

代码如下:

const int TrigPin = 2;
const int EchoPin = 3;
float distance;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(TrigPin,OUTPUT);
  pinMode(EchoPin,INPUT);
  Serial.println("ULtrasonic sensor:");
}
void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(TrigPin,LOW);
  delayMicroseconds(2);
  digitalWrite(TrigPin,HIGH);
  delayMicroseconds(10);
  digitalWrite(TrigPin,LOW);
  //计算
  distance = pulseIn(EchoPin,HIGH)/58.00;
  Serial.print(distance);
  Serial.print("cm");
  Serial.println();
  delay(1000);
}

通过打开串口监视器即可观察到到所测距离数值。

发布了31 篇原创文章 · 获赞 28 · 访问量 9507

猜你喜欢

转载自blog.csdn.net/visual_eagle/article/details/103165860