Arduino deneyi 11
Ultrasonic Distance Meter
Intermediate · 55 min · Time of flight
Measure distance with an HC-SR04 and alert when an object comes close.
Malzemeler
- Arduino Uno
- HC-SR04 ultrasonic sensor
- LED
- 220 Ω resistor
- Breadboard and jumper wires
Bağlantı
- Connect HC-SR04 VCC to 5V, GND to GND, Trig to pin 7 and Echo to pin 6.
- Connect pin 13 through 220 Ω to the LED anode and its cathode to GND.
Kod
const int trigPin = 7, echoPin = 6, ledPin = 13;
void setup() {
pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW); delayMicroseconds(2);
digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 30000);
float distance = duration * 0.0343 / 2.0;
Serial.println(distance);
digitalWrite(ledPin, duration > 0 && distance < 20 ? HIGH : LOW);
delay(100);
}
Ne olmalı?
Distance appears in centimetres and the LED turns on below 20 cm.
Meydan okuma
Make the LED blink faster as an object gets closer.
Güvenlik ve sorun giderme
- Bağlantıyı değiştirmeden önce gücü kes.
- Her LED ile direnç kullan.
- Kart ve port seçimini Arduino IDE'de kontrol et.
- Her kablonun koddaki pin numarasıyla eşleştiğini doğrula.
Not: Ders metinleri İngilizcedir. Orijinal Türkçe çalışma kâğıdı PDF olarak indirilebilir.
