// import libraries
#include <Servo.h> // Michael Margolis, Arduino
#include <TM1637Display.h> // TM1637 by Avishay Orpaz
// set pins
#define clkPin 2
#define dioPin 3
#define triggerPin 7
#define echoPin 8
#define servoPin 9
// define objects
Servo baseMotor;
TM1637Display monitor(clkPin, dioPin);
// define variables
int angle;
long duration;
int distance;
void setup() {
// setup serial
Serial.begin(9600);
// setup monitor
monitor.setBrightness(7);
//setup servo
baseMotor.attach(servoPin);
// setup ultrasonic
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
for (angle = 0; angle < 180; angle += 10) {
// set angle
baseMotor.write(angle);
delay(1000);
// get distance
getDistance();
// show resault
showResault();
delay(1000);
// clear monitor
monitor.clear();
}
for (angle = 180; angle > 0; angle -= 10) {
// set angle
baseMotor.write(angle);
delay(1000);
// get distance
getDistance();
// show resault
showResault();
delay(1000);
// clear monitor
monitor.clear();
}
}
void getDistance() {
// reset ulterasonic
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// send signal
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// recive signal
duration = pulseIn(echoPin, HIGH);
// calculate distance
distance= duration*0.034/2;
}
void showResault() {
// print in serial
Serial.print("angle: ");
Serial.print(angle);
Serial.print(", Distance: ");
Serial.print(distance);
Serial.println("cm");
// show in monitor
monitor.showNumberDec(distance, false);
}