top of page

Arduino Nano Code

//Austin Beayon
//Code for Long distance Rangfinder using Arduino Nano using 16X2 LCD Display and HC-SR04 Ultrasonic Sensor
#include "LiquidCrystal.h"
#define trigPin 10
#define echoPin 9

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); 

void setup()
{
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    
    lcd.begin(16, 2);
    lcd.setCursor(0,0);
    lcd.print("Distance");
    lcd.setCursor(0,1);
    lcd.print("Measuring");
}
 
void loop()
{
   
    long duration, distance;
    
    digitalWrite(trigPin, LOW);  
    delayMicroseconds(2); 
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(100); 
    digitalWrite(trigPin, LOW);
    
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    

    if (distance >= 1000 || distance <= 0) { 
    Serial.println("Out of range");
    }
    else {
    Serial.print(distance);
    Serial.println(" cm    ");
    }
    delay(500);
            
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Distance");
    lcd.setCursor(0, 1);
    lcd.print(distance);
    lcd.print(" cm");
     
}

bottom of page