#define trigPin 4 #define echoPin 5
// Define variables:
long duration;
int distance;
void setup() {
// Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Begin Serial communication at a baudrate of 9600:
Serial.begin(9600);
}
void loop() {
// Clear the trigPin by setting it LOW:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
// Trigger the sensor by setting the trigPin high for 10 microseconds:
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
duration = pulseIn(echoPin, HIGH);
// Calculate the distance:
distance = duration*0.034/2;
The output give 15 cm or sometimes 1 cm no matter where I point the sensor (wall, ceiling, the led, etc). The red LED on the sensor keeps on blinking multiple times a second. I have 2 sensors and both of them show the same behavior. What am I doing wrong?
Your code looks good. Assuming you have all your pins connected properly.
Not knowing any details on your setup I would start by checking the power supply to the sensor board. That board must create a higher signal to drive the waterproof sensor so at every measurement there will be a burst of current required.
I would also check the connections. The solderless breadboards are notorious for high resistance connections.
JohnRob:
Not knowing any details on your setup I would start by checking the power supply to the sensor board. That board must create a higher signal to drive the waterproof sensor so at every measurement there will be a burst of current required.
I would also check the connections. The solderless breadboards are notorious for high resistance connections.
This is just a test setup. I am using a base for the nano; the nano itself is powered by a usb cable from a port on my pc to the micro-usb port on the nano. There are 4 dupont jumper wires 20 cm long connecting the nano and sensor. The specs for the sensor say it requires max 30 mA. A usb 2 port can deliver up to 500 mA; nano+sensor is much less than this. I have also tried a usb 3 port on my the pc and a usb hub with a power adapter but the behavior is just the same. I have changed the jumper wires but it has made no difference. I got another sensor today but also behaves the same. I am stumped.
I have removed the nano base and connected the wires directly to the nano.
I replaced the nano with an uno r3 with its own set of jumper wires.
I replaced the sensor with HC-SR04 and it works fine. I have tried 3 different sensors. Maybe the entire lot of sensor is bad. Or there is some other trick to get the version 3 sensors to work.
One thing which seems odd is that the led on my sensor starts blinking as soon as I apply power; the blink frequency does not change no matter what is the duration of the sleep command in the loop. Is this the expected behavior?