harisz
Published © GPL3+

Ultrasonic sweep for objects with serial communication

Rotating object scanner using ultrasonic sensor and servo motor. Distance and servo's angle sent to serial port.

IntermediateShowcase (no instructions)1,142
Ultrasonic sweep for objects with serial communication

Things used in this project

Hardware components

Jumper wires (generic)
Jumper wires (generic)
×7
SG90 Micro-servo motor
SG90 Micro-servo motor
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Arduino UNO
Arduino UNO
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

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;

Code

Project's source code

C/C++
#include <Servo.h>

Servo scanner;

const int out = 12;
const int in = 13;
int pos = 0;
long dur;
long dis;
long tocm;
bool returningToZero;

void setup() {
  Serial.begin(9600);
  pinMode(in, INPUT);
  pinMode(out, OUTPUT);
  scanner.attach(9);
  scanner.write(0);
}

bool objectDetected(long tocm)
{
  if (tocm < 20)
  {
    return true;
  } else {
    return false;
  }
}

void loop()
{
  digitalWrite(out, LOW);
  delayMicroseconds(2);
  digitalWrite(out, HIGH);
  delayMicroseconds(10);
  digitalWrite(out, LOW);
  dur = pulseIn(in, HIGH);
  tocm = microsecondsToCentimeters(dur);
  if (objectDetected(tocm))
  {
    Serial.print("Object detected. Object's distance: ");
    Serial.print(tocm);
    Serial.print(". Servo's angle: ");
    Serial.println(pos);
  } else {
    if (pos < 180 && returningToZero == false)
    {
      scanner.write(pos);
      pos += 10;
      Serial.print("Searching for object. Servo's angle: ");
      Serial.println(pos);
      if (pos == 180)
        returningToZero = true;
    } else if (returningToZero == true) {
      pos -= 10;
      Serial.print("Searching for object. Servo's angle: ");
      Serial.println(pos);
      scanner.write(pos);
      if (pos == 0)
        returningToZero = false;
    }
  }
  delay(200);
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29.155 / 2;
}

Credits

harisz
1 project • 2 followers

Comments