#include <Servo.h>
// constants won't change
const int TRIG_PIN = 6; // Arduino pin connected to Ultrasonic Sensor's TRIG pin
const int ECHO_PIN = 7; // Arduino pin connected to Ultrasonic Sensor's ECHO pin
const int SERVO_PIN = 9; // Arduino pin connected to Servo Motor's pin
const int BUZZER_PIN = 3; // Arduino pin connected to Piezo Buzzer's pin
const int DISTANCE_THRESHOLD = 50; // centimeters
const int PIN_RED = 12;
const int PIN_GREEN = 10;
const int PIN_BLUE = 11;
Servo servo; // create servo object to control a servo
// variables will change:
float duration_us, distance_cm;
int pos = 90;
void setup() {
Serial.begin (9600); // initialize serial port
pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode
pinMode(ECHO_PIN, INPUT); // set arduino pin to input mode
pinMode(BUZZER_PIN, OUTPUT); // set arduino pin to output mode
servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object
servo.write(pos);
pinMode(PIN_RED, OUTPUT);
pinMode(PIN_GREEN, OUTPUT);
pinMode(PIN_BLUE, OUTPUT);
}
void loop() {
// generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);
// calculate the distance
distance_cm = 0.017 * duration_us;
if(distance_cm < DISTANCE_THRESHOLD){
digitalWrite(BUZZER_PIN, HIGH); // turn on Piezo Buzzer
// color red
setColor(255, 0, 0);
lookServ(); // call function lookServ()
}
else{
// color green
setColor(0, 255, 0);
digitalWrite(BUZZER_PIN, LOW); // turn off Piezo Buzzer
servo.write(pos); // servo 90 degree
}
// print the value to Serial Monitor
Serial.print("distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
delay(500);
}
void setColor(int R, int G, int B) {
// set the color for LED RGB
analogWrite(PIN_RED, R);
analogWrite(PIN_GREEN, G);
analogWrite(PIN_BLUE, B);
}
void lookServ(){
//serv look right and left then back to pos
servo.write(30);
delay(700);
servo.write(150);
delay(700);
servo.write(pos);
delay(500);
}