🛠 ADC 12 bits et PWM sur la Nucleo-F401RE : oversampling, millivolts et LED en fondu

STM32 Nucleo-64 famille F4 — phare : Nucleo-F401RE · intermediaire · Schéma : IMG-stm32f4-nucleo-intermediaire-5-stm32f4nuc-adc-12bits-pwm-fade.svg — potentiomètre relié à A0, bloc ADC 12 bits (0-4095) convertissant en bloc PWM pilotant une LED sur D5 via une résistance

Goals

Use the two analog faces of the F401RE: the 12-bit ADC (16 channels) and timer-driven PWM via analogWrite. You will build a potentiometer-in, brightness-out loop with a proper millivolt conversion, then add oversampling to quiet the last digits.

Hardware

The facts

Code

const int kFadePin  = D5;   // PWM-capable pin mapped by the core
const int kProbePin = A0;   // PA0 on the Arduino connector

void setup {
  Serial.begin(115200);     // ST-LINK VCP (USART2, PA2/PA3)
  analogWrite(kFadePin, 0);
}

void loop {
  // oversample: 64 reads averaged to stabilise the low digits
  long sum = 0;
  for (int i = 0; i < 64; i++) sum += analogRead(kProbePin);
  int raw = sum / 64;

  unsigned long mv = (unsigned long)(raw * 3300 / 4095);  // 12-bit scale
  int duty = map(raw, 0, 4095, 0, 255);
  analogWrite(kFadePin, duty);
  Serial.printf("raw=%4d  %4lu mV  duty=%3d\n", raw, mv, duty);
  delay(100);
}

Steps

  1. Wire the potentiometer divider and the LED as described.
  2. Upload with board Nucleo F401RE selected ; open the serial monitor at 115200.
  3. Sweep the potentiometer: LED brightness and the mV column track together.
  4. Compare a single analogRead against the 64-sample average — the flicker in the last digit disappears.

Expected result

A smooth 0 → 3300 mV sweep with a matching 0–255 PWM duty. The blink + fade + ADC-probe loop shipped in the core's own example set is the same pattern in one sketch: hard blink on PA5, software-visible PWM ramp with analogWrite, and a 12-bit probe printed over the ST-LINK VCP.

Common mistakes

Autres tutoriels pour cette carte

Exemples de code pour cette carte

← Retour à la fiche 🛠 Tous les tutoriels