// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;
const int ledPin = 13;
// defines variables
long duration;
int distance;
int safetyDistance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(buzzer, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
safetyDistance = distance;
if (safetyDistance <= 5){
digitalWrite(buzzer, HIGH);
digitalWrite(ledPin, HIGH);
}
else{
digitalWrite(buzzer, LOW);
digitalWrite(ledPin, LOW);
}
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}
I have created this project in which, there is a buzzer which beeps when any object is detected by the ultrasonic sensor. But it only detects it if the object is very close to it. SO can I change that and make it detect something that is 200 or 300 cm away?
What is the target (object)? An ultrasonic sensor is best at ranging a target that is hard and flat and whose surface is perpendicular to the sensor. Also the target has to be of some minimum size. So something like a book perpendicular to the "beam" would be easily detected. A little fluffy kitty not so much.
What is the supply voltage to the sensor? An HCSR-04 likes a supply voltage of a solid 5V. Less will lessen the range.
Changing the receiver turned circuit from 38Khz to 40Khz will garner more range. Somewhere on the internet is a thing about improving the SR04 with about 30.00 USD of new parts. Requires a SMD workstation.
The SR04 is a +/-12V device. The Vreg on the SR04 sucks at converting 5V to 12V and -12V, changing out the Vreg circuit with about 30USD of SMD parts will improve the performance of the SR04. The article on how to change out the power supply is somewhere on the internet.
Is there any benefit from fitting horns to get some "antenna gain"? Would nake it directional of course which might not be ideal depending on the application.
You currently look for <5 cm. You can change that to <300 cm.
NOTE: pulseIn() will return 0 if no echo is detected so you may want to skip zero values: if (safetyDistance != 0 && safetyDistance <= 300) {