Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
NicoB1
Published © GPL3+

Display Ultrasonic Sensor and Servo

An ultrasonic sensor rotating on a servo and displaying values.

IntermediateShowcase (no instructions)10,450
Display Ultrasonic Sensor and Servo

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Breadboard (generic)
Breadboard (generic)
×2
Rotary potentiometer (generic)
Rotary potentiometer (generic)
×1
Female/Female Jumper Wires
Female/Female Jumper Wires
×1
Arduino LCD Screen
Arduino LCD Screen
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

arduino_ultrasonic_lcd_bb_sU88VPdaWo.jpg

Code

Untitled file

Arduino
#include<LiquidCrystal.h>
#include<Servo.h>

int trigPin=2;
int echoPin=3;
int distance;

 const int rs = 12, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

long duration;
Servo servo;

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
  servo.attach(9);
  lcd.begin(16, 2);
}

void loop()
{
  for(int i=15;i<=165;i++)
  {
    servo.write(i);
    delay(200);
    printOut();
  }
  for(int i=165;i>15;i--)
  {
    servo.write(i);
    delay(200);  
   printOut(); 
  }
}

int calculateDistance()
{
  digitalWrite(trigPin,LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin,HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin,LOW);
  
  duration=pulseIn(echoPin,HIGH);
  distance=duration*0.034/2;
  return distance;
}  

void printOut()
 {
  lcd.clear();
    lcd.setCursor(0, 0); 
    lcd.print("Servo Pos: ");
    lcd.print(servo.read());
    lcd.setCursor(0, 1); 
    lcd.print("Distance: ");
    lcd.print(calculateDistance());
 }

Credits

NicoB1

NicoB1

1 project • 1 follower

Comments