HC-SR04 to modulate DC Motor Speed

I have a project wherein I need to control the speed of a DC motor which depends on the distance of my hand to a proximity sensor.

I purchased HC-SR04 for my proximity sensor.

However, I have noticed that the proximity sensor's output is a square wave pulse. Using Arduino Uno, is there a code wherein the pulse output of the HC-SR04 can directly modulate the speed of the motor?

This is a very good tutorial

1 Like

You could use the map() function to set the speed of the motor in proportion to the distance measured by the rangefinder.

For example (not tested):
analogWrite(motorPin, map(distance, 0, 300, 0, 255));
0-300 for the range (cm) and 0-255 for PWM (speed)

I like the NewPing library to use with the HCSR-04 sensor. Install the NewPing library with the IDE library manager.

1 Like

Thank you for your immediate replies.

The map function worked well.

Glad to be of assistance.

If your question has been answered to your satisfaction, please mark the thread as solved so that other members that wish to help will not waste their time opening the thread only to find that you no longer require assistance.

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