G Code Plotting Python

May 20, 2019 However this is intended as a minimal guide to understand a minimal set of codes needed for 2D plotting. G-Codes for 2D Plotting. To get an idea of how G-codes work, let me first show you the beginning of an example file.% G90 G49 M3 S15000 G0 X20.456 Y20.910 Z15.000 G1 Z35.000 F2500 G1 X18.202 Y13.354 F2500 X16.806 Y13.352 X15.300 Y18.656. Jul 07, 2020 The user presses the Play button to run the g-code. When a g-code reaches the line where it should execute an external Python script, PlanetCNC allows two ways of script execution: with (PY,PYTHON-SCRIPT) command, a python script is executed and PlanetCNC waits for it to finish until it proceeds to the next line of g-code.

Couple of week ago, I started working on homemade CNC plotter that uses stepper motors form old CD/DVD drives. At some time, controller was implemented and construction was solid, so that was a good time for a test run. But what to print? There are couple of web sites that can generate G code from string, but what if we want to plot some image with CNC plotter . How can we generate G code from an image?

In this post I will try to explain the process that I have found out to be very good in creating G code from an image. I wanted a solution that is free and easy, so the choice came down to open source software. I’m not saying that this is the best way, but until this point, it is the best way I know. So please, if you have any other suggestions, that can make this process easier, comment down bellow.

I’m using Inkscape, an open source vector graphics editor, that is used for image editing. Also, for a long time I wanted to try Linux distribution called Manjaro, so this G code generation is done using this operating system. Let’s start.

To begin with, what is actually G code?

“G-code (also RS-274), which has many variants, is the common name for the most widely used numerical control (NC) programming language. It is used mainly in computer-aided manufacturing to control automated machine tools.

G-code is a language in which people tell computerized machine tools how to make something. The “how” is defined by g-code instructions provided to a machine controller (industrial computer) that tells the motors where to move, how fast to move, and what path to follow.”

from Wikipedia

G code cheat note

Example of some G code that are used in CNC programming.
CodeDescription
G0Rapid Movement
G1Coordinated Movement X Y Z E
G2 clockwise ARC
G3counter clockwise ARC
G4Dwell S(seconds) or P(milliseconds)
G28 Home all Axis
G90Use Absolute Coordinates
G91Use Relative Coordinates
G92 Set current position to coordinates given
M0 Unconditional stop
M18Disable all stepper motors; same as M84
M84Disable steppers until next move or set an inactivity timeout
M112 Emergency stop

Now when we have basic understanding of G code, let’s install Inkscapeon Manjoro. Open the terminal in Manjaro with keyboard shortcut Ctrl+Alt+Tor by pressing F12 if program Yakuakeis running in background.

Python plotting tools

Install Inkscape with next command:

  1. sudo pacman -Syyu (optional – update system)
  2. sudo pacman -S inkscape

We have Inkscape now installed on our PC.

After successful installation, go to Inkscapesite at https://inkscape.org/ and go to tab Download >> Extensions, to download G code extension for Inkscape. Find GcodePlotextension and download it. To install this extension, copy the downloaded content into Inkscapeinstallation directory. Go into Download directory, unpack zip folder and copy that content to /usr/share/inkscape/extensions/ . After that, we can find option in Save As pop up window to save file as .gcode or 3-axis gcode plotter.

We are ready to start image processing. Let’s chose one image, logo for thunderbird email client, shown bellow. Just drag and drop image to Inkscape window. When that is done, we have an embedded image that we can process.

Next steps are as followed:

  • Set document size – go to File -> Document properties and set document custom width and height.
  • Move and Resize Image to fit
  • Trace Bitmap – in order to convert color images to G code, we need to lose information about the color. In other words, we need to convert the image to black and white. This can be done with Trace Bitmap (Path->Trace Bitmap…)
Python
  • Simplify trace a bit, to ease manufacturing process. Select image and go to Path-> Simplify. With this we have much less traces in our image, but image quality is still pretty much the same.
  • Next step is to save image as .gcode file using the extension that is installed in first part of this blog
  • Default configuration is used in pop-up window for gcode extension

And that is it. We have .gcode file. But is this the end? No.

G code is a bit different from machine to machine. It is a bit like a language dialect. Language is still the same, but there is some difference. I will run this .gcode file on my homemade CNC plotter, where CNC controller is programmed by me. I have’t implemented, yet, all gcode instructions inside, so for now there are only main functions, like linear movement, pen up, pen down.

Because of that reason I made simple python script called Gcode_BLN.py that will just simplify gcode to dialect that is currently implemented on my CNC controller. As this step is necessary for my CNC controller only, there is no need looking deeper into it.

We can start CNC machine and send G code file. Result is pleasing, maybe just for me. Construction of my CNC machine is, to say a least, not the best, and it needs improvement. There is a lot of wiggle, especially when pen is down and moving. As this is mainly a software test, I reckon that the result is pretty OK, especially for the first try.

We are almost at the end of my first post. I tried to capture my process of generating G code from Image. If you any ideas on a more optimal solution, please let me know.

If you stayed with me this long, thank you. Only with your help I can get better with every post, lose the typing errors and unclear sentences, get suggestions on what I need to fix and do better. So stay with me to witness the progress.

Thank you once again, and see you soon.

3d plotting python

Since I first acquired my CNC machine I started building a set of tools in Python to let me generate and manipulate gcode files. I have now released this code on GitHub under a Creative Commons Attribution-ShareAlike license in the hope it will be useful to others as well.

Disclaimer: Please be careful before using any of the gcode generated by these tools on your actual machine. Although I use it successfully myself on a range of projects I cannot guarantee that it won't damage your machine or behave differently in your environment. A good check is to run the resulting code through OpenSCAM before using it on an actuall CNC machine.

About The Code

So, what's in the box? The code consists of a simple class framework to load, manipulate and save .ngc files as well as a handful of simple (and complex) command line utilities. The code base is definitely a work in progress, so please don't expect a perfect 'out of box experience' - it has built up over the past 9 months and undergone several refactorings and rewrites as I added the tools and functionality I needed for a particular use case.

There is no 'pip install' option, you will just have to clone the repository and run the tools directory. You will need Python 2.6 or 2.7 to run the tools and there are a few dependencies you will need to install as well:

G Code Plotting Python
  1. pillow - the Python Imaging Library. This is used to generate PNG representations of gcode files.
  2. matplotlib - this is only used in the probeinfo.py utility to generate height map images from bCNC probe files.

All the tools use millimeters for units (and gcode files in inches will be converted to millimeters when they are loaded). In most cases the tools assume you are doing simple 2D operations with single cut (Z < 0) and safe (Z > 0) depths - gcode that uses a range of Z levels will probably not fare well.

To avoid having to specify parameters on every tool the library looks in the file 'gcode.json' (included in the repository) for a set of default values to use if the associated command line option is missing. That file looks like this ...

I've done my best to make the utilities self documenting, simply run them without any arguments to get a list of options available. The best way to see how it works though is to look at the source code itself.

The remainder of this post gives an overview of the classes provided and how to use them, if you are only interested in the existing set of utility programs you can skip ahead to the end of the post.

GCode and GCommand Classes

All of the supporting code lives in the util package in the repository. The two main classes of interest are GCommand which represents a single gcode command and GCode which represents a sequence of commands (basically the whole .ngc file).

You can either create a GCode instance by loading a .ngc file or by building it up line by line in your program. The GCode instance will update the bounding box that contains the cutting operations automatically.

Once the GCode instance is created you can inspect the individual commands by looking at the lines attribute.

Each entry in the lines list is a GCommand instance. This splits the gcode into it's command and parameters so you can easily manipulate it.

Each of the standard parameters for a gcode instruction is added as an attribute on the GCommand instance. If the parameter has not been assigned a value the attribute will be set to None. The command itself (eg 'G00' or 'G38.2') is stored in the command attribute.

You can create a GCommand directly either by passing the command you want to use as a string or by setting the attributes after construction.

Finally you can save the modified (or created) gcode to a file with the saveGCode() function.

As a bonus you can also render the gcode to an image - this gives you a visual representation of what the result will look like.

Filters

The classes above provide enough functionality to programatically create gcode either from mathematical functions or by converting other formats such as graphics files into something that can be sent to a CNC machine. The next step is to be able to modify existing files and apply transformations.

To do this the framework provides a Filter class that can be applied to a GCode instance. Each filter implements a method called apply() which will be called with each command in turn. The method can return None to indicate the line should be ignored or a sequence of GCommand instances that will replace the original.

I have already implemented a number of filters in filters.py that provide support for translation, rotation, flipping and axis swapping. One useful filter will fix arcs for you by recalculating the center point - the LineGrinder tool in particular has a bad habit of generating arc commands with poor resolution. The implementation of this filter is an adaption of the LineBender code.

Filters are applied with the clone() method on the GCode instance - this will return a new instance consisting of the modified commands. As you can see in the example above you can apply multiple filters in a single call - they will be applied in the order given.

Utilities

G Code Plotting Python Code

I have also included a set of simple utilities in the repository as well:

G Code Plotting Python Interview

  • areacut.py - generate a .ngc file to cut out a rectangular area at a specified depth.
  • ngcmerge.py - append multiple .ngc files together to create a single file.
  • reorigin.py - translate the file so the minimum X and Y cutting co-ordinates are at the origin.
  • bounds.py - display the bounding box for the cutting operations in the file and optionally generate an image of the tool path.
  • multipass.py - convert a single cutting operation into multiple passes at smaller cutting depths.
  • probeinfo.py - this one doesn't actually do anything with .ngc files, it creates a height map image from a bCNC .probe file.
  • rotate.py - rotate the file by a specified angle.
  • zlevel.py - change the cutting depth and safe level for the file.

There are also a few more complex utilities in there as well. The pcbpack.py script will lay out PCB isolation routing gcode files to fit a blank PCB panel and generated combined milling, edge milling and drilling files in the process. This tool will get it's own post in the next few days.

There is also svg2ngc.py which is an incomplete implementation of a SVG to gcode converter as well as a tool to generate SVG templates for cutting out double U style boxes.

What's Next?

Now that I've pushed the code to a public repository there is a bit of clean up work I would like to do - remove some redundant files and clean up the documentation for the project. While the PCB layout tool is mostly complete (enough that I can use it on a regular basis) it still needs some tweaking and the other larger tools are not yet finished.

Python Plot Graph

As I said at the start of the post, it's still a work in progress but functional enough to be useful and the framework makes it very easy to implement new tools as they are needed. I will keep adding to it over time and, if you come up with useful additions please send a pull request to have them included.