🛠 Tracer une courbe d'accélération en temps réel

M5StickC Plus2 (M5Stack) — ESP32-PICO-V3-02 "stick" wearable kit (SKU K016-P2) · intermediaire · Schéma : IMG-m5stack-stick-c-plus-2-intermediaire-1-m5stick-c2-courbe-imu.svg — Écran de la M5StickC Plus2 en paysage 240×135 affichant une courbe défilante de la norme d'accélération avec grille de repères et tampon circulaire de 240 échantillons.

Objectives

Draw the acceleration magnitude curve in real time on the 240×135 screen (rotation 1) using a circular buffer of 240 samples — one per pixel column — and M5GFX graphics primitives (drawLine, fillRect). This is a fundamental technique for any oscilloscope or chart recorder on this stick.

Hardware

Complete Code

// Oscilloscope d'accélération — tampon circulaire 240 colonnes (écran 240x135)
#include <M5Unified.h>

const int W = 240, H = 135, N = 240;
float buf[N];
int tete = 0;                 // prochaine position d'écriture
const float GMIN = -0.5f, GMAX = 3.0f;   // échelle verticale en g

int yDe(float g) {            // g -> coordonnée écran
  if (g < GMIN) g = GMIN; if (g > GMAX) g = GMAX;
  return H - 1 - (int)((g - GMIN) / (GMAX - GMIN) * (H - 1));
}

void setup {
  auto cfg = M5.config;
  M5.begin(cfg);
  M5.Display.setRotation(1);
  M5.Display.fillScreen(TFT_BLACK);
  M5.Display.setTextColor(TFT_DARKGREY, TFT_BLACK);
  M5.Display.setTextSize(1);
  for (int g = 0; g <= 3; g++)          // grille : 0, 1, 2, 3 g
    M5.Display.drawFastHLine(0, yDe(g), W, TFT_DARKGREY);
}

void loop {
  M5.update;
  float ax, ay, az;
  M5.Imu.getAccel(&ax, &ay, &az);
  float norme = sqrtf(ax * ax + ay * ay + az * az);
  int yAvant = yDe(buf[tete]);          // ancienne valeur de la colonne
  buf[tete] = norme;
  int yApres = yDe(norme);
  M5.Display.drawLine(tete, yAvant, tete, yApres, TFT_BLACK);  // efface colonne
  M5.Display.drawLine(tete, yApres, (tete + 1) % N, yDe(buf[(tete + 1) % N]), TFT_GREEN);
  M5.Display.setCursor(150, 0);
  M5.Display.setTextColor(TFT_GREEN, TFT_BLACK);
  M5.Display.printf("|a| %4.2f g", norme);
  tete = (tete + 1) % N;
  vTaskDelay(20 / portTICK_PERIOD_MS);
  if (M5.BtnB.wasPressed) {           // B = remise à zéro de l'écran
    M5.Display.fillScreen(TFT_BLACK);
    for (int g = 0; g <= 3; g++) M5.Display.drawFastHLine(0, yDe(g), W, TFT_DARKGREY);
  }
}

Expected Verification

At rest, the green curve is flat at 1 g; tapping the table or shaking the stick produces visible peaks. The gray grid marks 0/1/2/3 g. Button B clears and redraws the grid.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials