EN
Cloud
R1BBIT · COMMUNITY

Projects

A question from the R1BBIT community

Projects·R1BBITadmin·· edited

ESP-NOW lets you transmit data between two ESP32 boards at lightning speed!

The ESP32-S3 + QMI8658 sends gyroscope data wirelessly.
The ESP32-C3 receives the data and controls three servos, enabling movement along all three axes.
Fast wireless communication. Real-time motion control. No cables!

3D Model

Script for ESP32-S3 (Sender):

R1 BASIC
// =====================================================================
//  ELECTRONIC LEVEL + GYRO SERVO CONTROLLER
//  Waveshare ESP32-S3-Touch-AMOLED-2.16 (AMOLED 480x480 + QMI8658 IMU)
//
//  Two jobs in one script:
//
//  1. Artificial horizon on the screen (accelerometer)
//     - sky and ground split by the horizon. The horizon stays level with
//       the real world: tilt the board left / right and it turns the
//       other way on the screen; lean it forward / back and it moves
//       down / up. Two shades of sky and ground give depth.
//     - roll scale at the top with a pointer that always points to the
//       real "up"
//     - pitch (nose up / down) bar on the right edge with its angle
//     - fixed yellow level mark in the middle
//     - ROLL in degrees with the direction (LEFT / RIGHT) and an arrow
//     - when both roll and pitch are under LVLTHR the horizon turns
//       green and LEVEL is shown
//
//  2. Three-axis servo control over ESP-NOW (gyroscope)
//     - the gyro rotation speed is summed over time = angle turned
//       around each axis
//     - each angle becomes a servo duty delta -DMAX..+DMAX, sent to the
//       second board as X, Y, Z every SENDMS ms
//
//  Tap the screen: the current position becomes zero (level
//  calibration) and the three servo angles return to 0 (servos centre).
//
//  IMU: QMI8658_INIT fills ax, ay, az (acceleration in g, gravity
//  included) and gyx, gyy, gyz (rotation speed, deg/s) by itself in the
//  background every IMUMS ms. The script only reads those variables.
//
//  How the level angles are found: the accelerometer measures gravity.
//  With the board at rest gravity points straight down, so
//    roll  = angle of gravity inside the screen plane
//    pitch = how much gravity leaves the screen plane
//  Both are smoothed with a time-based low-pass filter.
//
//  Drawing: the ground is the part of the screen below the horizon line.
//  It is found by cutting the screen square with that line (polygon
//  clipping), which gives a polygon of 3..5 corners fully inside the
//  screen; it is filled with triangles from its first corner. Nothing
//  is ever drawn outside the screen.
// =====================================================================
CONFIG
// --- board memory -------------------------------------------------
// flash and PSRAM size in MB
FLASH_SIZE      16
PSRAM_SIZE      8
// time zone for the clock functions (not used by this script)
TIMEZONE        "UTC-5"
// --- AMOLED CO5300, 480x480, 4-lane QSPI --------------------------
// display controller chip and its bus
DISPLAY_DRIVER  CO5300
DISPLAY_BUS     QSPI
// the QSPI bus uses the SPI2 block; its clock pin and clock rate
DISPLAY_SPI     2
SPI_CLK         38
SPI_FREQ        80000000
// chip select and reset pins of the panel
DISPLAY_CS      12
DISPLAY_RST     39
// the four QSPI data lines
DISPLAY_QSPI_D0 4
DISPLAY_QSPI_D1 5
DISPLAY_QSPI_D2 6
DISPLAY_QSPI_D3 7
// panel resolution, px
DISPLAY_WIDTH   480
DISPLAY_HEIGHT  480
// AMOLED has no backlight: -1 = there is no backlight pin
DISPLAY_BL      -1
// --- shared I2C bus: touch, RTC, IMU, PMU, codecs -----------------
// data and clock pins, bus speed 400 kHz
I2C_SDA         15
I2C_SCL         14
I2C_FREQ        400000
// --- CST9220 touch ------------------------------------------------
// touch controller on I2C bus 0, interrupt and reset pins, resolution
TOUCH_DRIVER    CST9220
TOUCH_I2C       0
TOUCH_INT       11
TOUCH_RST       40
TOUCH_WIDTH     480
TOUCH_HEIGHT    480
// --- buttons ------------------------------------------------------
// both buttons short to ground: pull-up on, inverted so a press reads 1
IN1             18
IN1_PULL        UP
IN1_INVERT      1
IN2             0
IN2_PULL        UP
IN2_INVERT      1
END_CONFIG
// Left over from an earlier version that sent ax / ay / az as GIR0..2.
// GIR, GIR0..GIR2 are no longer sent; girT is still used as the timer
// of the ESP-NOW sending in the main loop.
VAR GIR[3]
VAR GIR0, GIR1, GIR2, girT = 0
// ---- display on: panel, UI engine and touch in one call ----
DISPLAY_INIT
// panel brightness, 0..100
DISPLAY_BRIGHTNESS(90)
// drawing canvas over the whole screen; frames are shown by DISPLAY_UPDATE
DISPLAY_INIT_CANVAS(0, 0, 480, 480)
// IMU readings, filled in the background by QMI8658_INIT.
// They must exist before the INIT line.
// ax, ay, az - acceleration, g (gravity included)
VAR ax = 0
VAR ay = 0
VAR az = 1
// gyx, gyy, gyz - rotation speed, deg/s
VAR gyx = 0
VAR gyy = 0
VAR gyz = 0
// ---------------- settings ----------------
// Axis signs: flip one to -1 if the horizon turns the wrong way.
//   AXS - must make gravity positive when the board stands upright
//         (roll = 0)
//   AYS - left / right tilt
//   AZS - forward / back tilt
CONST AXS = 1
CONST AYS = 1
CONST AZS = 1
// pitch -> pixels: how far the horizon moves per degree of pitch
CONST PPD = 4
// -1 or 1: which way the horizon moves when the board leans forward
CONST PSG = -1
// Smoothing: the angle covers most of the distance to the sensor in
// this many seconds, no matter how often the loop runs. 0.08 s is
// quick enough to follow a hand and still kills the sensor's noise;
// raise it if the numbers twitch, lower it if the picture lags.
CONST SMO = 0.08
// both angles below this -> LEVEL, degrees
CONST LVLTHR = 0.5
// The settings below are variables, not CONST, on purpose: CONST holds
// only 32 names and the script already uses most of them. Going over
// the limit silently dropped DMAX, AMAX, GDB and SENDMS before.
// Raw IMU numbers in the screen corners: twelve text draws per frame
// with their shadows, about 42 ms of a 118 ms frame. A debugging aid,
// so it is off (0) unless something needs checking (1).
VAR showraw = 0
// Angle change that counts as movement, degrees. Smaller changes do not
// redraw the screen: the picture already shows what the sensor says.
VAR move = 0.15
// Dark band further down the ground: a depth cue that costs a whole
// extra screen fill. 1 = on, 0 = flat ground (slightly faster).
VAR depth = 1
// Pitch (nose) bar on the right edge:
//   nbx0, nbx1 - left and right edge of the track, px
//   nby0, nby1 - top and bottom of the track, px
//   nbpd       - pixels per degree
//   nbsg       - direction: flip to -1 if the bar goes the wrong way
//                when the nose lifts
//   nbmax      - angle at which the bar is full, degrees
VAR nbx0 = 438
VAR nbx1 = 460
VAR nby0 = 110
VAR nby1 = 370
VAR nbpd = 2.8
VAR nbsg = 1
VAR nbmax = 45
// IMU update period, ms (the self-test uses 200; a level needs faster)
CONST IMUMS = 20
// Average character width as a share of the font size (for placing the
// degree mark after the number): width of one character = size * CW
CONST CW = 0.6
// Font sizes, px: small labels, medium banners, big number, scale labels
CONST FS_S = 20
CONST FS_M = 28
CONST FS_B = 48
CONST FS_L = 16
// ---------------- colours (0xRRGGBB) ----------------
// sky: dark top, lighter band near the horizon
CONST SKY1 = 0x0A2E73
CONST SKY2 = 0x1E66C8
// ground: brown near the horizon, darker further down
CONST GND1 = 0x7A4A1E
CONST GND2 = 0x4A2A10
CONST WHITE = 0xFFFFFF
// green = level, yellow = level mark, arrows, pitch bar
CONST GREEN = 0x3CFF6A
CONST YEL = 0xFFC400
CONST BLACK = 0x000000
// screen centre, px
CONST CX = 240
CONST CY = 240
// ---------------- working variables ----------------
// QX, QY      - the 4 screen corners, used for clipping
// PX, PY      - corners of the clipped polygon (up to 6)
// HPX, HPY    - the 2 points where the horizon crosses the screen edge
VAR QX[4], QY[4], PX[6], PY[6], HPX[2], HPY[2]
// TKA, TKL    - roll scale ticks: angle from "up" and tick length
VAR TKA[11], TKL[11]
// qx, qy, qz  - acceleration with the axis signs applied
// rr0, pp0    - raw roll / pitch, later the angles counted from zero
// roll, pitch - smoothed angles, degrees
// offr, offp  - zero set by the last tap
VAR qx, qy, qz, rr0, pp0, roll, pitch, offr, offp
// ra          - horizon angle on the screen, radians
// nx, ny      - horizon "up" normal; dx, dy - horizon direction
// hx, hy      - horizon centre point; lx, ly - line used for clipping
// col         - current colour; savh - 1 = keep the horizon points
VAR ra, nx, ny, dx, dy, hx, hy, lx, ly, sg, col, savh
// np, nh      - corners in the clipped polygon / horizon points found
// c, c2       - current and next screen corner
// x1..y2      - edge being clipped; s1, s2 - side of the line of its ends
// tt          - where the edge crosses the line (0..1)
// k, w        - loop counter, tick width
// ex0..ey1    - line / triangle end points
VAR np, nh, c, c2, x1, y1, x2, y2, s1, s2, tt, k, w, ex0, ey0, ex1, ey1
// tx, ty      - text position; a, ca, sa - tick angle and its cos / sin
// r1, r2      - outer / inner radius of a tick
// lvl         - 1 = level; hcol - horizon colour
// tcal        - time of the last tap (for the ZERO SET banner)
// first       - 1 until the first sensor reading
// tch, held   - touch now / touch on the previous pass (tap detection)
VAR tx, ty, a, ca, sa, r1, r2, lvl, hcol, tcal, first, tch, held
// lastr, lastp, lastl - roll, pitch and level of the last drawn frame
// nby, bh, bcol       - pitch bar tick position, bar height, bar colour
// redraw              - 1 = the screen must be redrawn this pass
VAR lastr, lastp, lastl, nby, bh, bcol, redraw
// dtm, tprv, smk - filter time step, previous time, filter share
VAR dtm, tprv, smk
// v$ - text to draw; d$ - direction word / sign
VAR v$, d$
// ---------------- screen corners for clipping ----------------
// listed round the screen: top-left, top-right, bottom-right, bottom-left
QX[0] = 0
QY[0] = 0
QX[1] = 479
QY[1] = 0
QX[2] = 479
QY[2] = 479
QX[3] = 0
QY[3] = 479
// ---------------- roll scale ticks: angle from "up", tick length ----------
// 0 degrees (longest), then 10, 20, 30, 45, 60 to each side;
// 30 and 60 are longer, as on a real attitude indicator
TKA[0] = 0
TKL[0] = 22
TKA[1] = 10
TKL[1] = 12
TKA[2] = -10
TKL[2] = 12
TKA[3] = 20
TKL[3] = 12
TKA[4] = -20
TKL[4] = 12
TKA[5] = 30
TKL[5] = 20
TKA[6] = -30
TKL[6] = 20
TKA[7] = 45
TKL[7] = 14
TKA[8] = -45
TKL[8] = 14
TKA[9] = 60
TKL[9] = 20
TKA[10] = -60
TKL[10] = 20
// start the IMU: background reading of the 6 variables every IMUMS ms,
// chip at I2C address 0x6B
PRINT "--- IMU QMI8658 ---"
QMI8658_INIT(ax, ay, az, gyx, gyy, gyz, IMUMS, 0x6B)
// give the sensor time to deliver its first readings
PAUSE 200
// no zero offset yet, first reading still to come, no touch, no tap
offr = 0
offp = 0
first = 1
held = 0
tcal = 0
// ESP-NOW on Wi-Fi channel 0: both boards must sit on the same router.
// Without a router give both the same channel, e.g. NOW_INIT(6).
NOW_INIT(0)
// X, Y, Z - servo duty deltas sent to the second board, -DMAX..+DMAX.
// The receiver gets them under the same names.
VAR X = 0
VAR Y = 0
VAR Z = 0
// max servo deviation, duty units, each side
CONST DMAX = 3
// accumulated gyro angle (degrees) that gives the full deviation DMAX
// (bigger = calmer servo, smaller = more sensitive)
CONST AMAX = 45
// gyro dead band, deg/s: smaller readings are treated as 0 so that the
// sum does not creep while the board stands still
CONST GDB = 0.5
// angX/Y/Z - sum of the gyro over time = turned angle, degrees
// bX/Y/Z   - gyro zero offset measured at start (board must be still)
VAR angX = 0
VAR angY = 0
VAR angZ = 0
VAR bX = 0
VAR bY = 0
VAR bZ = 0
// tg  - time of the previous gyro sum, ms
// dtg - time step of the gyro sum, s
// gi  - loop counter of the zero measurement
// vg  - gyro speed of the current axis minus its offset
VAR tg = 0
VAR dtg = 0
VAR gi = 0
VAR vg = 0
// ---- gyro zero: average 50 readings over 1 s, board must be still ----
// A still gyro should read 0, but every chip has a small offset. Summed
// over time even 0.3 deg/s becomes 18 degrees a minute, so the offset
// is measured here and subtracted from every reading later.
PRINT "gyro zero - keep the board still"
FOR gi = 1 TO 50
    bX = bX + gyx
    bY = bY + gyy
    bZ = bZ + gyz
    PAUSE 20
NEXT
bX = bX / 50
bY = bY / 50
bZ = bZ / 50
PRINT "gyro zero " + bX.2 + " " + bY.2 + " " + bZ.2
// the gyro sum starts counting time from now
tg = MILLIS
// how often the deltas are sent, ms
CONST SENDMS = 100
// =========================== main loop ================================
WHILE 1
    // ---- sum the gyro over time: angle = sum of (speed * time) ----
    // done on every pass, the deltas are only sent every SENDMS ms
    GOSUB gyro_sum
    // ---- servo deltas for the second board ----
    // summed angle -> duty-cycle delta: AMAX degrees give DMAX, the
    // result is clamped to -DMAX..+DMAX.
    // The receiver only adds it to its centre: PWM(1, 50, 9 + X) etc.
    IF MILLIS - girT >= SENDMS THEN
        girT = MILLIS
        X = MIN(DMAX, MAX(0 - DMAX, angX * DMAX / AMAX))
        Y = MIN(DMAX, MAX(0 - DMAX, angY * DMAX / AMAX))
        Z = MIN(DMAX, MAX(0 - DMAX, angZ * DMAX / AMAX))
        // NOW_SEND carries one variable at a time, under its own name
        NOW_SEND(X)
        NOW_SEND(Y)
        NOW_SEND(Z)
    ENDIF
    // ---- level: new smoothed roll / pitch and the LEVEL flag ----
    GOSUB read_angles
    // ---- tap on the screen = new zero ----
    GOSUB check_touch
    // Redraw when the board moved, when the LEVEL state flipped, or
    // while the ZERO SET banner is on screen; otherwise the picture
    // already shows what the sensor says and the loop stays fast for
    // the gyro sum and the radio.
    redraw = 0
    IF ABS(roll - lastr) >= move THEN redraw = 1
    IF ABS(pitch - lastp) >= move THEN redraw = 1
    IF lvl <> lastl THEN redraw = 1
    IF tcal > 0 AND MILLIS - tcal < 1700 THEN redraw = 1
    IF redraw = 1 THEN
        // remember what this frame shows
        lastr = roll
        lastp = pitch
        lastl = lvl
        GOSUB draw_frame
        // push the finished frame to the panel
        DISPLAY_UPDATE()
    ENDIF
WEND
END
// ---------------------------------------------------------------------
//  Accelerometer -> roll and pitch in degrees, smoothed. ax, ay, az are
//  kept up to date by QMI8658_INIT; here they only get the axis signs.
//  Output: roll, pitch (smoothed), rr0, pp0 (counted from the zero),
//  lvl (1 = level).
// ---------------------------------------------------------------------

read_angles:
    // acceleration with the axis signs applied
    qx = ax * AXS
    qy = ay * AYS
    qz = az * AZS
    // On this board the IMU sits turned by 90 degrees: with the board
    // upright, gravity lies along X, not Y. So X is the "down" axis and
    // Y is the sideways one. If it reads 180 instead of 0, set AXS = -1;
    // if left and right are swapped, set AYS = -1.
    // 57.2958 = degrees in one radian
    rr0 = ATAN2(qy, qx) * 57.2958
    pp0 = ATAN2(qz, SQRT(qx * qx + qy * qy)) * 57.2958
    // the very first reading is taken as is, after that low-pass
    IF first = 1 THEN
        roll = rr0
        pitch = pp0
        tprv = MILLIS
        first = 0
    ENDIF
    // Step by elapsed time, not by pass: EXP(-dt / SMO) is the share of
    // the old value that survives dt seconds. A pause of a whole second
    // (a frame that took long) must not jump the filter past the
    // reading, so dt is capped.
    dtm = (MILLIS - tprv) / 1000
    tprv = MILLIS
    IF dtm > 0.3 THEN dtm = 0.3
    // Only the accelerometer decides the angle here; the gyro's job is
    // the servo deltas over ESP-NOW and it does not touch the picture.
    smk = 1 - EXP(0 - dtm / SMO)
    roll = roll + (rr0 - roll) * smk
    pitch = pitch + (pp0 - pitch) * smk
    // Angles counted from the zero, and the level flag. LEVEL means both
    // angles are level: a board straight in roll but tipped forward is
    // not a level board.
    rr0 = roll - offr
    pp0 = pitch - offp
    lvl = 0
    IF ABS(rr0) < LVLTHR AND ABS(pp0) < LVLTHR THEN lvl = 1
RETURN

// ---------------------------------------------------------------------
//  Gyro sum. The gyro gives rotation speed (deg/s); speed * time since
//  the last pass = degrees turned, added to the total. The start offset
//  is taken away first, small noise inside GDB is ignored. The total is
//  held inside -AMAX..+AMAX: past the servo limit it does not keep
//  growing, so turning back moves the servo at once.
//  Output: angX, angY, angZ, degrees.
// ---------------------------------------------------------------------

gyro_sum:
    // time since the last pass, s; capped so one slow pass (a long
    // frame) cannot add a huge jump
    dtg = (MILLIS - tg) / 1000
    tg = MILLIS
    IF dtg > 0.2 THEN dtg = 0.2
    // X axis: speed minus offset, dead band, add, clamp
    vg = gyx - bX
    IF ABS(vg) < GDB THEN vg = 0
    angX = MIN(AMAX, MAX(0 - AMAX, angX + vg * dtg))
    // Y axis
    vg = gyy - bY
    IF ABS(vg) < GDB THEN vg = 0
    angY = MIN(AMAX, MAX(0 - AMAX, angY + vg * dtg))
    // Z axis
    vg = gyz - bZ
    IF ABS(vg) < GDB THEN vg = 0
    angZ = MIN(AMAX, MAX(0 - AMAX, angZ + vg * dtg))
RETURN

// ---------------------------------------------------------------------
//  Tap (press, not hold) -> the current position becomes zero.
//  Only the moment the finger touches counts: held remembers the touch
//  of the previous pass, so holding the finger does not repeat it.
// ---------------------------------------------------------------------

check_touch:
    tch = TOUCH_PRESSED
    IF tch = 1 AND held = 0 THEN
        // level: the present roll and pitch become 0
        offr = roll
        offp = pitch
        // the gyro sums start again from 0: servos back to the centre
        angX = 0
        angY = 0
        angZ = 0
        // start time of the ZERO SET banner
        tcal = MILLIS
        PRINT "zero set"
    ENDIF
    held = tch
RETURN

// ---------------------------------------------------------------------
//  One frame: sky, ground, horizon line, roll scale, pitch bar, level
//  mark and text, drawn back to front.
// ---------------------------------------------------------------------

draw_frame:
    // rr0, pp0 and lvl are ready from read_angles
    // horizon direction d and its "up" normal n on the screen.
    // The horizon turns against the board: angle = -roll.
    ra = 0 - rr0 / 57.2958
    dx = COS(ra)
    dy = SIN(ra)
    nx = SIN(ra)
    ny = 0 - COS(ra)
    // The horizon rides along its own normal by the pitch angle: lean
    // the board forward and it goes down, back and it goes up. PSG
    // picks which way, PPD how far per degree.
    hx = CX + nx * pp0 * PPD * PSG
    hy = CY + ny * pp0 * PPD * PSG
    // ---- sky: dark everywhere, lighter band near the horizon ----
    // the whole screen gets the dark sky, then everything below a line
    // 110 px above the horizon gets the lighter sky
    CANVAS_COLOR(SKY1)
    lx = hx + nx * 110
    ly = hy + ny * 110
    col = SKY2
    savh = 0
    GOSUB clip_fill
    // ---- ground: below the horizon, darker band further down ----
    // this fill also keeps the two horizon points (savh = 1)
    lx = hx
    ly = hy
    col = GND1
    savh = 1
    GOSUB clip_fill
    // darker ground from 130 px below the horizon (optional)
    IF depth = 1 THEN
        lx = hx - nx * 130
        ly = hy - ny * 130
        col = GND2
        savh = 0
        GOSUB clip_fill
    ENDIF
    // ---- horizon line, 3 px thick: three parallel lines ----
    // white normally, green when level; drawn only if the horizon is on
    // the screen (two crossing points found)
    hcol = WHITE
    IF lvl = 1 THEN hcol = GREEN
    IF nh = 2 THEN
        FOR k = -1 TO 1
            // shift each line by k px along the normal, kept on screen
            ex0 = MIN(479, MAX(0, HPX[0] + nx * k))
            ey0 = MIN(479, MAX(0, HPY[0] + ny * k))
            ex1 = MIN(479, MAX(0, HPX[1] + nx * k))
            ey1 = MIN(479, MAX(0, HPY[1] + ny * k))
            DISPLAY_LINE(ex0, ey0, ex1, ey1, hcol)
        NEXT
    ENDIF
    // the rest of the picture on top
    GOSUB draw_roll_scale
    GOSUB draw_nose_bar
    GOSUB draw_mark
    GOSUB draw_text
RETURN

// ---------------------------------------------------------------------
//  Fill the part of the screen below the line through (lx, ly) with
//  direction d (below = against the normal n) with colour col.
//  Sutherland-Hodgman: walk round the 4 screen corners, keep the corners
//  below the line and add the point where an edge crosses the line.
//  The result (np corners) is filled as a fan of triangles.
//  savh = 1 -> also keep the two crossing points (the visible horizon).
// ---------------------------------------------------------------------

clip_fill:
    np = 0
    IF savh = 1 THEN nh = 0
    FOR c = 0 TO 3
        // edge from corner c to the next corner c2
        c2 = (c + 1) % 4
        x1 = QX[c]
        y1 = QY[c]
        x2 = QX[c2]
        y2 = QY[c2]
        // side of the line for both ends: negative = below the line
        s1 = (x1 - lx) * nx + (y1 - ly) * ny
        s2 = (x2 - lx) * nx + (y2 - ly) * ny
        // the start corner is below the line: keep it
        IF s1 < 0 THEN
            PX[np] = x1
            PY[np] = y1
            np = np + 1
        ENDIF
        // the edge crosses the line: add the crossing point
        IF (s1 < 0 AND s2 >= 0) OR (s1 >= 0 AND s2 < 0) THEN
            // tt = share of the edge where the side value becomes 0
            tt = s1 / (s1 - s2)
            PX[np] = x1 + (x2 - x1) * tt
            PY[np] = y1 + (y2 - y1) * tt
            // keep the crossing points for drawing the horizon line
            IF savh = 1 AND nh < 2 THEN
                HPX[nh] = PX[np]
                HPY[nh] = PY[np]
                nh = nh + 1
            ENDIF
            np = np + 1
        ENDIF
    NEXT
    // fill: triangles from corner 0 to every pair of next corners
    IF np >= 3 THEN
        FOR k = 1 TO np - 2
            DISPLAY_FILL_TRIANGLE(PX[0], PY[0], PX[k], PY[k], PX[k + 1], PY[k + 1], col)
        NEXT
    ENDIF
RETURN

// ---------------------------------------------------------------------
//  Roll scale: fixed ticks round the top of the screen (0, 10, 20, 30,
//  45, 60 degrees to each side) and a triangle pointer that always
//  points to the real "up" (the normal n). Pointer on the 0 tick = level.
// ---------------------------------------------------------------------

draw_roll_scale:
    // outer radius of the ticks, px
    r1 = 205
    FOR k = 0 TO 10
        // tick angle measured from straight up, radians
        a = TKA[k] / 57.2958
        sa = SIN(a)
        ca = COS(a)
        // inner end of the tick
        r2 = r1 - TKL[k]
        DISPLAY_LINE(CX + sa * r1, CY - ca * r1, CX + sa * r2, CY - ca * r2, WHITE)
    NEXT
    // pointer: tip towards the scale at 178 px, base 18 px lower
    // and 20 px wide, along the horizon direction
    ex0 = CX + nx * 178
    ey0 = CY + ny * 178
    tx = CX + nx * 160
    ty = CY + ny * 160
    DISPLAY_FILL_TRIANGLE(ex0, ey0, tx + dx * 10, ty + dy * 10, tx - dx * 10, ty - dy * 10, hcol)
RETURN

// ---------------------------------------------------------------------
//  Fixed level mark in the centre: two yellow wings with short down
//  ticks and a centre dot, all with a black outline so they read on
//  both sky and ground. It does not move: the horizon moves behind it.
// ---------------------------------------------------------------------

draw_mark:
    // black outline: 5 px tall wings
    FOR k = -2 TO 2
        DISPLAY_LINE(150, CY + k, 210, CY + k, BLACK)
        DISPLAY_LINE(270, CY + k, 330, CY + k, BLACK)
    NEXT
    // yellow wings, 3 px tall, and the down ticks at their inner ends
    FOR k = -1 TO 1
        DISPLAY_LINE(152, CY + k, 208, CY + k, YEL)
        DISPLAY_LINE(272, CY + k, 328, CY + k, YEL)
        DISPLAY_LINE(208 + k, CY, 208 + k, CY + 12, YEL)
        DISPLAY_LINE(272 + k, CY, 272 + k, CY + 12, YEL)
    NEXT
    // centre dot with an outline
    DISPLAY_FILL_CIRCLE(CX, CY, 7, BLACK)
    DISPLAY_FILL_CIRCLE(CX, CY, 5, YEL)
RETURN

// ---------------------------------------------------------------------
//  Text: ROLL in degrees with direction, LEVEL banner,
//  "ZERO SET" for 1.5 s after a tap. Every text has a black shadow so
//  it reads on both sky and ground.
// ---------------------------------------------------------------------

draw_text:
    // ---- roll, bottom centre: label, big number, direction ----
    tx = 175
    ty = 348
    v$ = "ROLL"
    col = WHITE
    GOSUB txt_small
    // angle without sign, one decimal; the sign is shown as a word
    s1 = ROUND(ABS(rr0) * 10) / 10
    v$ = "" + s1.1
    ty = 372
    GOSUB txt_big
    // direction word
    d$ = "LEFT"
    IF rr0 > 0 THEN d$ = "RIGHT"
    IF ABS(rr0) < LVLTHR THEN d$ = "LEVEL"
    v$ = d$
    ty = 428
    GOSUB txt_small
    // arrow next to the direction: right of it for RIGHT, left for LEFT
    IF ABS(rr0) >= LVLTHR THEN
        IF rr0 > 0 THEN
            DISPLAY_FILL_TRIANGLE(300, 426, 300, 446, 318, 436, YEL)
        ELSE
            DISPLAY_FILL_TRIANGLE(158, 426, 158, 446, 140, 436, YEL)
        ENDIF
    ENDIF
    // ---- LEVEL banner under the roll scale ----
    IF lvl = 1 THEN
        tx = 195
        ty = 70
        v$ = "LEVEL"
        col = GREEN
        GOSUB txt_mid
    ENDIF
    // ---- raw IMU values in the top corners (debugging, see showraw) ----
    IF showraw = 1 THEN GOSUB draw_acc
    // ---- zero set message for 1.5 s after a tap ----
    IF tcal > 0 AND MILLIS - tcal < 1500 THEN
        tx = 168
        ty = 300
        v$ = "ZERO SET"
        col = YEL
        GOSUB txt_mid
    ENDIF
RETURN

// ---------------------------------------------------------------------
//  Raw accelerometer values ax, ay, az (in g, two decimals), top left,
//  and gyro values gyx, gyy, gyz (deg/s, one decimal), top right.
//  No colon in the text: a colon followed by a space froze the parser.
// ---------------------------------------------------------------------

draw_acc:
    col = WHITE
    // accelerometer, left column
    tx = 12
    ty = 12
    v$ = "AX " + ax.2
    GOSUB txt_small
    ty = 36
    v$ = "AY " + ay.2
    GOSUB txt_small
    ty = 60
    v$ = "AZ " + az.2
    GOSUB txt_small
    // gyro, right column
    tx = 350
    ty = 12
    v$ = "GX " + gyx.1
    GOSUB txt_small
    ty = 36
    v$ = "GY " + gyy.1
    GOSUB txt_small
    ty = 60
    v$ = "GZ " + gyz.1
    GOSUB txt_small
RETURN

// ---------------------------------------------------------------------
//  Text helpers: shadow first (black, offset), then the text itself.
//  Input: tx, ty - position; v$ - text; col - colour.
// ---------------------------------------------------------------------
// small text (labels)

txt_small:
    DISPLAY_TEXT(tx + 2, ty + 2, v$, BLACK, FS_S)
    DISPLAY_TEXT(tx, ty, v$, col, FS_S)
RETURN

// medium text (banners)

txt_mid:
    DISPLAY_TEXT(tx + 2, ty + 2, v$, BLACK, FS_M)
    DISPLAY_TEXT(tx, ty, v$, col, FS_M)
RETURN

// ---------------------------------------------------------------------
//  Big number + a drawn degree mark right after it.
//  The number is always shown with one decimal (s1.1), so its length is
//  1..3 digits before the point + 2 characters for ".5". There is no
//  LEN, so the length k is counted from the value s1 itself (0..180).
//  The degree mark is a white ring: a white dot with a black centre.
// ---------------------------------------------------------------------

txt_big:
    DISPLAY_TEXT(tx + 3, ty + 3, v$, BLACK, FS_B)
    DISPLAY_TEXT(tx, ty, v$, WHITE, FS_B)
    // number of characters in the number
    k = 3
    IF FLOOR(s1) >= 10 THEN k = 4
    IF FLOOR(s1) >= 100 THEN k = 5
    // degree mark just after the last character, near the top
    ex0 = tx + k * CW * FS_B + 8
    DISPLAY_FILL_CIRCLE(ex0, ty + FS_B * 0.15, 6, WHITE)
    DISPLAY_FILL_CIRCLE(ex0, ty + FS_B * 0.15, 3, BLACK)
RETURN

// ---------------------------------------------------------------------
//  Nose up / down as a bar on the right edge. The track is fixed, the
//  bar grows from the middle: up when the nose lifts, down when it
//  drops, nbpd pixels per degree and clamped at nbmax so a board stood
//  on its end does not paint the whole edge. Green while level.
//  Drawn with three rectangles and five ticks, much cheaper than text.
// ---------------------------------------------------------------------

draw_nose_bar:
    // track: black bed with a thin white frame, so it reads over sky
    // and ground
    DISPLAY_FILL_RECT(nbx0 - 2, nby0 - 2, nbx1 - nbx0 + 4, nby1 - nby0 + 4, BLACK)
    DISPLAY_RECT(nbx0 - 2, nby0 - 2, nbx1 - nbx0 + 4, nby1 - nby0 + 4, WHITE)
    // ticks every 15 degrees (-30..+30), the middle one (0) across the
    // whole width, the others 7 px long
    FOR k = -2 TO 2
        nby = CY - k * 15 * nbpd
        w = 7
        IF k = 0 THEN w = nbx1 - nbx0
        DISPLAY_LINE(nbx0, nby, nbx0 + w, nby, WHITE)
    NEXT
    // the bar itself: from the middle to the angle, clamped to +-nbmax
    a = MIN(nbmax, MAX(0 - nbmax, pp0 * nbsg))
    bh = a * nbpd
    bcol = YEL
    IF lvl = 1 THEN bcol = GREEN
    // positive = grows up from the middle, negative = grows down
    IF bh >= 0 THEN
        DISPLAY_FILL_RECT(nbx0 + 4, CY - bh, nbx1 - nbx0 - 8, bh + 1, bcol)
    ELSE
        DISPLAY_FILL_RECT(nbx0 + 4, CY, nbx1 - nbx0 - 8, 0 - bh + 1, bcol)
    ENDIF
    // the angle in degrees under the track, with its sign, one decimal
    s2 = ROUND(ABS(pp0) * 10) / 10
    d$ = "-"
    IF pp0 * nbsg >= 0 THEN d$ = "+"
    v$ = d$ + s2.1
    tx = nbx0 - 30
    ty = nby1 + 10
    col = WHITE
    IF lvl = 1 THEN col = GREEN
    GOSUB txt_small
RETURN

Script for ESP32-C3 (Receiver):

R1 BASIC
// =====================================================================
//  SERVO RECEIVER - three servos driven over ESP-NOW
//
//  The other board (electronic level + gyro) sends X, Y, Z: servo duty
//  deltas -3..+3 worked out from how far it has been turned around each
//  axis. This board adds each delta to its servo's centre position and
//  moves the servos smoothly towards the new values, so they glide
//  between the 10 updates per second instead of jumping in steps.
//
//  Axis -> servo wiring (crossed on purpose to match the mechanics):
//    Z axis -> channel 1 (PWM1_CH1, GPIO 2)
//    Y axis -> channel 2 (PWM1_CH2, GPIO 3)
//    X axis -> channel 3 (PWM2_CH1, GPIO 4)
//  The deltas are subtracted, which reverses each servo's direction.
//  If one servo turns the wrong way, change its "-" to "+" below.
// =====================================================================

CONFIG
// servo signal pins: PWM block 1 channels 1 and 2, PWM block 2 channel 1
PWM1_CH1 2
PWM1_CH2 3
PWM2_CH1 4
END_CONFIG

// X, Y, Z arrive over ESP-NOW from the other board (duty deltas -3..+3).
// The sender's NOW_SEND(X) lands in the variable of the same name here,
// so these names must match the sender's.
VAR X = 0
VAR Y = 0
VAR Z = 0

// Servo centre (duty, %) for each PWM channel - the position a servo
// holds when its delta is 0. Note: the names follow the channel, not the
// axis that drives it:
//   CX - channel 1 (driven by Z)
//   CY - channel 2 (driven by Y)
//   CZ - channel 3 (driven by X)
// At 50 Hz a duty of 5..10 % is a 1..2 ms pulse, the usual servo range;
// keep centre +- 3 inside what your servos accept.
CONST CX = 9
CONST CY = 9
CONST CZ = 9

// smoothing time, s: how fast the servo catches up with new data.
// smaller = quicker, bigger = smoother. 0.08..0.15 is "smooth but quick"
CONST TAU = 0.1

// smoothed values that actually go to the servos (SX follows X, etc.)
VAR SX = 0
VAR SY = 0
VAR SZ = 0
// t0 - time of the previous pass, ms; dt - time step, s;
// k  - share of the remaining distance covered this pass
VAR t0 = 0
VAR dt = 0
VAR k = 0

// ESP-NOW receiver on Wi-Fi channel 0: must be the same channel as the
// sender (both on one router, or the same fixed channel, e.g. 6)
NOW_INIT(0)
t0 = MILLIS

// =========================== main loop ================================
WHILE 1
    // time since the last pass, s
    dt = (MILLIS - t0) / 1000
    t0 = MILLIS
    // capped so that one slow pass cannot make the servo jump
    IF dt > 0.1 THEN dt = 0.1

    // each pass the servo moves a share k of the way to the new value:
    // fast when the difference is big, slows down softly near the target.
    // The share depends on the real time step, so the speed is the same
    // however fast the loop runs.
    k = 1 - EXP(0 - dt / TAU)
    SX = SX + (X - SX) * k
    SY = SY + (Y - SY) * k
    SZ = SZ + (Z - SZ) * k

    // 50 Hz servo signal: centre minus the smoothed delta
    // (see the axis -> channel wiring at the top)
    PWM(1, 50, CX - SZ)
    PWM(2, 50, CY - SY)
    PWM(3, 50, CZ - SX)

    // ~50 updates per second: smooth for the eye, light for the CPU
    PAUSE 20
WEND

photo_2026-11-30 20.26.39

1
0 replies

Sign in to reply