0% found this document useful (0 votes)
2 views

Untitled 5

The document contains an Arduino sketch that controls a servo motor based on distance measurements from an ultrasonic sensor. It uses the Servo library and calculates distance using the trigPin and echoPin to trigger and read the ultrasonic sensor. The servo position is set to 90 degrees if the distance is less than 100 cm and to 0 degrees if the distance is greater than 100 cm.

Uploaded by

miojomaromba
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Untitled 5

The document contains an Arduino sketch that controls a servo motor based on distance measurements from an ultrasonic sensor. It uses the Servo library and calculates distance using the trigPin and echoPin to trigger and read the ultrasonic sensor. The servo position is set to 90 degrees if the distance is less than 100 cm and to 0 degrees if the distance is greater than 100 cm.

Uploaded by

miojomaromba
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <Servo.

h>

const int echoPin = 3;


const int trigPin = 2;

Servo myservo;

int pos = 0;

void setup() {
myservo.attach(9);
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
Serial.begin(9600);
}

void loop() {

int dist = CalcDist(trigPin, echoPin);


Serial.println(dist);

if(dist<100){
pos = 90;
myservo.write(pos);
delay(15);
}else if(dist>100){
pos = 0;
myservo.write(pos);
delay(15);
}
}

int CalcDist(int trigPin, int echoPin){


long duration, distanceCm;

digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distanceCm = duration*343/10000/ 2;
return distanceCm;
}

You might also like