Day2 04_sonic
2024. 1. 18. 19:53ㆍarduino
- 초음파 센서를 이용한 거리 출력
const int trigPin = 14; //A0
const int echoPin = 15; //A1
const int ledPin = 13;
void setup() {
// put your setup code here, to run once:
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
long distance = getDistance();
Serial.println(String(distance) + " cm");
if (distance < 15) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
// delay(100);
}
long getDistance() {
// put your main code here, to run repeatedly:
// trig - 10us
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
long distance = (duration / 2) / 29.1;
return distance;
}
'arduino' 카테고리의 다른 글
Day2 06_Debounce (0) | 2024.01.18 |
---|---|
Day2 05_IR (0) | 2024.01.18 |
Day2 03_sensor_led (0) | 2024.01.18 |
Day2 02_button (0) | 2024.01.18 |
Day2 01_python_rgb (0) | 2024.01.18 |