I need help understanding why when I put this code:
#define echoPin 4 // Echo Pin
#define trigPin 5 // Trigger Pin
#define LEDPin 13 // Onboard LED
int maximumRange=200; //Maximum range needed
int minimumRange=0; //Minimum range needed
long duration,distance; //Duration used to calculate distance
void setup() {
Serial.begin(9600);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
pinMode(LEDPin,OUTPUT);//Use LED indicator (if required)
}
void loop() {
digitalWrite(trigPin,LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration = duration/58.2;
if(distance>=maximumRange||distance<=minimumRange){
Serial.println("-1");
digitalWrite(LEDPin,HIGH);
}
else{
Serial.println(distance);
digitalWrite(LEDPin,LOW);
}
//Delay 50ms before next reading.
delay(50);
}
to test the ultrasonic sensor to show me how far away it is from an obsatcle it gives me -1's all the time when the obstacles isn't that close to it. I am using a Keyestudio Mini Tank Robot and the obstacles avoidence just gives me -1's. Does anyone know how to fix this?