Controlling a Servo With Ultrasonic Sensor Signal Using Arduino Code not working

Hello I'm new to this and found a project online. I put it together and pasted in the code. I get an error message saying Compilation error: #include expects "FILENAME" or It doesn't say what file should go next to it in the source material, here is the code.

#include

Servo myservo; // create servo object to control a servo

const int trigPin = 2;

const int echoPin = 4;

void setup() {

// initialize serial communication:

Serial.begin(9600);

myservo.attach(9); // attaches the servo on pin 9 to the servo object

}

void loop() {

// and the distance result in centimeters:

long duration, cm;

pinMode(trigPin, OUTPUT);

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(20);

digitalWrite(trigPin, LOW);

pinMode(echoPin, INPUT);

duration = pulseIn(echoPin, HIGH);

// convert the time into a distance

cm = microsecondsToCentimeters(duration);

// the condition for the distance

if ( cm > 7 && cm < 14)

{

myservo.write(140); // sets the servo position according to the scaled value

delay(4000);

}

else if ( cm < 8)

{

myservo.write(40); // sets the servo position according to the scaled value

delay(100);

}

else

{

myservo.write(40); // sets the servo position according to the scaled value

delay(100);

}

Serial.print(cm);

Serial.print("cm");

Serial.println();

delay(100);

}

long microsecondsToCentimeters(long microseconds) {

// The speed of sound is 340 m/s or 29 microseconds per centimeter.

// The ping travels out and back, so to find the distance of the

// object we take half of the distance travelled.

return microseconds / 29 / 2;

}

Any help would be much appreciated!

Welcome to the forum

What should go after the #include statement is the name of the file that you want to include in the sketch

My guess would be that the line should be

#include <Servo.h>

as the code uses the Servo library

Please post a link to the project

Thank you for responding, that helped and fixed that issue. the link to the website is here https://www.instructables.com/Controlling-a-Servo-With-Ultrasonic-Sensor-Signal-/

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.