Using Arrays in OpenSCAD

I was doing some work today on a new chassis for our environmental sensor and I discovered how to use arrays in OpenSCAD. So I thought I’d write it down for me for later.

OpenSCAD is a language designed specifically to express 3D designs. I’ve been using Python inside the FreeCAD tool, but I’m trying to learn OpenSCAD too. Let’s just say I like a challenge.

Anyhoo, today I was placing the holes for the particle sensor mounting. I know where the four holes need to go, but I don’t want to have to create four separate cylinders that describe the holes to be cut. I’m lazy. And besides, next time I do this I might want to place 100 fixing holes. So I looked into how I could put the hole coordinates in an array and just write some code that works through them and makes the holes. That way, if I need to place 100 holes I just have to add to the array.

sensorMountingHoles = [[19,0],[41,0],[0,55],[60,55]];

for (a = [ 0 : len(sensorMountingHoles) - 1 ]) 
{
      point=sensorMountingHoles[a];
      translate([point[0],point[1],0])
      {
          cylinder(r=1.4,h=10);
      }
}

This little snippet of code creates an array called SensorMountingHoles which has offsets from 0,0 of the holes that we want to make. The array is actually an array of arrays (that’s why the square brackets are nested) and each “inner” array has just two elements, the x and y coordinates of the point. The for loop works through the “outer” array and pulls out each point in turn, translates to that position and puts a cylinder there. In other words I’m going to get holes at (19,0), (41,0) and so on. If I want more holes, I just add more elements. If I use the resulting collection of cylinders in a “difference” element I can use it to cut holes.

Rather nice.