PWM : digitalWrite() vs. analogWrite()

Hello everyone,

We have been experimenting with the Arduino for a few months now and was wondering if you could explain this "phenomenon".

We're trying out servo control without the Servo library, ie. using the PWM directly to the pins.

The common example already seen in many places is;

int servopin = 11;
int pulse = 1500;

void setup()
{
  pinMode(servopin,OUTPUT);
}

void loop()
{
  digitalWrite(servopin,HIGH);
  delayMicroseconds(pulse);
  digitalWrite(servopin,LOW);
  delay(20);
}

However, having discovered analogWrite(), we replaced the loop() section with;

  analogWrite(servopin, 127); // min-max = 0-255
  delay(500);               // wait for half second ??

Our question is, how come the latter leaves the servo jittery ? It also gets rather hot pretty quickly.

What are the underlying circumstances that make the digitalWrite() and analogWrite() scenarios different ?

Thanks!

What are the underlying circumstances that make the digitalWrite() and analogWrite() scenarios different ?

digitalWrite() turns a pin on or off. analogWrite() turns the pin on and off very fast, so that the duty cycle is what you specify (as a percentage of 255).

They are not interchangeable.

Hoever you can (by direct register manipulation) reprogram the PWM rate from the default (which about 500Hz on some pins, about 1kHz on others). This requires understanding of the counter modes and registers. You probably want a PWM frequency of 50 - 100Hz or so to get sensible behaviour from a servo.

Of course the Servo library is an even better idea as it can drive more pins and isn't limited to the PWM-capable pins.

PaulS:
digitalWrite() turns a pin on or off. analogWrite() turns the pin on and off very fast, so that the duty cycle is what you specify (as a percentage of 255).
...

ahh, that makes sense.