micros-cycle.ino

Arduino Nano Every · File : micros-cycle.ino · Language : Arduino · Use case : Mesurer un temps court avec micros()

Before servoing a frequency, measure: this test bench uses the Nano Every micros() to time an ADC reading and its processing, with min/max/mean over 100 cycles. The 4809 4 µs resolution suffices for most critical timings.

Hardware

An Arduino Nano Every (ATmega4809 at 20 MHz, same footprint as the Nano, micro-B USB, separate UART chip, 5 V pins, drop-in compatibility with the classic Nano). Nano Every, source on A0 (even floating to measure the converter alone).

Wiring

Nothing critical; note a floating pin adds settling time to the ADC multiplexer.

How it works

micros() counts the system clock; the t1-t0 subtraction handles the natural unsigned wraparound. Min/max statistics reveal the interrupts perturbing the measurement.

Running it

Install the Arduino megaAVR Boards package in the IDE, select Arduino Nano Every, upload. The USB Serial is separate from hardware Serial1 (RX/TX pins): classic serial code works as is.

Variants

For hard real time, compare with TCA timers in capture mode, or disable interrupts during the measurement window.

micros-cycle.ino

// micros() du 4809 : resolution 4 us (prescaler 8 a 20 MHz).
// Mesure de la duree d'une lecture capteur + boucle de controle.
const int CANAL = A0;

unsigned long t0, t1;
unsigned long minD = 1000000, maxD = 0, somme = 0;
int n = 0;

void setup() {
  Serial.begin(115200);
}

void loop() {
  t0 = micros();
  int v = analogRead(CANAL);       // ~100 us sur le 4809
  float tension = v * (5.0 / 1023.0);
  t1 = micros();

  unsigned long duree = t1 - t0;
  minD = min(minD, duree);
  maxD = max(maxD, duree);
  somme += duree;
  n++;

  if (n >= 100) {
    Serial.print(F("min=")); Serial.print(minD);
    Serial.print(F(" max=")); Serial.print(maxD);
    Serial.print(F(" moy=")); Serial.println(somme / n);
    Serial.println(F("us pour lecture+conversion"));
    n = 0; minD = 1000000; maxD = 0; somme = 0;
  }
  delay(10);
}

← Back to the board