Note
Project ini bertujuan untuk melakukan pemetaan 2D menggunakan Arduino Uno sebagai mikrokontroller dengan sensor HCSR-04 yang akan mendeteksi objek lalu dipetakan ke dalam LCD I2C 128x64.
Simulasi Rangkaian di wokwi.com
#include <Servo.h>
// Defines Trig and Echo pins of the Ultrasonic Sensor
const int trigPin = 10;
const int echoPin = 11;
const int servoPin = 12;
// Variables for the duration and the distance
long duration;
int distance;
Servo myServo; // Creates a servo object for controlling the servo motor
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
myServo.attach(servoPin); // Defines on which pin is the servo motor attached
}
void loop() {
for(int i=15;i<=165;i++){ // rotates the servo motor from 15 to 165 degrees
myServo.write(i);
delay(30);
distance = calculateDistance(); // Calls a function for calculating the distance measured by the Ultrasonic sensor for each degree
Serial.print(i);Serial.print(",");Serial.println(distance);
}
for(int i=165;i>15;i--){ // Repeats the previous lines from 165 to 15 degrees
myServo.write(i);
delay(30);
distance = calculateDistance();
Serial.print(i);Serial.print(",");Serial.println(distance);
}
}
// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // Sets the trigPin on HIGH state for 10 micro seconds
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
distance = duration*0.034/2;
return distance;
}