2016年2月23日 星期二

using wiringPi to implement ultrasonic function



有關於wiringPi 的安裝和執行  請參考這篇   wiringPi

然後我發覺我超音波做不出來的原因是因為我理解錯誤....

參考timing diagram



重點是要去數  第三列的pulse為高電位的時間......


int ultrasonic_read(_pin){
        unsigned int  start_time,end_time,duraction;
        pinMode (_pin, OUTPUT) ;
        digitalWrite (_pin, LOW) ;
        delayMicroseconds(3);
        digitalWrite (_pin, HIGH) ;
        delayMicroseconds(11);
        digitalWrite (_pin, LOW);
        pinMode (_pin, INPUT) ;
        while(digitalRead(_pin)==LOW)
            delayMicroseconds(1);
        start_time = micros();
        while(digitalRead(_pin)==HIGH)
            delayMicroseconds(1);
        end_time = micros();
        if(start_time > end_time)
           duraction = (unsigned int)4294967295 - end_time + start_time;
        else
           duraction = end_time - start_time;
        return (0.17 * duraction);
}

把跑出來的資料plot 出來....結果就像下圖一樣




wiringPi in raspberry



安裝

sudo apt-get install git-core
sudo apt-get update
sudo apt-get upgrade
git clone git://git.drogon.net/wiringPi
cd wiringPi
git pull origin
cd wiringPi
./build

pin  圖:
   wiringPi  定義的腳位和RPI的腳位不一樣...舉個例子....

GPIO14 (Txd) ->  wiringPi  15

所以這裡要特別注意





  • Pins 171819 and 20: (BCM_GPIO 28, 29, 30 and 31) These are additional GPIO pins on the Rev. 2 board.

sample code:

#include <wiringPi.h>
int main (void)
{
  int pin_num = 0;
  wiringPiSetup () ;
  pinMode (pin_num, OUTPUT) ;
  for (;;)
  {
    digitalWrite (pin_num, HIGH) ; delay (500) ;
    digitalWrite (pin_num,  LOW) ; delay (500) ;
  }
  return 0 ;
}
 then to compile and run, you would enter:
gcc -Wall -o blink blink.c -lwiringPi
sudo ./blink

如果線有接對....應該會亮了....

Reference : http://wiringpi.com/