🛠 Lire un capteur analogique (potentiomètre)
Objectives
Read an analog sensor (potentiometer) on the SAMD21G18A ADC: the MKR WAN 1310 has 7 analog inputs configurable at 8, 10, or 12 bits, and a 10-bit DAC output. You will learn how to change the read resolution and plot the curve in the Serial Plotter.
Hardware
- 1 MKR WAN 1310 board
- 1 potentiometer (10 kΩ recommended)
- Wiring: two outer pins to 3.3 V and GND, wiper to A0 (3.3 V logic, never exceed 3.3 V on a pin)
Complete code
// Lecture analogique 12 bits sur A0 — MKR WAN 1310
const int CAPTEUR = A0;
void setup {
Serial.begin(115200);
while (!Serial);
analogReadResolution(12); // 0..4095 au lieu de 0..1023 par défaut
analogRead(A0); // première lecture à jeter
Serial.println("Tourne le potentiometre");
}
void loop {
int brut = analogRead(CAPTEUR); // 0..4095
float tension = brut * 3.3f / 4095.0f; // tension réelle sur A0
Serial.print("brut=");
Serial.print(brut);
Serial.print("\tU=");
Serial.print(tension, 2);
Serial.println(" V");
delay(50);
}
Expected verification
Turning the potentiometer, the raw value follows 0 → 4095 and the calculated voltage follows 0 → 3.3 V. The Serial Plotter displays a continuous curve; the values match multimeter measurements.
Common errors
- Forgetting
analogReadResolution(12)and then dividing by 1023: the calculated voltage is half as large as it should be. - Powering the potentiometer with 5 V: the wiper can then send more than 3.3 V to A0, exceeding the circuit's operating voltage (3.3 V).
- Reading A0 without a wired pin: floating and unstable values, which is normal for an unconnected input.
- Confusing ADC (7 inputs) and DAC (1 analog output, 10-bit DAC):
analogWriteon a PWM pin is not the DAC output.
Other tutorials for this board
Code examples for this board
join-otaa.inoArduinouplink-confirme.inoArduinodownlink.inoArduinoactivation-abp.inoArduinosuivi-adr.inoArduinoclasse-c.inoArduino