Does analogWrite() to an analogue pin mean anything?

I thought that writing to an analogue pin with analogWrite() cause either the output voltage to change to some n/255 * 5 volts or something akin to PWM but it seems to do neither.

So. What behaviour should I expect (if any) if I analogWrite() to an analogue pin?

Basically it is a Pulse Width Modulation (PWM) output. It turns on/off (5v/0v) multiple times per second... See analogWrite() - Arduino Reference

The only pins that respond to analogWrite() are the PWM pins.

I would say that you con expect undefined behavior.

1 Like

No. analogWrite(uint8_t pin, int val) documented in the wiring_analog.c file of the IDE. It contains a lengthy switch case statement base on
switch(digitalPinToTimer(pin))
and which terminates with

case NOT_ON_TIMER:
      default:
        if (val < 128) {
          digitalWrite(pin, LOW);
        } else {
          digitalWrite(pin, HIGH);
        }

Thanks, Can I amend my statement to "nothing really useful"? :slightly_smiling_face:

It's not akin to pwm, it is pwm.

image

It's on for n/255 of the period, 128 or 50% in the 'scope trace shown; the frequency is either 980 or 490 depending on which pin you use.

Edit... just struck me though, that when you say "analogue pin" you may mean the Ax analog inputs, not the pwm output ~ pins?

1 Like

Good catch there, he probably does. The pins marked as analogue input A0 to A6 can be used as normal digital inputs / outputs and are not PWM capable pins.

As you pointed out a PWM capable pin is normally marked with a ~ next to the pin number.
Here is an animated gif of PWM
PWMan
From my tutorial on PWM
http://www.thebox.myzen.co.uk/Tutorial/PWM.html

I kind of agree with this comment about what happens on pins that do not support PWM.

I have done a few LCD libraries that have backlight dimming control.
But I won't use analogWrite() if the backlight control pin doesn't support PWM.
IMO, for backlight dimming control, the backlight should be on for any non zero dim value, instead of being off until the dim value is half way up to max.

IMO, analogWrite() as a very bad name for a function that does PWM.
These days it starts to get really confusing and messy since some MCUs actually support analog outputs.

--- bill

1 Like

I think that is the opinion of virtually everyone.

1 Like

Some chips actually have a digital-to-analog converter (DAC) as well as an ADC, and they usually group it with the "analog" pins, and support a true analog output.

For example, the Arduino Zero has the DAC on A0, and supports analogWrite() on that pin.

But for most AVR Arduinos, there is no real analog output, and PWM outputs are not available on the same pins that can do analog input.