繁体   English   中英

Arduino超声波距离传感器

[英]Arduino ultrasonic distance sensor

我试图从我的传感器接收信息,但是我的输出始终只是0,我的代码中有什么问题吗? 硬件相关的一切都做得很好。

loop()
{
    long duration, inches, cm;

    pinMode(pingPin, OUTPUT);
    digitalWrite(pingPin, LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin, LOW);

    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);

    inches = microsecondsToInches(duration);
    cm = microsecondsToCentimeters(duration);

    Serial.print(inches);
    Serial.print("in; ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
}

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

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

您拥有的传感器不使用PWM作为发送距离的方式。 相反,它使用serail连接。 问题是你在Arduino上没有额外的串行硬件。

您可以使用arduino的serail端口来读取传感器数据,但是您无法将任何内容记录到屏幕上

串行连接的运行速度为9600波特,可以在软件中快速模拟。

我建议您购买使用标准PWM通信模式的传感器。 这样做可以避免一些麻烦。但我应该告诉你有一种方法。 它使用的是软件序列库。 该库将帮助您使用数字引脚,就像它们是serail引脚一样。

http://arduino.cc/en/Reference/SoftwareSerial

http://www.suntekstore.com/goods-14002212-3-pin_ultrasonic_sensor_distance_measuring_module.html

http://iw.suntekstore.com/attach.php?id=14002212&img=14002212.doc

您正在使用Parallax PING的代码,该代码使用与您拥有的协议不同的协议。 这是传感器数据表的链接 它通过标准串行以每50ms 9600bps的速率输出。

经过多次尝试并得到John b的帮助,这被认为是如何正确使用这种传感器的正确答案,它完全按照需要工作,输出完美测量

#include <SoftwareSerial.h>

// TX_PIN is not used by the sensor, since that the it only transmits!
#define PING_RX_PIN 6
#define PING_TX_PIN 7

SoftwareSerial mySerial(PING_RX_PIN, PING_TX_PIN);

long inches = 0, mili = 0;
byte mybuffer[4] = {0};
byte bitpos = 0;

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

  mySerial.begin(9600);
}


void loop() {
  bitpos = 0;
  while (mySerial.available()) {
    // the first byte is ALWAYS 0xFF and I'm not using the checksum (last byte)
    // if your print the mySerial.read() data as HEX until it is not available, you will get several measures for the distance (FF-XX-XX-XX-FF-YY-YY-YY-FF-...). I think that is some kind of internal buffer, so I'm only considering the first 4 bytes in the sequence (which I hope that are the most recent! :D )
    if (bitpos < 4) {
      mybuffer[bitpos++] = mySerial.read();
    } else break;
  }
  mySerial.flush(); // discard older values in the next read

  mili = mybuffer[1]<<8 | mybuffer[2]; // 0x-- : 0xb3b2 : 0xb1b0 : 0x--
  inches = 0.0393700787 * mili;
  Serial.print("PING: ");
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(mili);
  Serial.print("mili");
  Serial.println();

  delay(100);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM