|
前面有人写过测距程序(https://www.cirmall.com/bbs/thread-11401-1-1.html),没注意到,自己从头写了一个,发现精度很好,发上来给大家玩玩
买板子的时候在淘宝买了个人体探头和超声探头,非常便宜:
http://item.taobao.com/item.htm?id=18046651946
本程序用gpio 1除非trip管脚,用adc 3采样,输出如下:
Usage ./dist trig(gpio 0~13) echo(adc 2~5)
Trig GPIO: 1, Echo ADC: 2
distance: 322cm
distance: 11cm
distance: 11cm
distance: 3716cm
这个程序从Echo上升沿开始计时,到下降沿结束作为具体计算: Echo时间*声速340/2
源代码:- /*
- * Distance test program
- */
- #include <core.h>
- int trig_pin = 1; //2nd pin of GPIO
- int echo_pin = 2; //3rd ADC pin, 12bits, 4096 max
- void setup()
- {
- if ( argc != 2)
- {
- printf("Usage %s trig(gpio 0~13) echo(adc 2~5)\n", argv[0]);
- } else if(argc==2) {
- trig_pin = atoi(argv[1]);
- echo_pin = atoi(argv[2]);
- }
- printf("Trig GPIO: %d, Echo ADC: %d\n", trig_pin, echo_pin);
- pinMode(trig_pin, OUTPUT);
- }
- void loop()
- {
- unsigned long time;
- int value;
- digitalWrite(trig_pin, HIGH);
- while(1) {
- value = analogRead(echo_pin); // get adc value
- if (value > 2048) { // send out
- time = micros();
- break;
- }
- }
- while(1) {
- value = analogRead(echo_pin); // get adc value
- if (value < 2048 ) { //echo stop
- printf("distance: %lucm\n", (micros() - time) * 340/2/10000 );
- break;
- }
- }
- digitalWrite(trig_pin, LOW);
- delay(100);
- }
复制代码 库中pulsein函数应该很好用,但是看了下源码,貌似不对。
|
|