0% found this document useful (0 votes)
14 views4 pages

Arduino Ultrasonik 013204

This document describes an Arduino ultrasonic distance sensor sketch that uses trig and echo pins to measure distance in centimeters and lights an LED if the distance is less than a threshold of 20 cm. It defines constants for the trig, echo, and LED pins and distance threshold, initializes the serial port and pins, generates a 10-microsecond trig pulse, measures the echo pulse duration to calculate distance, and lights the LED or not depending on if the distance is below the threshold, printing the results to the serial monitor.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views4 pages

Arduino Ultrasonik 013204

This document describes an Arduino ultrasonic distance sensor sketch that uses trig and echo pins to measure distance in centimeters and lights an LED if the distance is less than a threshold of 20 cm. It defines constants for the trig, echo, and LED pins and distance threshold, initializes the serial port and pins, generates a 10-microsecond trig pulse, measures the echo pulse duration to calculate distance, and lights the LED or not depending on if the distance is below the threshold, printing the results to the serial monitor.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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