Devices & Components
Arduino Uno Rev3
SG90 Micro-servo motor
Ultrasonic Sensor - HC-SR04 (Generic)
Jumper wires (generic)
Software & Tools
Arduino IDE
Project description
Code
Project's source code
c_cpp
1#include <Servo.h> 2 3Servo scanner; 4 5const int out = 12; 6const int in = 13; 7int pos = 0; 8long dur; 9long dis; 10long tocm; 11bool returningToZero; 12 13void setup() { 14 Serial.begin(9600); 15 pinMode(in, INPUT); 16 pinMode(out, OUTPUT); 17 scanner.attach(9); 18 scanner.write(0); 19} 20 21bool objectDetected(long tocm) 22{ 23 if (tocm < 20) 24 { 25 return true; 26 } else { 27 return false; 28 } 29} 30 31void loop() 32{ 33 digitalWrite(out, LOW); 34 delayMicroseconds(2); 35 digitalWrite(out, HIGH); 36 delayMicroseconds(10); 37 digitalWrite(out, LOW); 38 dur = pulseIn(in, HIGH); 39 tocm = microsecondsToCentimeters(dur); 40 if (objectDetected(tocm)) 41 { 42 Serial.print("Object detected. Object's distance: "); 43 Serial.print(tocm); 44 Serial.print(". Servo's angle: "); 45 Serial.println(pos); 46 } else { 47 if (pos < 180 && returningToZero == false) 48 { 49 scanner.write(pos); 50 pos += 10; 51 Serial.print("Searching for object. Servo's angle: "); 52 Serial.println(pos); 53 if (pos == 180) 54 returningToZero = true; 55 } else if (returningToZero == true) { 56 pos -= 10; 57 Serial.print("Searching for object. Servo's angle: "); 58 Serial.println(pos); 59 scanner.write(pos); 60 if (pos == 0) 61 returningToZero = false; 62 } 63 } 64 delay(200); 65} 66 67long microsecondsToCentimeters(long microseconds) 68{ 69 return microseconds / 29.155 / 2; 70}
Downloadable files
Connections Diagram
Ultrasonic sensor: GND to ground; Echo to pin 13; Trgr to pin 12; Vcc to +5V; Servo: Yellow wire to pin 9; Red wire to +5V; Brown wire to ground;
Connections Diagram

Connections Diagram
Ultrasonic sensor: GND to ground; Echo to pin 13; Trgr to pin 12; Vcc to +5V; Servo: Yellow wire to pin 9; Red wire to +5V; Brown wire to ground;
Connections Diagram

Comments
Only logged in users can leave comments