Skip to the content.

Distance Sensor controlled Motor

This tutorial creates a circuit to control a motor with an ultrasonic distance sensor. The greater the distance detected by the sensor, the faster the fan speed.

Motor and sensor code altered from

Components needed:

Wiring Diagram

wiring diagram

Code

const int motorPin = 6;
const int echoPin = 11;
const int trigPin = 12;
const int ledPin = 8;

float distance = 0;


void setup() {
  Serial.begin(9600);

  pinMode(motorPin, OUTPUT);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  pinMode(ledPin, OUTPUT);
}

void loop() {
  int speed;

  distance = getDistance();

  Serial.print(distance);
  // Serial.println(" in"); // Uncomment for inches
  Serial.println(" cm"); // Uncomment for centimeters

  //speed = map(distance, 0, 15, 0, 255); // Uncomment for inches
  speed = map(distance, 0, 50, 100, 255); // Uncomment for centimeters
  speed = constrain(speed, 100, 255);

  Serial.print("speed: ");
  Serial.println(speed);

  analogWrite(motorPin, speed);

  delay(500);
}


float getDistance() {
  float echoTime;
  float calculatedDistance;

  // Make sure transmission pin is turned off first
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  //send out 10ms ultrasonic pulse
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  echoTime = pulseIn(echoPin, HIGH);

  //half the bounce time multiplied by the speed of sound
  //calculatedDistance = echoTime / 148.0; // Uncomment for inches
  calculatedDistance = echoTime / 58.2; // Uncomment for centimeters

  return calculatedDistance;
}