I have recently been starting to learn electronics using Arduino like technology. I’ve had this kit lying around for some time and thought it best to at least try to use it. Besides the standard LED projects which I felt were a bit repetitive, I have found controlling motors most interesting.

First, I used an analog joystick:

 

This worked relatively well, the only library I needed to use here was the Servo library which I obtained from the library manager in the IDE.

The code that I wrote to do this took readings from the analog pin that the joystick was connected to on the Arduino, which then moved the Servo based on the extremities of the reading that was obtained. There are also other pins exposed on the joystick for y-axis readings and clicking the joystick down. I didn’t utilize these however as I thought it pointless seeing as I was only controlling one motor.

 

Next, I used an IR receiver to control the same servo:

 

 

Most of the code was already written to control the motor, the only things that needed adding were the IR based functionality.

This was done by decoding Hex values received from the remote control, these vary by manufacturer and can be looked up here.

The two values I chose to use were and , to move the motor anti-clockwise and clockwise, respectively.

 

After all of this, I kinda ran out of ideas, but then I found the HCSR04. I wanted to be able to use it to control the motor depending on the distance from the unit.

 

The Wiring

I found the wiring relatively simple and that it could be done without a breadboard. However, I like to use one when I can to keep things tidy.

See below Fritzing images:

 

 

 

 

 

 

 

 

The Code

The code uses the Servo and the HCSR04 libraries.  These can be included in the code as its being worked on through the Arduino IDE through Sketch -> Include Library -> Manage Libraries.

The general gist of the code is this:  If the HCSR04 detects something within a certain distance, it then moves the servo.

 

#include <HCSR04.h>

#include <Servo.h>

int SERVO_PIN = 9;

int pos = 0;

int triggerPin = 13;

int echoPin = 12;


UltraSonicDistanceSensor distanceSensor(triggerPin, echoPin);


Servo servo;
  
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  servo.attach(SERVO_PIN);
  servo.write(pos);
}

void loop() {
  // put your main code here, to run repeatedly:
  double distance = GetDistance(distanceSensor);
  
  ;

  if (distance <= 60.0)
  {
     Serial.print("Movement detected.\n");
     SweepServo(servo, 90);
  }


  if (distance < 0.00)
  {
    
  }
  else 
  {
    
  }
}

  double GetDistance(UltraSonicDistanceSensor sensor)
  {
    double distance = sensor.measureDistanceCm();
    return distance;
  }

  void SweepServo(Servo servo, int maxAngle)
  {
      
        if (pos <= maxAngle)
        {

           pos += 5;
           servo.write(pos);
           delay(500);

           Serial.print("Current position: ");
           Serial.print(pos);
           Serial.print("\n");
           
        }
        if(pos >= maxAngle)
        {
           pos = 0;
           servo.write(pos);
           delay(500);

          
          Serial.print("Current position: ");
          Serial.print(pos);
          Serial.print("\n");
        }
  
  }

I tried to abstract some of the logic out into separate methods out of the loop() as a bit of a refactoring exercise. I found this somewhat pointless as I seem to be using global variables in one of them, however  (Doh!).

 

The Result

After uploading the code to the board, try to move objects in front of the sensor and see if it activates the motor. If it does, then that’s great. If not, then unluckily I can’t help you.

Just kidding…

If you encounter an error it’s probably best to check that you have wired up the modules to the Arduino / breadboard properly then compare it to the fritzing diagrams up there. I have also added Serial.print() method calls at certain points in the program, so you can check whether inputs and outputs are happening by opening the serial monitor through Tools -> Serial Monitor. The serial monitor window may need adjusting to correspond to the correct COM port.

 

One thought on “Controlling a servo motor with a HCSR04 ultrasonic sensor”

  1. This is so informative! You’ve done such a good job explaining everything that you have achieved so it is easy to duplicate! Well done.

Leave a Reply

Your email address will not be published. Required fields are marked *