🛠 Lire un capteur analogique sur A0
Objectives
Read an analog sensor (potentiometer, thermistor, light sensor) on the A0 input of the MKR NB 1500. The SAMD21 has a 10-bit ADC (0–1023) limited to 3.3 V, and A0 (PA02) is also the microcontroller's DAC output: the same pin can both measure and generate an analog voltage.
Hardware
- 1 MKR NB 1500 board + micro-USB cable
- 1 10 kΩ potentiometer: one end to 3.3 V, the other to GND, the wiper to A0
- Optionally, a 3.3 V sensor instead of the potentiometer (never apply a signal > 3.3 V to A0)
Complete code
// Lecture ADC + boucle DAC — MKR NB 1500
const uint8_t SENSOR_PIN = A0; // PA02 : entree ADC0 + sortie DAC (DAC0)
void setup {
Serial.begin(9600);
while (!Serial);
analogReadResolution(10); // ADC SAMD21 : 10 bits par defaut
}
void loop {
int raw = analogRead(SENSOR_PIN); // 0..1023 pour 0..3,3 V
uint32_t mv = (uint32_t)raw * 3300UL / 1023UL; // tension en millivolts
Serial.print("raw="); Serial.print(raw);
Serial.print(" -> "); Serial.print(mv); Serial.println(" mV");
analogWrite(DAC0, raw); // reemet la meme tension en 0..3,3 V
delay(500);
}
Expected verification
Turn the potentiometer: the displayed value goes from 0 to 1023 and the millivolts follow. By connecting A0 (via a 100 nF capacitor to GND for smoothing) to another analog input, the voltage copied by the DAC is identical — the measure/reproduce loop works.
Common errors
- Applying 5 V to A0 (5 V sensor without a voltage divider): above 3.3 V it saturates, worse, you risk damaging the SAMD21.
- Expecting 12-bit resolution: the ADC is 10-bit,
analogReadreturns 0–1023. - Forgetting that the pin switches to DAC mode as soon as you call
analogWrite(DAC0, ...): you must reconfigure it to read it again afterwards. - Measurements that "jump" by several steps: normal without decoupling; add an average over N readings.
Other tutorials for this board
Code examples for this board
attente-lte-nbiot.inoArduinochoix-bande.inoArduinopublish-mqtt-minimal.inoArduinoeconomie-energie.inoArduinogeoloc-cellules.inoArduinotest-coverage.inoArduino