Hi thank you everyone who can help i cant seem to figure out what is wrong with my if statement. I have attached the code
I hope you guys can help it is for school project ![]()
if any more information needed please comment ill try and respond as fast as I can
thank you SO MUCH!
// Ultrasonic HC-SR04 unit interface
// Uses serial port at 115200 baud for communication
// use trig pin for output, echo pin for input
// pulse out (10us) on trig initiates a cycle
// pulse width returned on echo is proportional to distance
// specs say 38ms = no return (beyond limit), but 90ms and more have been seen
// set utimeout when calling usonic (routine will take longer for longer returns)
// higher timeout measures further, but can take longer if no echo
// if return >= utimeout, no valid pulse received
// if return < ~100 unit is faulty/disconnected (routine is timing out waiting for start)
// if return == 0 then unit is still sending return from last ping (or is faulty)
// maximum nominal range is 5m => utimeout = 29000 us
// call usonicsetup() during setup
// call usonic(timeout) to get return time in microseconds
// divide result of usonic by 58 to get range in cm
#define TRIG 3
#define ECHO 2
#define USMAX 3000
int led2=A0;
int led4=A1;
int led6=A2;
int led8=A3;
int led10=A4;
void setup()
{
 Serial.begin(115200);
Â
usonicsetup();
Â
Â
Â
Â
 pinMode(led2, OUTPUT);
 pinMode(led4, OUTPUT);
 pinMode(led6, OUTPUT);
 pinMode(led8, OUTPUT);
 pinMode(led10, OUTPUT);
Â
 digitalWrite(led2, LOW);
 digitalWrite(led4, LOW);
 digitalWrite(led6, LOW);
 digitalWrite(led8, LOW);
 digitalWrite(led10, LOW);
Â
 delay(1000);
}
void loop()
{
int distance;
distance=usonic(11600)/58; //distance in cm, time out at 11600us or 2m maximum range
Serial.println(distance); //distance in cm
delay(10000); // how long between differnt sonar scans 1000 = 1 sec
Â
}
void usonicsetup(void)
{
pinMode(ECHO, INPUT);
pinMode(TRIG, OUTPUT);
digitalWrite(TRIG, LOW);
}
long usonic(long utimeout){ //utimeout is maximum time to wait for return in us
long b;
if(digitalRead(ECHO)==HIGH){return 0;} //if echo line is still low from last result,
return 0;
digitalWrite(TRIG, HIGH); //send trigger pulse
delay(1);
digitalWrite(TRIG, LOW);
long utimer=micros();
while((digitalRead(ECHO)==LOW)&&((micros()-utimer)<1000)){} //wait for pin state to changereturn starts after 460us typically or timeout (eg if not connected)
utimer=micros();
while((digitalRead(ECHO)==HIGH)&&((micros()-utimer)<utimeout)){} //wait for pin state to change
b=micros()-utimer;
if(b==0){b=utimeout;}
return b;
Â
}
if (Â (distance > 0) && (distance <= 20)Â ) // distance in cm
{
 digitalWrite(led2, HIGH);
 digitalWrite(led4, HIGH);
 digitalWrite(led6, HIGH);
 digitalWrite(led8, HIGH);
 digitalWrite(led10, HIGH);
// note to self add else next to }
// then repeat if statment
bodacious_migelo_albar1.ino (2.55 KB)