#include Servo myservo; Servo myservo2; int pos = 0; int ledpins = 2; const int TRIG_PIN = 12; const int ECHO_PIN = 13; void setup() { // initialize serial communication: Serial.begin(9600); pinMode(2, OUTPUT); pinMode(TRIG_PIN,OUTPUT); pinMode(ECHO_PIN,INPUT); } void loop() { long duration, distance; // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); duration = pulseIn(ECHO_PIN,HIGH); // convert time into distance distance = duration / 29.1 / 2 ; if (distance <= 50){ myservo.attach(9); myservo2.attach(10); Serial.println("Detectie!"); /* ///////////////////closer than 100cm///////////////////////*/ for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees // in steps of 1 degree myservo.write(pos); // tell servo to go to position in variable 'pos' myservo2.write(pos); digitalWrite(ledpins, HIGH); delay(0); // waits 15ms for the servo to reach the position } for (pos = 180; pos >= 80; pos -= 1) { // goes from 180 degrees to 0 degrees myservo.write(pos); // tell servo to go to position in variable 'pos' myservo2.write(pos); delay(0); // waits 15ms for the servo to reach the position } /* ////////////////////////////////////////////////*/ } else { Serial.print(distance); Serial.print("cm"); Serial.println(); myservo.detach(); myservo2.detach(); digitalWrite(ledpins, LOW); } }