极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 9284|回复: 0

新手,超声波测距反应滞后

[复制链接]
发表于 2013-10-28 19:10:28 | 显示全部楼层 |阅读模式
测距模块为HC-SR04,用12864显示。代码摘自网上,运行没有问题,但是要跑一阵子才能稳定下来,反应滞后。人从跟前走过,数据没有变化。本来想如果有人走过,可以点亮LED。而且数据有抖动,170cm左右的距离,不知为什么偶尔会出现2米多的数据。有上下5cm的波动,不知是否正常。代码如下:
  1. #include <LCD12864RSPI.h>

  2. /*
  3. 日期:2013.5.18
  4. IDE 版本:1.0.1
  5. 功能:利用SR04超声波传感器进行测距,并用串口显示测出的距离值
  6. */

  7. // &#65533;趨SR04&#65533;&#65533;&#65533;&#1269;&#65533;Arduino&#65533;&#65533;&#65533;
  8. const int TrigPin = 5;
  9. const int EchoPin = 6;
  10. float distance;

  11. #define AR_SIZE( a ) sizeof( a ) / sizeof( a[0] )
  12. unsigned char unit[] = "cm";
  13. unsigned char messageString[]={
  14.   0xCA, 0xB5,
  15.   0xCA, 0xB1,
  16.   0xBE, 0xE0,
  17.   0xC0, 0xEB
  18. };                    ///实时距离

  19. char str[6];
  20. unsigned char show0[]={
  21.   0xB3, 0xAC,
  22.   0xC9, 0xF9,
  23.   0xB2, 0xA8,
  24.   0xB2, 0xE2,
  25.   0xBE, 0xE0
  26. };                    //超声波测距


  27. unsigned char msg[]={
  28.   0xD3, 0xD0,
  29.   0xC8, 0xCB,
  30.   0xBE, 0xAD,
  31.   0xB9, 0xFD,
  32.   0xA3, 0xA1
  33. };                    //有人经过!

  34. void setup()
  35. {   
  36.   // 初始化串口通信及连接SR04的引脚
  37.   //Serial.begin(9600);
  38.   pinMode(TrigPin, OUTPUT);
  39.   // 要检测引脚上输入的脉冲宽度,需要先设置为输入状态
  40.   pinMode(EchoPin, INPUT);
  41.   // 屏幕初始化
  42.   LCDA.Initialise();
  43.   delay(100);
  44. }
  45. void loop()
  46. {
  47.   //LCDA.CLEAR();//清屏
  48.   //delay(100);

  49.   LCDA.DisplayString(0,1,show0,AR_SIZE(show0));//第一行第二格开始,显示文字
  50.   //delay(100);

  51.   LCDA.DisplayString(1,0,messageString,AR_SIZE(messageString));//第二行第一格开始,显示文字实时距离
  52.   //delay(100);

  53.   // 产生一个10us的高脉冲去触发TrigPin
  54.   digitalWrite(TrigPin, LOW);
  55.   delayMicroseconds(2);
  56.   digitalWrite(TrigPin, HIGH);
  57.   delayMicroseconds(10);
  58.   digitalWrite(TrigPin, LOW);
  59.   // 检测脉冲宽度,并计算出距离
  60.   distance = pulseIn(EchoPin, HIGH) / 58.00;
  61.   if (distance<300)
  62.   {
  63.     dtostrf(distance,6,2,str);
  64.     LCDA.DisplayString(2,0,(unsigned char *)str,sizeof(str));
  65.     LCDA.DisplayString(2,3,unit,sizeof(unit));
  66.     delay(50);
  67.   }


  68.   //Serial.print(distance);
  69.   //Serial.print("cm");
  70.   //Serial.println();
  71.   delay(800);
  72. }



复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|联系我们|极客工坊

GMT+8, 2026-6-9 10:59 , Processed in 0.034598 second(s), 17 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表