Arduino Ultrasonik 013204

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

// constants won't change

const int TRIG_PIN = 9; // pin Trig terhubung dengan Pin 9 Arduino


const int ECHO_PIN = 10; // pin Echo terhubung dengan Pin 10 Arduino
const int LED_PIN = 3; // pin LED terhubung dengan Pin 3 Arduino
const int DISTANCE_THRESHOLD = 20; // minimal jarak terbaca

// variables will change:


float duration_us, distance_cm;

void setup() {
Serial.begin (9600); // Seriap port
pinMode(TRIG_PIN, OUTPUT); // Trig pin sebagai output
pinMode(ECHO_PIN, INPUT); // Echo pin sebagai input
pinMode(LED_PIN, OUTPUT); // pin led sebagai out
}

void loop() {
// generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);
// calculate the distance
distance_cm = 0.017 * duration_us;

if(distance_cm < DISTANCE_THRESHOLD)


digitalWrite(LED_PIN, HIGH); // turn on LED
else
digitalWrite(LED_PIN, LOW); // turn off LED
// print the value to Serial Monitor
Serial.print("distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
delay(500);
}
Contoh
VID_20231003_114643.mp4

You might also like