Advertisement
Muzaffar79

SIMULASI JARAK PADA MOBIL

Jul 12th, 2018
416
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1. const int TRIG_PIN = 9;
  2. const int ECHO_PIN = 10;
  3. const int BUZZER = 11;
  4. int LED = 12;
  5.  
  6. long duration;
  7. int distance;
  8. int safetyDistance;
  9.  
  10. void setup() {
  11. Serial.begin(9600);
  12. pinMode(TRIG_PIN,OUTPUT);
  13. pinMode(ECHO_PIN,INPUT);
  14. pinMode (BUZZER , OUTPUT);
  15. }
  16.  
  17. void loop() {
  18. // Clears the trigPin
  19. digitalWrite(TRIG_PIN, LOW);
  20. delayMicroseconds(2);
  21.  
  22. // Sets the trigPin on HIGH state for 10 micro seconds
  23. digitalWrite(TRIG_PIN, HIGH);
  24. delayMicroseconds(10);
  25. digitalWrite(TRIG_PIN, LOW);
  26.  
  27. // Reads the echoPin, returns the sound wave travel time in microseconds
  28. duration = pulseIn(ECHO_PIN, HIGH);
  29.  
  30. // Calculating the distance
  31. distance= duration*0.034/2;
  32.  
  33. safetyDistance = distance;
  34. if (safetyDistance >= 5 && safetyDistance <= 10 ){
  35.     for(int fadeValue = 10 ; fadeValue <= 200; fadeValue +=5)
  36.     analogWrite(BUZZER, fadeValue);
  37. }
  38. else if (safetyDistance >= 10 && safetyDistance <= 18 ){
  39.     for(int fadeValue = 200 ; fadeValue >= 50; fadeValue -=5)
  40.     analogWrite(BUZZER, fadeValue);
  41. }
  42. else if (safetyDistance >= 18 && safetyDistance <= 20 ){
  43.     for(int fadeValue = 200 ; fadeValue >= 0; fadeValue -=5)
  44.     analogWrite(BUZZER, fadeValue);
  45. }
  46.  
  47. // Prints the distance on the Serial Monitor
  48. Serial.print("Distance: ");
  49. Serial.println(distance);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement