Alden’s ITP Home

Breaking A Servo?

I wanted to make a project that would display a dubiously motivational message each time I sat at my home office desk. To start off I used a HC-SR04 ping distance sensor and attached a pin with a message (in this case a pin I got at the art book fair) to a little SG90 micro servo motor. I initially tried to map the distance readings of the HC-SR04 to the angle of the servo motor, but it was too noisy and the servo jittered around quickly (you can see that code commented out below).

After that I tried running it as an if/then statement, where the servo would change positions if the distance sensor recorded a short distance. However, the servo didn’t change position even as I watched the distance go below the threshold on the serial monitor. Instead it stayed in one place making a really awful noise and getting hotter until it stopped moving at all. After that it wouldn’t move at all even for simpler movements like the servo sweep example code, leading me to think that it was broken. However I tried it again after it had cooled down and it worked fine, but just still not for the application I wanted.

You can see the code here:

#include <Servo.h>

Servo myServo;

const int trigPin = 13;
const int echoPin = 12;
const int servoPin = 6;
int servoAngle;

long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
  myServo.attach(servoPin);
}

void loop() {
  myServo.write();
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;
  Serial.print("Distance: ");
  Serial.println(distance);

  if(distance < 10) {
    myServo.write(90);
  } else {
    myServo.write();
  }



  // int servoAngle = map(distance, 0, 30, 0, 179);
  //  myServo.write(servoAngle);

}