Arduino + SR-HC04

Parts :

– 1 x Arduino nano

– 1 x led

– 1 x buzzer

– 1x R 220 Ω

– 1 x SR-HC04 module

int trig = 12;
int echo = 11;
long lecture_echo;
long cm;
int LED = 6;

void setup()
{
pinMode(trig, OUTPUT);
digitalWrite(trig, LOW);
pinMode(echo, INPUT);
Serial.begin(9600);
pinMode(9, OUTPUT);
}

void loop()
{
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
lecture_echo = pulseIn(echo, HIGH);
cm = lecture_echo / 58;
Serial.print(« Distancem : « );
Serial.println(cm);
delay(1000);

if(cm<125)
{
digitalWrite(LED, HIGH);
beep(200);
}
else
{
digitalWrite(LED,LOW);
}
}

void beep(unsigned char delayms){
analogWrite(9, 20); // Almost any value can be used except 0 and 255
// experiment to get the best tone
delay(delayms); // wait for a delayms ms
analogWrite(9, 0); // 0 turns it off
delay(delayms); // wait for a delayms ms
}