🛠 Tracer une courbe d'accélération en temps réel
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
- 1× M5StickC Plus2 (v2)
- USB-C cable for uploading
- Arduino IDE / PlatformIO, M5Unified library (includes M5GFX)
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
- Redrawing the entire screen every loop: causes flickering; draw column by column as done here.
- Forgetting to clear the old column value before writing the new one → vertical trail.
- Poorly bounded vertical scale: without clamping in
yDe, peaks go off-screen and the trace jumps to the top/bottom. - Using portrait coordinates while
setRotation(1)is active: the buffer must be 240 columns, not 135. - Too much
vTaskDelay: the curve becomes jagged; too little: the IMU's I2C (bus G21/G22 shared with the RTC) saturates the rendering.
Other tutorials for this board
Code examples for this board
hello-stick.inoArduinoboutons.inoArduinobuzzer.inoArduinoinclinometre.inoArduinohorloge.inoArduinoir-tv.inoArduino