└── pet_ino (1).ino /pet_ino (1).ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // constants won't change 4 | const int TRIG_PIN = 6; // Arduino pin connected to Ultrasonic Sensor's TRIG pin 5 | const int ECHO_PIN = 7; // Arduino pin connected to Ultrasonic Sensor's ECHO pin 6 | const int SERVO_PIN = 9; // Arduino pin connected to Servo Motor's pin 7 | const int DISTANCE_THRESHOLD = 50; // centimeters 8 | 9 | Servo servo; // create servo object to control a servo 10 | 11 | // variables will change: 12 | float duration_us, distance_cm; 13 | 14 | void setup() { 15 | Serial.begin (9600); // initialize serial port 16 | pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode 17 | pinMode(ECHO_PIN, INPUT); // set arduino pin to input mode 18 | servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object 19 | servo.write(0); 20 | } 21 | 22 | void loop() { 23 | // generate 10-microsecond pulse to TRIG pin 24 | digitalWrite(TRIG_PIN, HIGH); 25 | delayMicroseconds(10); 26 | digitalWrite(TRIG_PIN, LOW); 27 | 28 | // measure duration of pulse from ECHO pin 29 | duration_us = pulseIn(ECHO_PIN, HIGH); 30 | // calculate the distance 31 | distance_cm = 0.017 * duration_us; 32 | 33 | if(distance_cm < DISTANCE_THRESHOLD) 34 | servo.write(90); // rotate servo motor to 90 degree 35 | else 36 | servo.write(0); // rotate servo motor to 0 degree 37 | 38 | // print the value to Serial Monitor 39 | Serial.print("distance: "); 40 | Serial.print(distance_cm); 41 | Serial.println(" cm"); 42 | 43 | delay(500); 44 | } 45 | --------------------------------------------------------------------------------