I have an issue using an ultrasonic sensor. The problem is that when I connect the ultrasonic sensor to my Arduino Nano, it always gives some random values, usually 130 cm, I don't know why.
I bought a second ultrasonic sensor and the problem reoccured. One I bought last year, and the other one I bought yesterday.
I tried several programs like the traditional one:
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.println(distance);
}
This didn't work, so I searched for useful libraries such as NewPing.h:
#include <NewPing.h>
const int trigPin = 9 ;
const int echoPin = 10;
const int maxDistance = 2000;
unsigned int distance;
NewPing sonar(trigPin, echoPin, maxDistance);
void setup() {
Serial.begin(9600);
}
void loop() {
delay(1000) ;
distance = sonar.ping_cm();
Serial.print("Distance : ");
Serial.print(distance);
Serial.println(" cm !");
}
This also didn't work. This is a simple screenshot of what happens in the monitor: (the 0 cm ! value is caused because I turned off the ultrasonic, and the object was actually 4 cm away):
Any help would be appreciated.
