Ultrasonic sensor and LCD for Distance Measurements : Arduino Tutorial




Arduino Library


MedianFilter


Arduino Sketch

#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
#include <MedianFilter.h>

MedianFilter test(31, 0);

LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display


const int trigPin = 9;
const int echoPin = 10;

long duration;
int distance, temp=-1;

void setup() {

    lcd.init();
  
    Serial.begin(9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    
    lcd.backlight();
    lcd.setCursor(0,0);
    lcd.print("Distance:");
}

void loop() {
  // Clears the trigPin
  digitalWrite( trigPin , LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite( trigPin , LOW);
  // Reads the echoPin, returns the sound wave 
  // travel time in microseconds 
  duration = pulseIn( echoPin , HIGH);

  distance = duration * 0.034 / 2;

  test.in( distance ); // software filter
  distance = test.out();

  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);

  if( temp != distance ){
       temp = distance;
  lcd.setCursor(0,1);
  lcd.print("          ");
  lcd.setCursor(0,1);
  lcd.print(distance);
  lcd.print(" CM");
  }
}

ความคิดเห็น