Analog & PWM Output

Quick Reference

Configuring an Analog Output Pin

Arduino

Most boards don't have true analog output.

CircuitPython

import board
import analogio
dac = analogio.AnalogOut(board.A1)

Using an Analog Output Pin

Arduino

Most boards don't have true analog output.

CircuitPython

dac.value = 32767

Configuring a PWM Output Pin

Arduino

Nothing required

CircuitPython

import board
import pulseio
led = pulseio.PWMOut(board.A1)

Using a PWM Output Pin

Arduino

analogWrite(9, 128);

CircuitPython

led.duty_cycle = 32767

Disscussion

Arduino

Writing to an analog pin is straight forward. This is generally not technically a true analog value, but rather a PWM signal. I.e. the value you are writing sets the duty-cycle of the PWM signal. The range is 0-255, inclusive. The analogWrite is used for this and, like digitalWrite, takes the pin and value.

The Arduino DUE has 2 actual analog to Digital converters that output an actual analog voltage rather than a PWM signal.

Download: file
    analogWrite(pin, val);
  

Putting it together, we can read from an analog pin and write to another. The difference is value ranges needs to be accommodated, and that's what the division by 4 accomplishes.

Download: file
int ledPin = 9;      // LED connected to digital pin 9
int analogPin = 3;   // potentiometer connected to analog pin 3
int val = 0;         // variable to store the read value

void setup()
{
  pinMode(ledPin, OUTPUT);   // sets the pin as output
}

void loop()
{
  val = analogRead(analogPin);   // read the input pin
  analogWrite(ledPin, val / 4);  // analogRead values go from 0 to 1023, analogWrite values from 0 to 255
}

CircuitPython

There are two types of analog output available on CircuitPython hardware: true analog and PWM (as on Arduino).

For true analog output, the value parameter of the AnalogOut object is set to a value between 0 and 65535, the same range as seen in AnalogInput's value range: 0 sets the output to 0v and 65535 sets it to the reference voltage.

Download: file
dac.value = 32767

A related output capability is PWM (Pulse Width Modulation). It's done in a completely different way. Instead of using the analogio module, you'll need to use pulseioand create a PWMOut object using the Pin on which you want to generate the signal.

Download: file
>>> import board
>>> import pulseio
>>> led = pulseio.PWMOut(board.A1)

Once you have a PWMOut object, you can set it's duty cycle (the percent of time the output is high) as a 16 bit interger (0-65535). For example:

 

Download: file
# set the output to 100% (always high)
>>> led.duty_cycle = 65535
# set the output to 0% (always low)
>>> led.duty_cycle = 0
# set the output to 50% (high half the time)
>>> led.duty_cycle = 32767
This guide was first published on Oct 22, 2018. It was last updated on Oct 22, 2018. This page (Analog & PWM Output) was last updated on Oct 22, 2019.