วิธีต่อ Arduino กับ Ping Ultrasonic Sensor (HC-SR04)
รูป Ping Ultrasonic Sensor (HC-SR04)
ตัวอย่างโค้ด
/* HC-SR04 Ping distance sensor: VCC to arduino 5v GND to arduino GND Echo to Arduino pin 7 Trig to Arduino pin 8 This sketch originates from Virtualmix: http://goo.gl/kJ8Gl Has been modified by Winkle ink here: http://winkleink.blogspot.com.au/2012/05/arduino-hc-sr04-ultrasonic-distance.html And modified further by ScottC here: http://arduinobasics.blogspot.com/ on 10 Nov 2012. */ #define echoPin 7 // Echo Pin #define trigPin 8 // Trigger Pin #define LEDPin 13 // Onboard LED long duration, inches, cm; int maximumRange = 100; // Maximum range needed int minimumRange = 10; // Minimum range needed void setup() { Serial.begin (9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(LEDPin, OUTPUT); // Use LED indicator (if required) } void loop() { /* The following trigPin/echoPin cycle is used to determine the distance of the nearest object by bouncing soundwaves off of it. */ digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); if (cm >= maximumRange || cm <= minimumRange){ /* Send a negative number to computer and Turn LED ON to indicate "out of range" */ digitalWrite(LEDPin, HIGH); } else { /* Send the distance to the computer using Serial protocol, and turn LED OFF to indicate successful reading. */ digitalWrite(LEDPin, LOW); } //Delay 50ms before next reading. delay(1000); } long microsecondsToInches(long microseconds) { // According to Parallax's datasheet for the PING))), there are // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // second). This gives the distance travelled by the ping, outbound // and return, so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2; }ความรู้จากบทความนี้สามารถนำไปประยุกต์ใช้
- สร้างหุ่นยนต์ด้วย Arduino ตอนที่ 1 ฝึกให้หุ่นยนต์หลบหลีกสิ่งกีดขวาง
ที่มา
ไม่มีความคิดเห็น:
แสดงความคิดเห็น