Controlling Servos Without Timers

Here is a sketch that uses functions I found that allow you to control servo motors without using any timers!!! :smiley:

The servo is only held in position for a specific delay period so this sketch would be unsuitable for say a robotic arm, but just perfect for rotating a sensor. Also, by not holding the servo in position, the robot (or whatever thingy) saves power.

Before looking at this code, I did not fully understand how servo signal timing worked, but now I do.
Bloody simple.
I wish I thought of this myself.

Maybe later I’ll add some definitions, change the function to also accept angles by degrees and raw timing, and put this into a proper library and post the update here.

SoftServo.ino


/*******************************
 * Softservo.ino
 * software servo control without using timers
 * note that these functions block until complete
 *******************************/

void setup()                    // run once, when the sketch starts
{
    softServoAttach(5);
}

void loop() 
{
  softServoWrite(90, 500);
  delay(2000);
  softServoWrite(45, 500);
  delay(2000);
  softServoWrite(135, 500);
  delay(2000);
}

/***********************************************************************/
int servoPin;
void softServoAttach(int pin)
{
  servoPin = pin;
  pinMode(pin, OUTPUT);
}
// writes given angle to servo for given delay in milliseconds
void softServoWrite(int angle, long servoDelay)
{
  int pulsewidth = map(angle, 0, 180, 544, 2400); // width in microseconds
  do {
    digitalWrite(servoPin, HIGH);
    delayMicroseconds(pulsewidth);
    digitalWrite(servoPin, LOW);
    delay(20); // wait for 20 milliseconds
    servoDelay -= 20;
  } 
  while(servoDelay >=0);
}