There's a pretty cool algorithm for drawing Sierpinski triangles. Wikipedia calls it the Chaos Game. I'll explain how the algorithm works below:
Your triangle consists of 3 points:
p1
,p2
, andp3
.Choose a random current point. For simplicity you can just hardcode this.
Draw a dot at that point
Choose a random triangle point (
p1
,p2
, orp3
)Find the point in the middle of your current point and your random triangle point.
This is now your new current point.
Go to step 3
This is a pretty simple algorithm, and you'd probably expect it to just fill the triangle with random points. Amazingly, what you get instead is a Sierpinkski triangle!
I've written this algorithm before, but I've only ever drawn to an image. I thought it would be fun to control a pen plotter instead.
The pen plotter I have access to is an HP7440A. It takes ASCII commands over serial, meaning it's super easy to control. In fact, the hardest part was getting the pen into the plotter, but that was purely due to me having no idea what I'm doing. Next time will be easier!
The code lives here. It's pretty simple - generate the random points, and for each one, move the pen to the correct position, move it down and up, and repeat. There's a bit of initialization logic (initialize the plotter, select the correct pen, and set the velocity to maximum).
One extra bit of logic prevents overflowing the pen plotter's tiny input buffer. This is not a technique of my own, but the idea is to execute the "OA;" command, which doesn't return until the pen has stopped moving, and then waiting for a carriage return betore continuing execution. There's probably a smarter way using hardware flow control. I'm used to not using hardware flow control, though, because I only ever solder up my serial cables with TX, RX, and ground.
Quick blog post - just wanted to show off my cool triangles (: