Saturday, December 3, 2011

Engine: 9 - poly-v belt

In modern cars, engine equipment like alternator or air-conditioning compressor is driven by a poly-v belt. How create such belt model in FreeCAD? You have to create a section sweep along a trajectory.

Create a new closed sketch on the XY plane. You will use it as poly-v belt section. I've fixed corner point to (0,0) but in real application x=0 should be somewhere around half of the v-groove height. Close the sketch (Sketch).

Next create a trajectory. You have to draw it on the YZ plane. Trajecory for the v-belt should be closed but for other purposes it can be open. Set vertical line to x=0 and close the sketch (Sketch001).

Sketches should be perpendicular to each other (picture above). Now you need a python script. I've borrowed one from this forum topic.

import Part, FreeCAD, math, PartGui, FreeCADGui
from FreeCAD import Base

# get the selected objects, with first selection for the trajectory and second for the section
s = FreeCADGui.Selection.getSelection()
     print "Wrong selection"

traj = Part.Wire([shape1])
section = Part.Wire([shape2])

# create Part objec in the current document

# variable makeSolid = 1 to create solid, 0 to create surfaces
makeSolid = 1
isFrenet = 1

# create a 3D shape and assigh it to the current document
Sweep = Part.Wire(traj).makePipeShell([section],makeSolid,isFrenet)
myObject.Shape = Sweep

Save it as a macro (post about macros). Select the trajectory sketch (Sketch001) and then with [Ctrl] the section sketch (Sketch). After that execute the macro.

In the picture above you can see the effect. The sweep isn't parametric (a sketch change doesn't affect to the sweep) but script can be easily modified:)

Download file.

Download RAW Video.

FreeCAD 0.12 5211 SVN

Saturday, November 19, 2011

Engine: 8 - liner blueprint (FreeCAD+LibreCAD)

(In this tutorial I'm using alternative DXF-export algoritm.)
Start Freecad and open liner model created in older tutorial.

Select the last feature (Pocket) and write in Python console:

import Part,Drawing,FreeCADGui,FreeCAD
from FreeCAD import Base
filename = "/home/adi/Pulpit/xy.dxf"
FILE = open(filename,"w")
sel = FreeCADGui.Selection.getSelection()
sel = sel[0]
shape = sel.Shape
dxf_output = Drawing.projectToDXF(shape,Base.Vector(0,0,1))

You should change filename = "/home/adi/Pulpit/xy.dxf" to your path and filename. A view will be exported to 2D DXF. Open it in LibreCAD.

In the same way export other views:

import Part,Drawing,FreeCADGui,FreeCAD
from FreeCAD import Base
filename = "/home/adi/Pulpit/yz.dxf"
FILE = open(filename,"w")
sel = FreeCADGui.Selection.getSelection()
sel = sel[0]
shape = sel.Shape
dxf_output = Drawing.projectToDXF(shape,Base.Vector(1,0,0))

import Part,Drawing,FreeCADGui,FreeCAD
from FreeCAD import Base
filename = "/home/adi/Pulpit/xz.dxf"
FILE = open(filename,"w")
sel = FreeCADGui.Selection.getSelection()
sel = sel[0]
shape = sel.Shape
dxf_output = Drawing.projectToDXF(shape,Base.Vector(0,1,0))

As you can see, direction can be specified by Base.Vector().

Now you have 3 DXF with 3 views. Select all in xy.dxf and use Edit-Copy. In the left side of the LibreCAD window you can see column menu with acive actions. Geometry is selected, so click Continue action and Snap to grid. Then select base point for a copy.
  • to back to previous active action right click somewhere,
  • in the statusbar you can see tips for active actions.
Open xz.dxf and use Edit-Paste to paste your geometry. You can flip it by mirror tool: select geometry, choose from left column: Edit-Mirror-Continue action-Snap to grid and draw horizontal mirror line. After operation return to first column menu by right-clicking. 

Now is time to adjust some layers, lines colors and widths. You can do this in Layer list (right column). Create 3 layers:

  • contour - simply rename sheet_layer layer,
  • axis
  • dimensions
Add axes. Select axis layer and from column menu: Show menu "Lines"-Line with two points-Snap to grid or Snap to middle points.

Add dimensions. Select dimensions layer and from column menu: Show menu "Dimensions". Then:

  • for linear dimensions select Horizontal Dimension or Vertical Dimension, select Snap to intersections automatically and pick two points. To set dimension line position you have to select Snap to grid or Free positioning,
  • for angles select Angular Dimension and pick two lines,
  • for diameters select Diametric Dimension and pick circle.
To add φ select Edit-Edit Text from column menu and pick a dimension.

Save the drawing with a new name. You can print it - use File-Print Preview and adjust scale and style (Toggle Black / White mode) using toolbar above preview window.

Download DXF.
Download PDF.

Download RAW Video.

FreeCAD 0.12 5150 SVN

Scripting example: Wankel block

Wankel engine shape is good to show some FreeCAD scripting capabilities. I will show Wankel block creation in two ways:
  • simple but uneditable,
  • slightly more complicated but fully real-time editable by values in the Property view fields.
Wankel shape is based on the epitrochoid. What we have to do:
  1. Create lines with start- and endpoint positions based on the epitrochoid equations.
  2. Connect lines in a one closed polyline.
  3. Upgrade polyline (wire) to face.
  4. Cut epitrochoid face from rectangle face (for simplicity rectangle is the external shape of our block).
  5. Extrude result face in a solid.

Non-parametric way:

Open a new document. Put below script in the Python interpreter line or create a macro. (Download macro)

from __future__ import division # allows floating point division from integers
import FreeCAD, FreeCADGui, Part
from FreeCAD import Base
import math
steps=360 #number of polyline segments
dang=math.radians(360/steps) #step angle
e=10 #eccentricity
r=60 #radius
ang=0 #start anle
z=0 #line z coordinate

for i in range(steps): #make many lines and connect they in wire (polyline, epitrochoid)
    if i==0: #for first line
        x1=e*math.cos(3*ang)+r*math.cos(ang) #coords for line startpoint
        x2=e*math.cos(3*ang)+r*math.cos(ang) #coords for line endpoint
    ang=ang+dang #increment angle

edge1 = Part.makeLine((-halfw,halfh,0), (halfw,halfh,0)) #lines needed to create rectangle
edge2 = Part.makeLine((halfw,halfh,0), (halfw,-halfh,0))
edge3 = Part.makeLine((halfw,-halfh,0), (-halfw,-halfh,0))
edge4 = Part.makeLine((-halfw,-halfh,0), (-halfw,halfh,0))
wire1 = Part.Wire([edge1,edge2,edge3,edge4]) #rectangle
face1 = Part.Face(wire1) #face from rectangle
face2=Part.Face(wire2) #face from epitrochoid
diff = face1.cut(face2) #boolean cut epitrochoid from rectangle
ext=diff.extrude(Base.Vector(0,0,30)) #extrude the cut (face) #show extrude in FreeCAD window

You should see Shape object in the Tree view and Wankel block model in the view area. You can click Fits the whole content of the screen button to tune view area. Unfortunately the Shape is not editable:(

Parametric way:

Open a new document and create a macro from below code (download macro):

from __future__ import division # allows floating point division from integers
import FreeCAD, Part, math
from FreeCAD import Base

class WankelBlock:
    def __init__(self, obj):
        ''' Add the properties: Radius, Eccentricity, Height, Segments (see Property View) '''
        obj.addProperty("App::PropertyLength","Radius","Wankel","Base radius").Radius=60.0
        obj.addProperty("App::PropertyLength","Eccentricity","Wankel","Rotor eccentricity").Eccentricity=12.0
        obj.addProperty("App::PropertyLength","Height","Wankel","Height of the block").Height=30.0
        obj.addProperty("App::PropertyLength","Segments","Wankel","Number of the line segments").Segments=72
        obj.Proxy = self

    def onChanged(self, fp, prop):
        if prop == "Radius" or prop == "Eccentricity" or prop == "Height" or prop == "Segments": #if one of these is changed

    def execute(self, fp): #main part of script
        steps=int(fp.Segments) #get value from property

        for i in range(steps):
            if i==0:
                x1=e*math.cos(3*ang)+r*math.cos(ang) #coords for line startpoint
                x2=e*math.cos(3*ang)+r*math.cos(ang) #coords for line endpoint
            ang=ang+dang #increment angle
        edge1 = Part.makeLine((-halfw,halfh,0), (halfw,halfh,0)) #lines needed to create rectangle
        edge2 = Part.makeLine((halfw,halfh,0), (halfw,-halfh,0))
        edge3 = Part.makeLine((halfw,-halfh,0), (-halfw,-halfh,0))
        edge4 = Part.makeLine((-halfw,-halfh,0), (-halfw,halfh,0))
        wire1 = Part.Wire([edge1,edge2,edge3,edge4]) #rectangle
        face1 = Part.Face(wire1) #face from rectangle
        face2=Part.Face(wire2) #face from epitrochoid
        diff = face1.cut(face2) #boolean cut epitrochoid from rectangle
        ext=diff.extrude(Base.Vector(0,0,h)) #extrude the cut (face)
        fp.Shape = ext #result shape

def makeWankelBlock():
    doc = FreeCAD.activeDocument()
    if doc == None:
        doc = FreeCAD.newDocument()
    wankelblock=doc.addObject("Part::FeaturePython","Wankel_Block") #add object to document
    wankelblock.Label = "Wankel Block"

if __name__ == "__main__": #feature will be generated after macro execution

After macro execution effect should be similar to first one. But take look in the Property View-Data. If you change one of the properties (radius, eccentricity, etc.) model will be automatically refreshed.

Properties can be also changed from the command line. As example, type:
App.activeDocument().getObject("Wankel_Block").Radius = 80

Comments are in the scripts code (after "#").
I have used four spaces for indentation.

Download RAW Video.

FreeCAD 0.12 5150 SVN

Friday, November 4, 2011

Engine: 7 - conrod, part 1

In recent versions of FreeCAD you can find graphical tool called Loft. It helps to make an extrude based on two or more sketches.
Create a sketch with H-like shape, it will be our conrod cross-section.

Next create two copies by selecting the sketch and using menu Edit-Duplicate Selection. You should have 3 sketches: Sketch, Sketch001 and Sketch002.

Translate the Sketch001 (~80 mm) and he Sketch002 (~100 mm) along Z-axis. You have to change Placement-Position in Property view tree (the sketch should be selected during operation).

The sketches should be different, so change some dimensions.

Now you can open the Part workbench, and select menu Part-Loft... Then move all sketches in the Task view to the Loft field. Check also Create solid option.

If effect isn't good, you can re-edit sketches.

Download file.

Download RAW Video.

FreeCAD 0.12 5088 SVN

Sunday, October 23, 2011

Engine: 5v2 - camshaft gear, parametric copy

In the post Engine: 5 - camshaft gear I used simple Python script to generate a radial copy. Unfortunately copies were independent from base object. Today I'll show how use more advanced radial script.

In directory:
you can find script.

Open earlier camshaft gear model. Delete Chamfer, Cut, Fusion and Fillet001 to Fillet036. Leave only he Revolution and the Fillet. Save model as a new file.

Import script by typing in the python console:
from PartDesign.Scripts import RadialCopy as rcopy
Select the Fillet and make a radial copy:
and eventually refresh the document:
At the end change values in Property view-data tab: Radius 0, Angle 10.

Open the Part workbench and use the boolean difference to cut the Radial Copy from the Revolution.

Try change something, eg. first sketch.

After a while whole model will be regenerated. This is the difference between previous and actual script.

Download file.

Download RAW Video.

FreeCAD 0.12 5052 SVN

Saturday, October 15, 2011

Engine: 6 - piston ring, macro tutorial

FreeCAD has good macros support. Let's me show you macro recording example: simple piston ring creation.

Macro creation

Open a new file in Part Design workbench. You should see four icons:

  • "Open a dialog to record a macro" - red circle 
  • "Stop the macro recording session" - (inactive) square
  • "Opens a dialog to let you execute a recorded macro" - notepad icon
  • "Execute the macro in the editor" - (inactive) triangle

Click on the "Open a dialog to record a macro" and fill "Macro name" field. Click on the Record button, macro recording will start.

Sketch a rectangle as above image on the plane  XY. It would be ring section.

Revolve section around Y axis with angle 359.5 deg (ring needs a small gap). Important: set base in the Property view to [0,0,0]. Now you should see finished piston ring model. You can stop macro recording - click on the "Stop the macro recording session" icon.

Click on the "Opens a dialog to let you execute a recorded macro", select your macro in the dialog window, and click Edit button. Now you can see your macro listing. You can do some clean up (I recommend replace "FreeCAD.getDocument.("Unnamed")"  with more universal "App.activeDocument()"). Save it with "Save the active document" icon. Listing should be similar to this:

# Macro Begin: /home/adi/.FreeCAD/piston-ring1.FCMacro +++++++++++++++++++++++++++++++++++++++++++++++++
import FreeCAD
import Sketcher
import PartDesign

App.activeDocument().Sketch.Placement = App.Placement(App.Vector(0.000000,0.000000,0.000000),App.Rotation(0.000000,0.000000,0.000000,1.000000))
#Gui.activeDocument().activeView().setCamera('#Inventor V2.1 ascii \n OrthographicCamera { \n viewportMapping ADJUST_CAMERA \n position 0 0 87 \n orientation 0 0 1 0 \n nearDistance 37 \n farDistance 137 \n aspectRatio 1 \n focalDistance 87 \n height 119 }')
App.activeDocument().Revolution.Sketch = App.activeDocument().Sketch
App.activeDocument().Revolution.Base = App.Vector(37.600000,1.850000,0.100000)
App.activeDocument().Revolution.Axis = App.Vector(0.000000,1.000000,0.000000)
App.activeDocument().Revolution.Angle = 360.0
App.activeDocument().getObject("Revolution").Angle = 359.50
App.activeDocument().getObject("Revolution").Base = (0.00, 0.00, 0.00)

# Macro End: /home/adi/.FreeCAD/piston-ring1.FCMacro +++++++++++++++++++++++++++++++++++++++++++++++++

Your icon, your toolbar

If you created an amazing macro you need your custom shortcut:) Open dialog window from the "Tools-Customize" menu.

Select "Macros" tab, fill "Menu text" and select your favorite "Pixmap". Then click "Add".

Now you can add icon to a toolbar. Select tab "Toolbars" and "Macros" from combo view. From the right combo select Workbench (eg. Part Design). Create new toolbar by clicking "New..." and then add your macro icon (eg. "Ring creator") using right arrow.

At the end you can see your icon (football in the example) in one of the FreeCAD toolbars. Click it to execute macro.


You can try:

  • modify created macros,
  • put scripts fro older posts as macros,
  • use PyQT to extend graphical interface,
  • use external modules in macros, eg. oosheet, pyODE
  • and much more!

Download file.

Download RAW Video.

FreeCAD 0.12 5017 SVN

This is probably the last "FreeCAD: engine tutorial" post before FreeCAD 0.12 stable release.

Friday, October 7, 2011

OOSheet as FreeCAD and LibreOffice bridge

Access to LibreOffice ( docs is able from Python. You can do it with PyUNO. When you need Calc spreadsheet, situation is even simpler. In this case OOSheet Python module is useful. 


As example I will show script which gets LibreOffice spreadsheet data, modifies FreeCAD wrench model and additionally returns model volume to the spreadsheet.

OOSheet installation under Ubuntu

I think that all readers have LibreOffice and Python installed. Fastest OOSheet installation method, type in terminal:

sudo apt-get install python-pip
sudo pip install oosheet

Actual FreeCAD version installation

I recommend add PPA repository:

sudo add-apt-repository ppa:freecad-maintainers/freecad-daily
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install freecad freecad-doc

What do you need to proceed

  1. File klucz_en.ods with our data.
  2. Model file klucz.fcstd. Everything should be saved in the fctest directory.


Our solid is based on a single sketch pad. Script for rows 2-12 will:
  • change pad (wrench thickness),
  • change sketch constraints: 45 (wrench gap), 51 (wrench length), 54 (wrench connector width),
  • recompute model,
  • export solid to STEP - file number equal to row number,
  • export model views to SVG file,
  • compute solid volume and return it to last spreadsheet column.
Open LibreOffice spreadsheet with 2002 port listening by typing in terminal:
oocalc fctest/klucz_en.ods -accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"

Then open in FreeCAD klucz.fcstd model file. Put below script in FreeCAD Python console. You should see new STEP and SVG files in fctest directory. Last sheet column should be filled by computed volume values.

Script listing:

from oosheet import OOSheet as S # for connection with z OO Calc
import ImportGui # for STEP export
for keynumber in range (2,13):
     skey = str(keynumber)
     App.ActiveDocument.Sketch.setDatum(54,S('b'+skey).value) #wrench connector width from sheet
     App.ActiveDocument.Sketch.setDatum(51,S('a'+skey).value) #wrench length
     App.ActiveDocument.Sketch.setDatum(45,S('d'+skey).value) #wrench gap
     App.ActiveDocument.getObject("Pad").Length = S('c'+skey).value #wrench thickness
     App.ActiveDocument.recompute() #model recompute
     __objs__=[] #STEP export
     del __objs__
     PageFile = open(App.activeDocument().Page.PageResult,'r') #SVG export
     OutFile = open('fctest/klucz'+skey+'.svg','w')
     del OutFile,PageFile
     S('e'+skey).value = App.ActiveDocument.getObject("Pad").Shape.Volume #save volume in the sheet

Download Video.
Source post.

Saturday, October 1, 2011

Engine: 5 - camshaft gear

Timing wheel (camshaft gear) which works with toothed belt is quite simple part. However it needs radial pattern tool - I will use short python script.

Open a new sketch in Part Design workbench. First of all sketch a trapezoid on the plane XY. Use dimensions as in the picture. Trapezoid should be connected with point (0,0) by two construction (blue, length = 47) lines.

Pad the sketch. The pad should be 30. You can add fillets to edges.

Make a new sketch on the plane YZ. Draw a wheel section.

Dimension and constraints are shown above.

Revolve the sketch around Z axis (Data tab in Property view). Next hide the revolution by selecting it and pressing [Space].

Use a python script

FreeCAD has a python console (at the bottom). Select Pad in Tree view and copy this script to python console:

teeth= 36
sel = FreeCADGui.Selection.getSelection()
sel = sel[0]
name = sel.Name
shape = sel.Shape
for i in range(1,
     newshape = sel.Shape.copy()
     newshape.Placement=App.Placement(App.Vector(0,0,0),App.Vector(0,0,1),       (i*(float(360)/float(
     newobject = FreeCAD.ActiveDocument.addObject("Part::Feature",name)
     newobject.Shape = newshape

35 new pads should appear as in the image above. You made radial pattern!

Short explanation:
teeth= 36 number of pads

sel = FreeCADGui.Selection.getSelection()
sel = sel[0]
name = sel.Name
shape = sel.Shape
get information from part selected in Tree view

for i in range(1,teeth): loop from 1 to 35 (python count from 0)

newshape = sel.Shape.copy() make a copy

newshape.Placement=App.Placement(App.Vector(0,0,0),App.Vector(0,0,1),       (i*(float(360)/float(teeth)))) move the copy, syntax App.Placement(Base, Axis, Angle in deg)

Open Part workbench and select all pads (or fillets if made they) in Tree View - use [Shift] and click first and last. You can deselect revolve with [Ctrl]. Now make a fusion (two blue balls icon) of the all pads. Unhide [Space] the revolution.
Select with [Ctrl] revolution and fusion and do cut of them (icon with blue and white ball).

Now we have a crankshaft gear.

You can also open Part Design and add some fillets and chamfers.

More info:
Download file.

Download RAW Video.

FreeCAD 0.12 4983 SVN

Sunday, September 25, 2011

Engine: 4 - camshaft

Open model file with cams. Save it with different name, eg. camshaft.fcstd. Next select Part Design Workbench in Combo Select or by menu View-Workbench-Part Design.

You need revolve around Z-axis. Create new sketch on the XZ plane. You can also toggle visibility of cams by selecting one in Tree view and pressing [Space].
First end of shaft should be moved by 95. I recommend you sketching in steps: draw poliline with 3-4 segments, constrain they, then add next poliline. The shaft looks like a fusion of several cylinders:

Length Radius
20 8
23 10
30 12.5
72 10
16 12.5
70 10
2 13.5
16 12.5
2 13.5
70 10
16 12.5
72 10
16 12.5

In the left corner you can see a new feature in FreeCAD information about number of missing constraints or text Fully constrained sketch.

Close the sketch, and revolve it around Z-axis. You can set different angle but it this example 360 deg is necessary.

Unhide all shapes with [Space].

Boolean operations

Boolean operations are available in the Part workbench. Select the Part workbench. Next select all shapes with [Ctrl] key and click on "Make a union of several shapes" icon.

Now you have a new shape "Fuse". Return to the Part Design workbench. Select edges with [Ctrl] to fillet. Apply fillet and change it radius to 2 in Property view-Data.


Currently FreeCAD has very limited blueprints support.
Open Drawing workbench. Click on "Insert new drawing". Select a shape in Tree view and click on "Insert a new view of a Part in the active drawing". In a new tab you can see badly placed view. Tune placement in the Property view-Data-Drawing and Property view-Data-Shape view (in the Tree view Page-View have to be selected). In the screenshot you can see two views:
  • scale=0.5, x=100, y=100, direction x=0, y=0, z=1
  • scale=0.5, x=300, y=100, direction x=1, y=0, z=0
Finally you can export a page by clicking "Export a page to an SVG file" icon.

Download file.

Download first RAW Video.

Download second RAW Video.

FreeCAD 0.12 4957 SVN

Saturday, September 17, 2011

Engine: 3 - cams

Simple 8-valve engine needs only one camshaft: with 4 inlet and 4 exhaust cams. Today I'll design only cams - not entire camshaft.

Open a new sketch.

Our shape will be rotated by 14.24 deg. It is result of specified valves timing. Lets draw two connected lines: one horizontal, second rotated by 14.24 deg. Set second line length to 21.5. Next set they construction mode.

Construction lines are blue instead white. At the end set connecting point to (0, 0) with a lock constrain.
I need harmonic cam working with flat-faced follower. It can be constructed from four tangent arcs.
Take look at 21.5 mm line: left end will be bigger arc centre, right is for smaller arc centre. Draw arcs as in the above picture.

Now I should connect those arcs with two next, tangent arcs... but current (4928 SVN) FreCAD have not arc-arc tangency support. I drew two short, tangent for arcs, construction lines.

Next I connected arcs with second two (big radius ~100) ones. One of them I made tangent to two short construction lines. Additionally I set up first two arcs radius to 14 and 1.5 mm respectively. Connecting arcs should be exactly the same - use equality  constraint for them and next set two points (one end of each one) symmetrical for 21.5 mm line.
Note: also radius of connecting arcs should be specified but I have problems with this in 4928 SVN FreeCAD. I'll return to this issue in the future... 

Now you can make 12 mm pad. If shape isn't solid, check construction lines in the sketch.

Next I made second cam. This time shape is rotated by 167 deg from vertical line.

Now we have two cams: exhaust (first one) and inlet.

Select second cam and set Placement in Property view - Data. Set Z translation to -40.

For your convenience set names for Pads - click on it and press [F2]. Different colors also are useful - set they in Property view - View - Shape Color.

Now you can add next 6 cams: simply use Copy-Paste and Placement options.
Cam Z translation [mm] Rotation around Z axis [deg]
Exhaust 0 0
Inlet 40 0
I 88 90
E 128 90
E 176 270
I 216 270
I 264 180
E 304 180

And the final result:

Download model file.

FreeCAD 0.12 4928 SVN