🛠 Lire un capteur analogique sur A1

Arduino MKR GSM 1400 · debutant · Schéma : IMG-mkr-gsm-1400-debutant-3-mkrgsm-capteur-analogique.svg — MKR GSM 1400 avec un potentiomètre alimenté en 3,3 V dont le curseur est relié à l'entrée analogique A1, tension affichée sur la console USB.

Objectives

Use the analog inputs of the MKR GSM 1400: the board has 7 inputs A0–A6 with a 12-bit ADC (ADC_RESOLUTION 12 in the core variant), and A0 is also the DAC output. This tutorial reads a potentiometer on A1, averages several samples, and turns on the onboard LED above a threshold — the basic pattern for any analog sensor (level probe, water quality sensor like WaterAid, etc.).

Hardware

Complete code

// Capteur analogique sur A1, ADC 12 bits, moyenne mobile + seuil LED
const uint8_t CAPTEUR = A1;
const uint16_t SEUIL  = 2048;   // milieu de l'echelle 12 bits (0..4095)

uint16_t lireMoyenne(uint8_t broche, uint8_t n) {
  uint32_t somme = 0;
  for (uint8_t i = 0; i < n; i++) {
    somme += analogRead(broche);
    delay(2);
  }
  return somme / n;
}

void setup {
  analogReadResolution(12);      // 12 bits par defaut, explicite ici
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  while (!Serial) {}
}

void loop {
  uint16_t v = lireMoyenne(CAPTEUR, 16);
  // Tension approximative : ADC alimente en 3,3 V, pleine echelle 4095.
  float mv = v * 3300.0f / 4095.0f;
  Serial.print("A1 brut : "); Serial.print(v);
  Serial.print("  ~"); Serial.print(mv);
  Serial.println(" mV");
  digitalWrite(LED_BUILTIN, v > SEUIL ? HIGH : LOW);
  delay(200);
}

Expected verification

When turning the potentiometer, the raw value follows from 0 to approximately 4095 and the displayed voltage remains close to 0–3300 mV. The onboard LED turns on at mid-range. Averaging over 16 samples stabilizes the reading: without it, the last digits fluctuate, especially when the radio module is transmitting (at this stage it is inactive).

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials