Devices & Components
Arduino Uno Rev3
SG90 Micro-servo motor
Jumper wires (generic)
Ultrasonic Sensor - HC-SR04 (Generic)
Hardware & Tools
Hot glue gun (generic)
Software & Tools
Arduino IDE
Project description
Code
Code
arduino
1#include <Servo.h> 2 3Servo servoMain; // Define our Servo 4 5int trigpin = 10; 6 7int echopin = 11; 8 9int distance; 10 11float duration; 12 13float cm; 14 15void setup() 16 17{ 18 19servoMain.attach(9); // servo on digital pin 10 20 21pinMode(trigpin, OUTPUT); 22 23pinMode(echopin, INPUT); 24 25} 26 27void loop() 28 29{ 30 31digitalWrite(trigpin, LOW); 32 33delay(2); 34 35digitalWrite(trigpin, HIGH); 36 37delayMicroseconds(10); 38 39digitalWrite(trigpin, LOW); 40 41duration = pulseIn(echopin, HIGH); 42 43cm = (duration/58.82); 44 45distance = cm; 46 47if(distance<30) 48 49{ 50 51servoMain.write(180); // Turn Servo back to center position (90 degrees) 52 53delay(3000); 54 55} 56 57else{ 58 59servoMain.write(0); 60 61delay(50); 62 63} 64 65}
Downloadable files
Circuit Diagram
Circuit Diagram
Comments
Only logged in users can leave comments