This code is an example of how to use an Arduino Ultrasonic Sensor Module to create a Smart Obstacle Detection System. The code uses the NewPing library to communicate with the sensor, and it calculates the distance to an obstacle using the time of flight of the ultrasonic sound waves. The distance is then printed on the serial monitor in centimeters. The code also checks if the distance is less than or equal to 30cm and if true it will trigger an action or event. This can be useful for obstacle avoidance in robots or other automation projects.
#include <NewPing.h> #define TRIGGER_PIN 8 // Arduino pin tied to trigger pin on the ultrasonic sensor. #define ECHO_PIN 7 // Arduino pin tied to echo pin on the ultrasonic sensor. #define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. void setup() { Serial.begin(9600); // setup serial communication at 9600 baud } void loop() { delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings. unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS). Serial.print("Ping: "); Serial.print(uS / US_ROUNDTRIP_CM); // convert to cm Serial.println("cm"); if (uS / US_ROUNDTRIP_CM <= 30) { // if obstacle is detected within 30 cm Serial.println("Obstacle detected!"); // Trigger an action or event here } }
To use this code, the following parts are required:
- Arduino board (any model)
- Ultrasonic Sensor Module compatible with Arduino
- Jumper wires to connect the sensor to the Arduino
- USB cable to connect the Arduino to a computer for programming and power supply
- A computer with the Arduino IDE installed
Note: The NewPing library is also required for this code, you can install it through the Arduino IDE library manager.
The pin configuration of the code for the Smart Obstacle Detection System using Arduino Ultrasonic Sensor Module is as follows:
- TRIGGER_PIN is connected to the trigger pin of the ultrasonic sensor and it is defined as 8 in the code.
- ECHO_PIN is connected to the echo pin of the ultrasonic sensor and it is defined as 7 in the code.
- MAX_DISTANCE is the maximum distance for which the sensor is configured to detect obstacles and it is defined as 200cm in the code.
It is important to note that the code uses the constant variables for the trigger and echo pin, and the maximum distance, you should check the pin connections of your sensor and adjust accordingly. Also, you can adjust the detection distance and the delay between pings to suit your specific application.