Close

How to draw a line

A project log for 1K Challange Laser

Draw the hackaday logo with a laser with less than 1K of data.

cyrille-gindreauCyrille Gindreau 12/09/2016 at 19:530 Comments

Once we had the laser at the origin, we wanted to draw a square to find the borders of the area we could project in. Using for loops, we iterated through each side.

uint16_t i;
while(1){
	for(i = 0; i <= 4095; i++){
		writeMCP492x(i, SSX);
		writeMCP492x(0, SSY);
	}
	for(i = 0; i <= 4095; i++){
		writeMCP492x(4095, SSX);
		writeMCP492x(i, SSY);
	}
	for(i = 0; i <= 4095; i++){
		writeMCP492x(4095-i, SSX);
		writeMCP492x(4095, SSY);
	}
	for(i = 0; i <= 4095; i++){
		writeMCP492x(0, SSX);
		writeMCP492x(4095-i, SSY);
	}
}

This was the result.

So far, we were only using about 310 bytes of our 1K, smooth sailing!

Now that we knew how to draw lines, we thought that the easiest way to implement the drawing of any shape would be to create a function that took in four numbers: an X and Y coordinate from where a line would start and an X and Y coordinate for where it would end. The function would then find every location between these points and move the mirrors to their corresponding location. This is what we came up with.

void drawLine(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2){

	int dx = (int)x2 - (int)x1;
	int dy = (int)y2 - (int)y1;
	int steps;
	if (abs(dx) > abs(dy)){
	    steps = abs(dx/4);
	} else{
	    steps = abs(dy/4);
	}

	float Xincrement = (float) dx / (float) steps;
	float Yincrement = (float) dy / (float) steps;

	float x = (float) x1;
	float y = (float) y1;
	int i;
	for(i = 0; i < steps; i++){
	    x = x + Xincrement;
	    y = y + Yincrement;
	    writeMCP492x( ((int)(x*16)),SSX);
	    writeMCP492x( ((int)(y*16)),SSY);
	}
}

int abs(int val){
	return (val<0 ? (-val) : val);
}

With this, we could feed it the coordinates to any kind of polygon, for example, a hexagon.

while(1){
    	 drawLine(192, 128, 160, 183);
    	 drawLine(160, 183, 96, 183);
    	 drawLine(96, 183, 64, 128);
    	 drawLine(64, 128, 95, 72);
    	 drawLine(95, 72, 160, 72);
    	 drawLine(160, 72, 192, 128);
}

After compiling, our size was almost 1500 bytes! But it worked, so we just had to figure out what was taking up all that space.

Discussions