1

我正在尝试从传感器接收信息,但是我的输出一直都是 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;
}
4

3 回答 3

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

于 2013-07-03T13:18:34.850 回答
1

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

于 2013-07-03T12:55:20.847 回答
1

经过多次尝试并感谢 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);
}
于 2013-07-03T14:33:51.770 回答