Problem with Code

Hi guys,

I am making a project that uses an ultrasonic sensor to control a servo motor.The motor is only meant to run when an object is a certain distance from the sensor but the sensor just keeps running.Please have a look at my code(which I have attached) and let me know if you find something.

arduino_code.ino (1.86 KB)

Here is your code, it’s easier to read like this

#include <Servo.h>

// defines pins numbers
const int trigPin = 2;
const int echoPin = 3;
// defines variables
long duration;
int distance;

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object

  Serial.begin(9600); // Starts the serial communication

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance= duration*0.034/2;

  Serial.print("Distance: ");
  while(distance < 10);
    /*for (pos = 0; pos <= 90; 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'
      delay(15);                       // waits 15ms for the servo to reach the position
    for (pos = 90; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(45);                       // waits 15ms for the servo to reach the position
    } */

In the loop, you only measure the distance when it is less than 10 (cm ?). But if the distance becomes higher than 10, then it is not measured anymore and it will never change.
As you do not provide an initial value for the distance, laybe the compiler sets it to 0 at beginning but I’m not 100% sure about that. If it has a random value, then maybe it is greater than 10 and you will never do any measurement.
Furthermore, all the servo commands are commented out so the code does not control the servo.

All of the servo actions have been commented out. All your sketch does is measure the distance over and over.

Do you have a 'continuous rotation' servo? It will continue to move until you write just the right value to it (should be near 90). Since your code doesn't write any value to the servo I guess the default is not correct for stopping the motor.