Advertisement
ItzLanJiao

Untitled

Apr 5th, 2022
1,251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //超音波酒精噴灑器
  2.  
  3.  
  4. //Ultra sonic sensor上的腳位定義
  5.  
  6. #define trigPin  2
  7.  
  8. #define echoPin 3
  9.  
  10. //LED及WaterPump腳位定義
  11.  
  12. #define led 9
  13.  
  14. #define pump 8
  15.  
  16. //感測距離(單位:inches)
  17. int range = 5;
  18.  
  19.  
  20. void setup() {
  21.  
  22.   Serial.begin(9600);
  23.  
  24.   pinMode(trigPin, OUTPUT);
  25.  
  26.   pinMode(echoPin, INPUT);
  27.  
  28.   pinMode(led, OUTPUT);
  29.  
  30.   pinMode(pump, OUTPUT);
  31.  
  32.   digitalWrite(led, HIGH);
  33.  
  34.   digitalWrite(pump, LOW);
  35.  
  36. }
  37.  
  38. void loop()
  39.  
  40. {
  41.  
  42.   long duration, inches, cm;
  43.  
  44.  
  45.   //觸發時機,當High持續2微秒
  46.  
  47.   digitalWrite(trigPin, LOW);
  48.  
  49.   delayMicroseconds(2);
  50.  
  51.   digitalWrite(trigPin, HIGH);
  52.  
  53.   delayMicroseconds(5);
  54.  
  55.   digitalWrite(trigPin, LOW);
  56.  
  57.   duration = pulseIn(echoPin, HIGH);
  58.  
  59.   //微秒轉吋,吋再轉公分
  60.   inches = microsecondsToInches(duration);
  61.  
  62.   cm = microsecondsToCentimeters(duration);
  63.  
  64.   if(inches < 5) {
  65.  
  66.     digitalWrite(led, LOW);
  67.  
  68.     digitalWrite(pump, HIGH);
  69.  
  70.     delay(100);
  71.   }
  72. else {
  73.  
  74.      digitalWrite(led, HIGH);
  75.  
  76.      digitalWrite(pump, LOW);
  77.  
  78.      delay(100);
  79.   }  
  80.  
  81.    delay(200);
  82.  
  83. }
  84.  
  85. long microsecondsToInches(long microseconds)
  86.  
  87. {
  88.  
  89.   return microseconds / 74 / 2;
  90.  
  91. }
  92.  
  93.  
  94. long microsecondsToCentimeters(long microseconds)
  95.  
  96. {
  97.  
  98.   // 聲速為340m/s or 29cm/ms
  99.  
  100.   // 得出的距離要/2,因為所得之距離為來回的總和。
  101.  
  102.   return microseconds / 29 / 2;
  103.  
  104. }
  105.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement