Search code examples
clinekeil

Bresenham's line function C


I am trying to implement Bresenham's line algorithm in c, the wikipedia simplified version. My code gets stuck to an infinite loop and i cannot figure out why! (While im pretty sure it has to do with my c knowledge)

void Draw_line (unsigned int x0, unsigned int y0,unsigned int x1, unsigned int y1)
{
    unsigned int dx = abs(x1-x0);
    unsigned int dy = abs(y1-y0);
    signed short sx,sy;
    signed int err,e2;

    if (x0 < x1) {sx = 1;} else {sx = -1;}
    if (y0 < y1) {sy = 1;} else {sy = -1;}
    err = dx-dy;

    while (!(x0==x1 && y0==y1))
    {
        GLCD_PutPixel(x0, y0);
        e2 = 2*err;
        if (e2 > -dy) 
        {
            err = err - dy;
            x0 += sx;
        }
        if (e2 < dx) 
        {
            err = err + dx;
            y0 += sy;
        }
    }
}

Thanks!

EDIT: The conditional of the loop was wrong so it did not plot straight lines, changed it to the correct one.


Solution

  • Could it be that dy is an unsigned value so -dy is positive (and likely quite large) still (not negative). removing the unsigneds should fix it.