mikroavr

ultrasonic

Mar 7th, 2019
190
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Wire.h>
  2. #include <LiquidCrystal_I2C.h>
  3. LiquidCrystal_I2C lcd(16, 2);
  4.  
  5. const byte Echo = 2;//kaki ultrasonik
  6. const byte Trig = 3;//kaki ultrasonik
  7. long duration;
  8. int distance;
  9. int jarak;
  10. String line1, line2;
  11. unsigned long old_time;
  12. const unsigned long tinggi_tabung = 15000;
  13. float baca_tinggi_tabung;
  14.  
  15. void setup() {
  16.    Serial.begin(9600);
  17.    lcd.autoAddress();
  18.    lcd.begin();
  19.    pinMode(Echo, INPUT);
  20.    pinMode(Trig, OUTPUT);
  21. }
  22.  
  23. void loop() {
  24.    if( millis() - old_time >= 250 ){
  25.     get_data();
  26.     old_time = millis();
  27.    }
  28. }
  29. void baca_sensor(int trigPin, int echoPin){
  30.   digitalWrite(trigPin, LOW);
  31.   delayMicroseconds(2);
  32.   digitalWrite(trigPin, HIGH);
  33.   delayMicroseconds(10);
  34.   digitalWrite(trigPin,LOW);
  35.   duration = pulseIn(echoPin, HIGH);
  36.   distance = duration * 0.034/2;
  37. }
  38. void get_data(){
  39.   baca_sensor(Trig,Echo);
  40.   jarak = distance;
  41.   baca_tinggi_tabung = tinggi_tabung - (float)jarak/100;
  42.   line1 = String("Jarak: ") + jarak + " cm";
  43.   line2 = String("Tinggi: ") + String(baca_tinggi_tabung,2) + " m";
  44.   lcd.clear();
  45.   lcd.setCursor(0,0);
  46.   lcd.print(line1);
  47.   lcd.setCursor(0,1);
  48.   lcd.print(line2);
  49. }
RAW Paste Data