El sonar HC-SR04 és un element que permet controlar la proximitat d’objectes. El seu ús més directe és per a controlar moviments de robots, tot i que també pot tenir altres aplicacions en enginys voladors, com ara quadcopters o avions, controlats per Arduino.
Pràctiques:
Exemple 1.
Aquí hi ha un error, a veure…
#define trigPin 3 #define echoPin 2 void setup() { // initialize serial communication: Serial.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { // establish variables for duration of the ping, // and the distance result in inches and centimeters: long duration, inches, cm; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); // convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); } 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; } |
Exemple 2
- Instal·lar llibreria NewPing.
- Mostrar dades del sonar pel monitor serial.
- Mostrar les dades pel serial del Bluetooth en una App del mòbil.
- Encendre un LED vermell quant la distancia sigui inferior a 5 cm i un de verd mentre sigui més gran de 5cm.
- Si anem allunyant un objecte fer més llum a un LED.
- Si anem apropant un objecte fer més llum a un LED.
- Amb 3 leds representar el % de la distancia assignada.
// ————————————————————————— // Example NewPing library sketch that does a ping about 20 times per second. // ————————————————————————— #include <Servo.h> #include <NewPing.h>#define TRIGGER_PIN 3 // Arduino pin tied to trigger pin on the ultrasonic sensor. #define ECHO_PIN 2 // Arduino pin tied to echo pin on the ultrasonic sensor. #define MAX_DISTANCE 20 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. #define SERVO_PIN 8 NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. void setup() { void loop() { //int cm = sonar.ping_cm(MAX_DISTANCE); // Send ping, get distance in cm and print result (0 = outside set distance range) p = map(cm, 0, MAX_DISTANCE, 0, 100); // int cm = sonar.convert_cm(sonar.ping_median(5)); // Serial.print(cm); |