OpenSCAD two types of function

I’ve been experimenting with OpenSCAD for some time and was building some plates to attach some components together. For these I needed a rounded corner rectangle with some regularly spaced holes. I knew that you could create module functions that generate objects but I’d not realised that there was a second type which acted on objects, called an operator module.

RoundedRectangle

To create my rounded rectangle I take four cylinders and act on them with the hull function. This turns them into a single object, with rounded corners. Originally I had the cylinder repeated 4 times with different translates. But after reading I realised that I could do that in code too.

module RoundedRectangle(width,length,height,radius)
{
if (radius > width/2 || radius > length/2) {
echo("Warning radius too large");
}
hull() {
ForRectangle(width/2-radius,length/2-radius)
{
cylinder(h=height,r=radius,centre=true);
}
}
}

To produce my four cylinders I’ve created an operator module which repeats any children of the function over a rectangular array. Looking back the the previous function we can see that a cylinder is passed in as the child object. So these operator modules are good for repeating or arranging items.

module ForRectangle(offsetx,offsety) {
for(i = [[-1,-1], [1,-1], [1,1], [-1,1]])
{
translate([offsetx*i[0],offsety*i[1],0])
children();
}
}

This function is used again in my board object module, to create 4 mounting holes.

module Board()
{
difference() {
RoundedRectangle(20,28,2,2);
translate([0,0,-1])
ForRectangle(7,11)
{
cylinder(h=7,d=2+(gap/2),$fn=200,centre=true);
}
}
}

Finally a call the board function. I’ve increased the smoothing parameter for the corners so we nice round corners rather than jagged ones.

$fn=200;
Board();

So by creating functions in this way you can avoid duplication in your code and make it shorter and easier to read and maintain. Having functions also gives you more chances to re-use code.

Leave a Reply

Your email address will not be published. Required fields are marked *

 characters available

Notify me of followup comments via e-mail. You can also subscribe without commenting.

overappreciative-makalu