Devices & Components
Arduino Uno Rev3
LED (generic)
SG90 Micro-servo motor
Ultrasonic Sensor - HC-SR04 (Generic)
Jumper wires (generic)
Buzzer
Hardware & Tools
Hot glue gun (generic)
Tape, Double Sided
Software & Tools
Arduino IDE
Project description
Code
Proximity Detector
arduino
1// Code by theriveroars 2// On 25-8-2020 3 4 5#include <Servo.h> 6#include <NewPing.h> 7 8Servo myservo; // create servo object to control a servo 9 10 11const int trigPin = 9; // Trigger Pin of Ultrasonic Sensor 12const int echoPin = 10; // Echo Pin of Ultrasonic Sensor 13const int red = 11; // led to pin 11 14const int buzz = 12; // buzzer to pin 12 15const int serv0 = 8; // servo to pin 8 16 17NewPing sonar (trigPin, echoPin, 300); //300 is max distance 18 19int pos = 0; // variable to store the servo position 20 21void setup() { 22 myservo.attach(serv0); // attaches the servo on pin 9 to the servo object 23 Serial.begin(9600); // Starting Serial Terminal 24 pinMode(red, OUTPUT); // setting led pin as output 25 pinMode(buzz, OUTPUT); //setting buzzer pin as output 26} 27 28void loop() { 29 long duration, inches, cm; 30 for (pos = pos; pos <= 180; pos += 5) { // goes from 0 degrees to 180 degrees // in steps of 5 degree 31 myservo.write(pos); // tell servo to go to position in variable 'pos' //pos varies from 0 to 180 in steps of 5 32 delay(10); 33 int cm = sonar.ping_cm(); // gets the distance in cm from the ultrasonic sensor 34 Serial.print(cm); 35 Serial.print("cm"); //prints the distance 36 Serial.println(); 37 38 delay(15); 39 40 if (cm < 20) 41 { 42 analogWrite(red, 125); // if distance to object is less than 150 light up the red led to half its brightness 43 if (cm < 10) { // if distance is less than 100 44 digitalWrite(red, HIGH); //light up red led to full brightness 45 digitalWrite(buzz, HIGH); //switch on the buzzer 46 } 47 else digitalWrite(buzz, LOW); 48 49 } 50 else 51 { digitalWrite(buzz, LOW); //otherwise switch of the buzzer and led 52 digitalWrite(red, LOW); 53 } 54 } 55 56 for (pos = 180; pos >= 0; pos -= 5) { // same thing is repeated for the turn from 180 to 0 57 myservo.write(pos); 58 delay(10); 59 int cm = sonar.ping_cm(); 60 61 Serial.print(cm); 62 Serial.print("cm"); 63 Serial.println(); 64 65 delay(15 ); // waits 15ms for the servo to reach the position 66 if (cm < 20) 67 { 68 analogWrite(red, 125); 69 if (cm < 10) 70 { 71 72 digitalWrite(red, HIGH); 73 digitalWrite(buzz, HIGH); 74 } 75 else digitalWrite(buzz, LOW); 76 77 } 78 else 79 { digitalWrite(buzz, LOW); 80 digitalWrite(red, LOW); 81 } 82 } 83 84 85 delay(100); 86} 87
Downloadable files
Circuit diagram
Made with Fritzing
Circuit diagram

Or Here Is The .fzz File
Or Here Is The .fzz File
Or Here Is The .fzz File
Or Here Is The .fzz File
Circuit diagram
Made with Fritzing
Circuit diagram

Comments
Only logged in users can leave comments