Hey,
This is my first time using Arduino's.
I wanted to write a code in which I use a ultrasonic sensor that detects movement say less than 50cm. In which that will trigger the servo motor to move 90 degrees.
Here is what I have so far
#include <Servo.h>
#define trigPin 13
#define echoPin 12
Servo myservo;
void setup () {
myservo.attach(9);
myservo.write(0);
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop(){
int duration, distance,pos=0,i;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) /29.1;
Serial.print (distance);
Serial.print(" cm");
if (distance < 50) // This is where the Servo On/Off happens
{
myservo.write(180);
}
else{
myservo.write(0);
}
delay(100);
}
After I finish uploading all I get is, the motor to continuously move forever.
I just want the servo to move 90 degrees once, when the ultrasonic sensor has detected movement for say 50 cm or less.
First time with Arduino's and coding. Help is appreciated.