int TrigPin = 7 ; //define Trig pin which send a high square wave for 10 //10 micro seconds int EchoPin = 8; //Define Echo pin which receives the wave and give the time // The wave took to reflect from a surface int Buzzer = 9; //Define Buzzer pin int i; //Define index i long WaveTime ; // define variables to save the time and distance int Distance; void setup() { pinMode(TrigPin, OUTPUT); // set TrigPin as output pin pinMode(EchoPin, INPUT); // set EchoPin as input pin pinMode(Buzzer, OUTPUT); // set Buzzer as output pin Serial.begin(9600); // Start serial } void loop() { digitalWrite(Buzzer,LOW); // inital value for buzzer digitalWrite(TrigPin, LOW); // Clear TrigPin delayMicroseconds(2); //Delay in micro seconds digitalWrite(TrigPin,HIGH); // Genarate square wave write high on trig pin //delay then write law delayMicroseconds(10); digitalWrite(TrigPin,LOW); WaveTime = pulseIn(EchoPin, HIGH); //measure of the pulse (in microseconds) // when EchoPin become HIGH Distance= (WaveTime*0.0343)/2; // calculate the distance Serial.print("Distance: "); //Print distance on serial monitor Serial.println(Distance); if (Distance<30){ // Compare distance of the obstacle //if it less than 30 cm //the buzzer will ring in higher frequency for( i=0; i<5; i++){ //For loop to generate square wave // to operate the buzzer digitalWrite(Buzzer,LOW); delay(50); //Delay in milliseconds digitalWrite(Buzzer,HIGH); delay(50); } } if (Distance>30 && 50>Distance){ // Compare distance of the obstacle //if it more than 30 cm and less than 50cm //the buzzer will ring in higher frequency for( i=0; i<5; i++){ digitalWrite(Buzzer,LOW); delay(100); digitalWrite(Buzzer,HIGH); delay(100); } } }