Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F103, STM32F407, STM32G031 · level intermediate · 9 min read
Open in the interactive handbook

76н. Bresenham's algorithm: lines and circles on a display and coordinated motion of two stepper motors in integers

Drawing a segment on a 128×64 display means choosing which dots to light. The line equation gives fractional coordinates, a division and rounding at every dot; on a Cortex-M0 without hardware division or floating point that is slow. Bresenham's algorithm does the same with nothing but integer additions and comparisons — and the same idea drives two stepper motors of a machine or a plotter along a straight line, when one must make 1000 steps and the other 370 in the same time.

Grounds: alg.c was built with gcc 12.2.0 on a computer (stm-sys:1) and run by host.c: 380 lines from the centre of the frame to every point of its edge, circles of radius 1 to 31, two-axis interpolation on five paths; the answer is checked against the exact line and the exact radius in floating point. The same alg.c was built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0 — sizes and frames.

Terms used in the documentation

Term Meaning
Bresenham's line algorithm drawing a segment with integer error tracking
midpoint circle algorithm drawing a circle by the sign at the midpoint
octant one eighth of the plane by signs and slope
decision variable, error term the accumulated error whose sign picks the step
eight-way symmetry eight reflections of one eighth of a circle
digital differential analyzer (DDA) a digital integrator: a step by accumulated sum
major axis, leading axis the axis that steps every tick
tie-breaking the choice at exactly one half: where to round a tie

In plain words. Walk along the long axis one dot per step and keep in mind how far behind you are on the short one. As soon as the lag passes half a dot — step along the short axis too. No fractions: the "half" is written so that everything stays integer.


76н.1 The task: dots instead of a line

A segment from (63, 31) to (127, 0) on a display is 65 dots: one per column, because the path is longer in x. For each column we need the row nearest to the exact line. The naive way is y = y0 + k·(x − x0) with a fractional k and rounding at every dot. Bresenham notes that from dot to dot the exact y changes by the same fraction, and tracks only when the accumulated fraction crosses one half.

76н.2 An error instead of a fraction

Multiply everything by 2·dx and the fraction becomes an integer: instead of "k" — dy, instead of "one half" — dx. The accumulated error err holds both axes at once: a step in x adds dy (negative) to it, a step in y adds dx. The sign of the doubled error decides which axis to step; on a diagonal both are stepped.

76н.3 A line in all eight octants

The form with a negative dy and the direction signs sx, sy works for any slope and direction without eight separate branches:

uint32_t line(int x0, int y0, int x1, int y1)
{
    int dx = x1 > x0 ? x1 - x0 : x0 - x1, sx = x0 < x1 ? 1 : -1;
    int dy = y1 > y0 ? y0 - y1 : y1 - y0, sy = y0 < y1 ? 1 : -1; /* dy <= 0 */
    int err = dx + dy;
    uint32_t n = 0;
    for (;;) {
        fb_set(x0, y0);
        n++;
        if (x0 == x1 && y0 == y1)
            break;
        int e2 = 2 * err;
        if (e2 >= dy) { /* шаг по x */
            err += dy;
            x0 += sx;
        }
        if (e2 <= dx) { /* шаг по y */
            err += dx;
            y0 += sy;
        }
    }
    return n;
}

The loop ends by comparing with the end point, not by a counter, so the end is always drawn.

Bresenham's line: the accumulated error and steps along two axes

76н.4 Experiment: 380 lines from the centre of the frame

Lines were drawn from (63, 31) to all 380 points of the edge of a 128×64 frame. For each one it was checked that:

76н.5 A line drawn backwards is a different line

The same check with the ends swapped gave a different set of dots for 157 lines out of 380. The reason is ties: at exactly one half the algorithm always picks one side by the sign, and on the reverse pass the signs change. Both lines are correct but different. If you erase a line by drawing it black in the reverse direction, dots will remain on the screen; erase with the same ends in the same order — or order the ends (for example, always left to right) before the call.

76н.6 A circle by the midpoint

A circle has eight-way symmetry, so one eighth is computed — from (r, 0) to the diagonal — and every dot is drawn eight times:

    int x = r, y = 0, d = 1 - r;
    uint32_t n = 0;
    while (x >= y) {
        fb_set(cx + x, cy + y); fb_set(cx + y, cy + x);
        fb_set(cx - y, cy + x); fb_set(cx - x, cy + y);
        fb_set(cx - x, cy - y); fb_set(cx - y, cy - x);
        fb_set(cx + y, cy - x); fb_set(cx + x, cy - y);
        n++;
        y++;
        if (d < 0) {
            d += 2 * y + 1;
        } else {
            x--;
            d += 2 * (y - x) + 1;
        }
    }

d is the sign of x² + y² − r² at the midpoint between two candidates, updated by increments without multiplications. Experiment:

Radius steps per eighth dots on the circle largest deviation from the radius
1 1 4 0.000
5 4 28 0.385
10 8 56 0.440
20 15 112 0.396
31 23 176 0.406

Over all 31 radii the largest deviation of a dot from the exact radius is 0.485; none went half a dot off. Radius 1 gives a cross of four dots: one eighth has just one step, and the diagonal dots lie 0.41 beyond the radius and are not chosen.

76н.7 🔧 An SSD1306 frame: a dot in a page

The frame buffer of an SSD1306 display (section 22м) is organised in pages: 8 pages of 8 rows, a byte is a column of eight dots, the least significant bit at the top. Dot (x, y) is bit y & 7 in byte (y >> 3) · 128 + x:

static inline void fb_set(int x, int y)
{
    if ((unsigned)x < FB_W && (unsigned)y < FB_H)
        fb[(y >> 3) * FB_W + x] |= (uint8_t)(1u << (y & 7));
}

The check (unsigned)x < FB_W cuts off both negative and too large coordinates with one comparison: a negative number cast to unsigned is huge. So lines and circles may be drawn partly beyond the edge — the extra dots simply do not get into the buffer.

76н.8 🔧 Two stepper motors: interpolation by Bresenham

A machine has to go from (0, 0) to (1000, 370) steps in a straight line. The axis with more steps is the leading one, it steps every timer tick; the second steps when the accumulated error becomes negative:

uint32_t interp_tick(interp_t *s)
{
    if (!s->left)
        return 0;
    s->left--;
    uint32_t m;
    if (s->dx >= s->dy) {
        m = 1;
        s->err -= s->dy;
        if (s->err < 0) {
            s->err += s->dx;
            m |= 2;
        }

The function returns a mask of steps per tick; in the timer interrupt handler (section 57) STEP pulses are issued by the bits of the mask. Experiment:

Path, steps X × Y ticks X steps Y steps largest deviation, steps
1000 × 370 1000 1000 370 0.500
370 × 1000 1000 370 1000 0.500
1000 × 1000 1000 1000 1000 0.000
5 × 0 5 5 0 0.000
0 × 0 0 0 0 0.000

The number of steps on each axis matches exactly — the motors arrive exactly at the end point, and the error does not accumulate from segment to segment. The deviation from the line along the way is at most half a step. The initial value of err is half the length of the leading axis: so the first step of the following axis happens in the middle of the first interval, not at the very start.

The speed is set by the tick rate, and set by the leading axis: the path 1000 × 370 runs at the same tick rate as 1000 × 0, so the real speed along the line is √(1 + 0.37²) times higher. For a constant speed along the path the timer period is divided by this factor once per segment.

76н.9 Sizes on Cortex-M4F and Cortex-M0

Function Cortex-M4F, bytes Cortex-M0, bytes M4F frame M0 frame
line 148 180 48 56
circle 684 652 48 56
interp_tick 52 50 0 0

No function calls anything: no division, no floating point, no library routines even on Cortex-M0. circle is the largest because of eight inlined copies of fb_set. interp_tick is 52 bytes with no stack frame: it fits right into a timer interrupt handler.

76н.10 Pitfalls

Erasing a line backwards. 157 lines out of 380 with swapped ends fall on other dots (76н.5).

A counter instead of comparing with the end. A loop "max(dx, dy) times" is easy to write one short — and the last dot is not drawn. Comparing with the end point rules that out.

Overflow of 2 * err. In a 32-bit int this starts at coordinates of about a billion — irrelevant for a display, but quite possible for a machine with microstepping and a long travel in int16_t: keep the error in 32 bits.

A circle with a negative centre or beyond the edge. Without a bounds check in fb_set dots beyond the edge write into someone else's memory; with the check (unsigned)x < FB_W they are silently dropped (76н.7).

Machine speed by the leading axis. Without a correction for length a diagonal runs √2 times faster than straight moves (76н.8).


76н.11 Summary

Check yourself

  1. What does Bresenham replace the fractional slope of a line with? - A) A table of slopes in Flash - B) An accumulated integer error whose sign picks the step - C) Single-precision floating point - D) A division at every dot
  2. Why may a line drawn backwards fall on other dots? - A) Because of ties: at exactly one half the choice depends on the direction - B) Because of error overflow - C) Because of a bug in the algorithm - D) It cannot, the line is always the same
  3. How many steps will the following axis make on a 1000 × 370 path? - A) 369 or 371 — a rounding error - B) As many as there are ticks - C) Exactly 370: the error does not accumulate - D) It depends on the timer frequency

Check yourself: answers - 1 — B. Why: Multiplying by 2·dx makes the "half" an integer, and all the arithmetic stays integer (76н.2). - 2 — A. Why: In the experiment 157 lines out of 380 with swapped ends fell differently (76н.5). - 3 — C. Why: The experiment gave exactly 1000 and 370 steps with a deviation along the way of at most half a step (76н.8).

Next: section 76о "Lossless compression on a microcontroller: RLE, deltas and LZSS with a small window for display frames and logs" — how to squeeze display frames and sensor logs with a couple of hundred bytes of code.

Open in the interactive handbook