2013年3月31日 星期日

Ultrasonic Sensor!

const unsigned int PING_SENSOR_IO_PIN=7; //輸出
const unsigned int PING_SENSOR_IO_PIN2=8; //接收
const unsigned int BAUD_RATE=9600;
void setup(){
Serial.begin(BAUD_RATE);
}
void loop()
{
pinMode(PING_SENSOR_IO_PIN,OUTPUT); //輸出端
pinMode(PING_SENSOR_IO_PIN2,INPUT); //接受端
digitalWrite(PING_SENSOR_IO_PIN,LOW); //先設定低波
delayMicroseconds(2); //2微渺
digitalWrite(PING_SENSOR_IO_PIN,HIGH); //發射高坡
delayMicroseconds(5); //5毫秒
digitalWrite(PING_SENSOR_IO_PIN,LOW); //低波
const unsigned long duration=pulseIn(PING_SENSOR_IO_PIN2,HIGH);
//pulseln 假如回傳746, 746/29/2= 12cm
//因為超音波1秒343公尺,1/343=0.0029155 聲音前進一公分=29.155微秒
//為何又要/2呢? 因為 傳送+接收 =兩倍時間
if(duration==0)
{
Serial.println("Warning:we did not get a pulse from sensor");
}
else
{
Serial.println(duration); //可顯示 duration目前數值 經過計算 duration/29/2= CM
Serial.print("Distance to nearest object:");
Serial.print(microseconds_to_cm(duration)); //呼叫副程式(參數)
Serial.println("cm");
}
delay(100);
}
unsigned long microseconds_to_cm(const unsigned long microseconds) //副程式(帶入duration)
{
return microseconds / 29 / 2; //duration/29/2=return!!
}


腳位紀錄
HC-SR04
VCC=5V
Trig =output
Echo=intput
Gnd =Gnd

以下為Float 寫法


const unsigned int PING_SENSOR_IO_PIN = 7;
const unsigned int PING_SENSOR_IO_PIN2 = 8;
const unsigned int BAUD_RATE = 9600;
const float MICROSECONDS_PER_CM = 29.155;// 聲音一公分所需時間
const float MOUNTING_GAP = 0.2;
const float SENSOR_OFFSET = MOUNTING_GAP * MICROSECONDS_PER_CM * 2; //麵包版與SENSOR距離
void setup() {
Serial.begin(BAUD_RATE);
}
void loop() {
const unsigned long duration = measure_distance(); //呼叫1
if (duration == 0) //如果沒收到訊號時
Serial.println("Warning: We did not get a pulse from sensor.");
else
output_distance(duration);//收到訊號時 呼叫2 帶參數duration
}
const float microseconds_to_cm(const unsigned long microseconds)//副程式3
{
const float net_distance = max(0, microseconds - SENSOR_OFFSET);
//dutation=1502 -11.6=1490.4
return net_distance / MICROSECONDS_PER_CM / 2; //1490.4/29.155/2=25.559
}
const unsigned long measure_distance()//副程式1
{
pinMode(PING_SENSOR_IO_PIN, OUTPUT); //輸出模式
digitalWrite(PING_SENSOR_IO_PIN, LOW); //低頻
delayMicroseconds(2);
digitalWrite(PING_SENSOR_IO_PIN, HIGH); //高頻
delayMicroseconds(5);
digitalWrite(PING_SENSOR_IO_PIN, LOW); //低頻
pinMode(PING_SENSOR_IO_PIN2, INPUT); //定義接收端
return pulseIn(PING_SENSOR_IO_PIN2, HIGH);//利用pulseln方法 接收高頻
}
void output_distance(const unsigned long duration)//副程式2
{
Serial.print(duration);
Serial.print("Distance to nearest object: ");
Serial.print(microseconds_to_cm(duration)); //呼叫3 帶入 duration
Serial.println(" cm");
}

沒有留言:

張貼留言