在淘宝“高校基地”店买了一个http://item.taobao.com/item.htm?spm=a1z0k.6846101.1130973605.d4915209.SAObbz&id=36884805726,还有一种是PWM输出,这个代码比较多,就是最普遍的发送命令,然后等待信号,再计时,用声速推算距离,但是TX输出把我搞乱了。
终于在http://forum.arduino.cc/index.php?topic=88388.5;wap2找到了答案:
#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 7SoftwareSerial 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! 😀 )
if (bitpos < 4) {
mybuffer[bitpos++] = mySerial.read();
} else break;
}
mySerial.flush(); // discard older values in the next readmili = 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”);delay(100);
}
说明:模块每次输出一帧,含4个8位数据,帧格式为:0XFF+H_DATA+L_DATA+SUM
1、0XFF: 为一帧开始数据,用于判断。
2、H_DARA:距离数据的高8位。
3、L_DATA:距离数据的低8位。
4、SUM: 数据和用于交验。其0XFF+H_DATA+L_DATA=SUM(仅低8位)
5、H_DATA与L_DATA合成16位数据,即以毫米为单位的距离值。
注意:模块检测最小距离为30cm,在30cm内有物体,将获得不准确信号。
以上代码中没有做SUM校验