WiringProject / Wiring

Wiring Framework
http://wiring.org.co/
Other
217 stars 168 forks source link

Alternating between AnalogWrite and DigitalWrite on the same pin behaves unexpectedly. #31

Open Nilloc opened 11 years ago

Nilloc commented 11 years ago

The following sketch causes the LED to go fully bright, then dim (analogWrite(50)) then stay dim, never returning to 5 volts.

The sketch does work as expected in the Arduino 1.0.1 IDE.

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

void loop()
{
  digitalWrite(11, HIGH);
  delay(500);
  analogWrite(11, 50);
  delay(500);
}

Tested using a Sparkfun Redboard and a 2.7v LED.

bhagman commented 11 years ago

This is an obscure issue since there is typically no reason to use digitalWrite() and analogWrite()/pwmWrite() on the same pin in the same sketch.

The problem comes from the fact that digitalWrite() no longer (compared to previous versions) clears the the PWM mode for the pin.

This was chosen for optimization reasons (i.e. to reduce the digitalWrite() to a single machine instruction if using a constant for the pin number.)

However, as we move forward, it will make more sense to be thorough instead of optimal.

A fix for this problem is to clear the output mode for the given pin in its associated timer at the start of digitalWrite().

This applies to the AVR8Bit core only.

Fix forthcoming.