Trig핀으로 신호를 보내고 Echo핀으로 측정값을 받습니다.
측정된 값을 왕복이니깐 2로 나누고, 소리는 초당 343m를 이동하므로, 1cm를 이동하는데 29.155ms가 소요되므로 29.1을
나누어 줍니다.
/*HC-SR04 Ping distance sensor]VCC to arduino 5v GND to arduino GNDEcho to Arduino pin 13 Trig to Arduino pin 12Red POS to Arduino pin 11Green POS to Arduino pin 10560 ohm resistor to both LED NEG and GRD power railMore info at: http://goo.gl/kJ8GlOriginal code improvements to the Ping sketch sourced from Trollmaker.comSome code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar*/#define trigPin 13#define echoPin 12#define led 11#define led2 10void setup() {Serial.begin (9600);pinMode(trigPin, OUTPUT);pinMode(echoPin, INPUT);pinMode(led, OUTPUT);pinMode(led2, OUTPUT);}void loop() {long duration, distance;digitalWrite(trigPin, LOW); // Added this linedelayMicroseconds(2); // Added this linedigitalWrite(trigPin, HIGH);// delayMicroseconds(1000); - Removed this linedelayMicroseconds(10); // Added this linedigitalWrite(trigPin, LOW);duration = pulseIn(echoPin, HIGH);distance = (duration/2) / 29.1; // 소리는 초당 343m를 이동하므로, 1cm를 이동하는데 29.155ms가 소요됨if (distance < 4) { // This is where the LED On/Off happensdigitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn offdigitalWrite(led2,LOW);}else {digitalWrite(led,LOW);digitalWrite(led2,HIGH);}if (distance >= 200 || distance <= 0){Serial.println("Out of range");}else {Serial.print(distance);Serial.println(" cm");}delay(500);}
댓글 없음:
댓글 쓰기