🛠 A 1 kHz sine on the 12-bit DAC (A0)

Arduino UNO R4 Minima · debutant · Schéma : IMG-uno-r4-minima-debutant-3-dac-sine-a0.svg — UNO R4 Minima, broche A0 reliée à un buzzer piézo amplifié ou une entrée d'oscilloscope, sortie sinusoïdale 1 kHz dessinée, badge DAC 12 bits.

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials