下面範例是計算出距離後,如果距離大於100,就顯示其中一顆LED,沒有就另一顆亮
int ECHO_Pin=4; // ultrasonic ECHO
int TRIG_Pin=5; // ultrasonic TRIG
int Near_LED = 9;
int Far_LED = 10;
void setup()
{
Serial.begin(9600);
pinMode(ECHO_Pin, INPUT);
pinMode(TRIG_Pin, OUTPUT);
}
void loop()
{
digitalWrite(TRIG_Pin, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_Pin, HIGH); // Pulse for 10 micro sec to trigger ultrasonic detection
delayMicroseconds(10);
digitalWrite(TRIG_Pin, LOW);
int distance = pulseIn(ECHO_Pin, HIGH); // Read receiver pulse time
distance= distance/58; // Transform pulse time to distance
Serial.println(distance); //Output distance
if(distance > 100)
{
digitalWrite(Far_LED, HIGH);
digitalWrite(Near_LED, LOW);
}else{
digitalWrite(Far_LED, LOW);
digitalWrite(Near_LED, HIGH);
}
delay(50);
}
超音波模組運作原理
http://coopermaa2nd.blogspot.tw/2012/09/hc-sr04.html
http://mcudiy.blogspot.tw/2012/12/usm-ultrasonic-module-hc-sr04.html
datasheet
https://www.google.com.tw/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwjPxZqsgIrOAhUDEpQKHfkICa4QFggnMAI&url=http%3A%2F%2Fwww.micropik.com%2FPDF%2FHCSR04.pdf&usg=AFQjCNGQka2FGj3tvAzU2HEDfgZvvCQpNw&sig2=axF9GWdLv_KJdj3alHP1aA
DataSheet裡的波形圖
新學到的
PulseIn:量測input腳位的高電位或低電位脈波長度
https://www.arduino.cc/en/Reference/PulseIn
沒有留言:
張貼留言