Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Wire.h>
- #include <LiquidCrystal_I2C.h>
- LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display
- // Define Trig and Echo pin:
- #define trigPin 3
- #define echoPin 4
- long max_distance = 5000;
- // Define variables:
- float duration;
- float distance;
- void setup() {
- // Define inputs and outputs
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- Serial.begin(9600);
- lcd.init();
- lcd.backlight();
- // Begin Serial communication at a baudrate of 9600:
- }
- void loop() {
- // Clear the trigPin by setting it LOW:
- digitalWrite(trigPin, LOW);
- delayMicroseconds(5);
- // Trigger the sensor by setting the trigPin high for 10 microseconds:
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
- duration = pulseIn(echoPin, HIGH);
- // Calculate the distance:
- distance = duration*0.034/2; // cm
- distance = distance*10; // convert to mm
- // Print the distance on the Serial Monitor (Ctrl+Shift+M):
- Serial.print("Distance = ");
- Serial.print(distance);
- //distance = max_distance - distance;
- Serial.println(" mm");
- String str_jarak = String(distance,0) + "mm";
- lcd.clear();
- lcd.setCursor(0, 0);
- lcd.print("Distance");
- lcd.setCursor(0, 1);
- lcd.print(str_jarak);
- delay(1000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement