Gnd===========Gnd
Pictureconnectionasbelow:
Examplecode:
*********Codebegin*********
#definetrigPin13
#defineechoPin12
#defineled11
#defineled210
voidsetup(){Serial.begin
(9600);pinMode(trigPin,
OUTPUT);pinMode(echoPin,
INPUT);pinMode(led,
OUTPUT);
pinMode(led2,OUTPUT);
}
voidloop(){
longduration,distance;
digitalWrite(trigPin,LOW);//Addedthisline
delayMicroseconds(2);//Addedthisline
digitalWrite(trigPin,HIGH);
//delayMicroseconds(1000);‐Removedthisline
delayMicroseconds(10);//Addedthisline
digitalWrite(trigPin,LOW);
duration=pulseIn(echoPin,HIGH);
distance=(duration/2)/29.1;
if(distance<4){//ThisiswheretheLEDOn/Offhappens
digitalWrite(led,HIGH);//WhentheRedconditionismet,theGreen