gpt4 book ai didi

c - 使用超声波传感器时距离等于什么公制单位?

转载 作者:行者123 更新时间:2023-11-30 19:24:41 25 4
gpt4 key购买 nike

我目前正在使用超声波接近传感器来测量水箱中的水量。我首先尝试接收传感器与反射波的物体之间的距离测量值。我尝试过构建自己的代码(用 C 语言),但是我不太确定我的问题出在哪里。我已经编写了在液晶显示屏上显示的代码。我得到的数字是 669、A45、h45。下面是我为执行此任务而编写的带注释的函数。

void distance_sensor(void)
{
DDRC= 0x0F; //enables only one nybble to be an output

double timecnt;
double distance;
int echo;

char distb [16] = {"Container up to:"};
lcd_write(distb, 16, line_1); //displays banner on LCD

echo = (PINC & 0x10); //declares the input echo from the 2nd nybble

distance= 0; //initialization
timecnt = 0;

PORTC = 0x00;
_delay_ms(1.0);

PORTC = 0x0F;
_delay_ms(5.2); //creating a 10 us output square wave and sending it out through port c
PORTC = 0x00;

while(echo==0)
{
echo = (PINC & 0x10); //rechecking the input
timecnt = timecnt + 1; //time taken for the wave to reflect back to the sensor
_delay_us(100.0);
}

timecnt= timecnt*100;
distance = (timecnt*0.000343)/2;
hextodec(distance); //function made to split the value into msd, nsd, lsd and displays on LCD

return;
}

最佳答案

一旦TRIG输入端出现高电平,超声波模块就会在ECHO输出端设置低电平,并发出一阵声音脉冲。如果有障碍物,声音爆发就会作为回声反射回来。一旦模块检测到回声,它就会在 ECHO 输出处设置高电平。

因此,距离等于发出声音和接收回声之间的时间乘以 speed of sound在空气中并除以二(因为声音来回传播的距离)

仅供引用,在 +20 °C 的干燥空气中,声速为 343 米每秒。

公式是你的代码是正确的

但是代码中存在几个问题。

1)

    PORTC = 0x0F;
_delay_ms(5.2); //creating a 10 us output square wave and sending it out through port c
PORTC = 0x00;

不要混淆 ms(毫秒)和 μs(微秒)。

在 5.2 毫秒内,声音传播 178 厘米,因此当您开始计算回声时,可能会得到错误的结果。

请问为什么,为什么要在4个输出上设置高电平?您只需在连接 TRIG 的引脚上进行设置。 (我不知道是哪个,就说是PC2吧)

PORTC = 0x0F;

    PORTC |= (1 << 2); // set high level at PC2
_delay_us(10); //creating a 10 us output square wave and sending it out through port c
PORTC &= ~(1 << 2); // set low level at PC2

2) 您正在将 echo 初始化为

echo = (PINC & 0x10);  //declares the input echo from the 2nd nybble

这是错误的。首先,因为 ECHO 信号在触发 TRIG 之前没有任何意义,其次,因为 ECHO 自上次测量以来一直保持高电平。因此,echo 变量将被初始化为非零,并且 while(echo==0) 永远不会进入循环。

3) 如果模块无法检测到反射回波,则它永远不会在 ECHO 输出上设置高电平。因此,您需要以某种方式限制循环等待的时间,否则,它永远不会结束。

4) 我不知道什么是 hextodec 以及当 float 传递给它时它是如何工作的。你确定它能正确显示小于 1.0 的 float 吗?我很确定它不会尝试扩大数字并将其转换为整数:

hextodec(lround(distance * 1000)); 

关于c - 使用超声波传感器时距离等于什么公制单位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60049038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com