Advertisement
mikroavr

ultrasonic_lcd

Sep 1st, 2021
1,821
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Wire.h>
  2. #include <LiquidCrystal_I2C.h>
  3.  
  4. LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display
  5.  
  6.  
  7. // Define Trig and Echo pin:
  8. #define trigPin 3
  9. #define echoPin 4
  10. long max_distance = 5000;
  11.  
  12. // Define variables:
  13. float duration;
  14. float distance;
  15.  
  16. void setup() {
  17.   // Define inputs and outputs
  18.   pinMode(trigPin, OUTPUT);
  19.   pinMode(echoPin, INPUT);
  20.   Serial.begin(9600);
  21.   lcd.init();
  22.   lcd.backlight();
  23.  
  24.  
  25.   // Begin Serial communication at a baudrate of 9600:
  26.  
  27. }
  28.  
  29. void loop() {
  30.   // Clear the trigPin by setting it LOW:
  31.   digitalWrite(trigPin, LOW);
  32.   delayMicroseconds(5);
  33.  // Trigger the sensor by setting the trigPin high for 10 microseconds:
  34.   digitalWrite(trigPin, HIGH);
  35.   delayMicroseconds(10);
  36.   digitalWrite(trigPin, LOW);
  37.  
  38.   // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
  39.   duration = pulseIn(echoPin, HIGH);
  40.  
  41.   // Calculate the distance:
  42.   distance = duration*0.034/2; // cm
  43.   distance = distance*10; // convert to mm
  44.  
  45.   // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  46.   Serial.print("Distance = ");
  47.   Serial.print(distance);
  48.   //distance = max_distance - distance;
  49.   Serial.println(" mm");
  50.   String str_jarak = String(distance,0) + "mm";
  51.  
  52.   lcd.clear();
  53.   lcd.setCursor(0, 0);
  54.   lcd.print("Distance");
  55.   lcd.setCursor(0, 1);
  56.   lcd.print(str_jarak);
  57.   delay(1000);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement