🛠 A 1 kHz sine on the 12-bit DAC (A0)
Goal
Drive the R4's true 12-bit DAC on pin A0 - not PWM, no RC filter needed - to output an analog sine wave you can hear through an amplifier or see on a scope.
Code
#include <math.h>
const float FREQ = 1000.0f; // Hz
void setup { analogWriteResolution(12); } // 0..4095
void loop {
static uint32_t t0 = micros;
float phase = fmodf((micros - t0) / 1e6f * FREQ, 1.0f);
float v = 2048.0f + 2047.0f * sinf(2.0f * PI * phase);
analogWrite(A0, (int)v); // true DAC output
}
Couple A0 to a piezo through a small capacitor or feed an amplifier/scope input. A0 is a real analog output, so unlike PWM there is no ripple to filter.
Expected result
A roughly 1 kHz tone; on a scope, a stepped sine around 1.65 V DC offset. Frequency is approximate because the loop timing follows micros calls.
Common mistakes
- Treating A0 like PWM: it is the DAC pin; analogWriteResolution(12) gives the full 0-4095 span.
- Loading the pin: GPIO are limited to 8 mA, so buffer speakers with an amplifier, never wire them to A0 directly.
- Expecting sample-accurate frequency: this naive loop drifts slightly; use a timer for precision.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-poussoir.inoArduinodac-analogique.inoArduinoentree-analogique.inoArduinopwm-respiration.inoArduinoservo-balayage.inoArduino