🛠 Lire un capteur analogique sur A1
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
- Arduino MKR GSM 1400 board
- 1 10 kΩ potentiometer (or any 0–3.3 V analog sensor)
- Breadboard and jumper wires
- USB for power (radio module not used)
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
- Powering the sensor with 5 V and reading without a voltage divider: the ADC accepts a maximum of 3.3 V on the pin; beyond that, measurements are incorrect and you risk damaging the input.
- Expecting a 0–1023 range: the SAMD21 is configured for 12 bits on this core, not 10 bits like an Arduino Uno.
- Measurement noise: keep grounds close, increase the averaging, and do not compare two successive readings without a margin (hysteresis) around the threshold.
- Confusing A1 (input) with A0/DAC0 (the board's only analog output) as an output.
- Forgetting
while (!Serial)and thinking the console is dead at startup.
Other tutorials for this board
Code examples for this board
gsm-connexion.inoArduinoenvoi-sms.inoArduinohttp-get.inoArduinohttp-post-capteur.inoArduinoheure-gsm.inoArduinoappels.inoArduino