G-code, firmware & ecosystem
Behind every print is a text file of simple commands and a firmware that turns them into motor pulses and heater power. Learn to read G-code, understand how the main firmware families differ, and connect your printer to your network safely.
- How to read G-code, with the essential commands explained line by line, including a first-layer example.
- What firmware does, and how Marlin, Klipper, RepRapFirmware, Prusa, Bambu and Creality differ.
- Key control concepts: motion planning, pressure advance, input shaping and bed mesh compensation.
- Host software, network modes, security and privacy basics, monitoring and automation.
- How to edit start and end G-code, post-process files and debug a print by reading its G-code, safely.
G-code primer
G-code is a line-based language of machine commands. Each line holds a command (like G1) followed by parameters (letters with numbers, like X50 Y20 E0.8 F1800). Anything after a semicolon is a comment that the printer ignores. Your slicer writes the file; the printer's firmware reads it one line at a time and executes it. Because the language dates back to CNC machines of the 1950s, dialects differ between firmware, but the basics are shared.
Essential commands
| Command | Meaning | Example and notes |
|---|---|---|
G0 / G1 | Move; G1 usually carries extrusion, G0 is a "rapid" move | G1 X100 Y50 E2.5 F1800. Feed rate F is in mm/min (1800 = 30 mm/s). Many firmwares treat G0 and G1 the same. |
G2 / G3 | Arc clockwise / counter-clockwise | G2 X20 Y0 I10 J0: I, J are offsets from the start point to the arc center. Reduces file size when arc fitting is enabled. |
G28 | Home axes | G28 (all) or G28 X Y. Always the first motion of a job. |
G29 | Bed leveling / mesh probing | Marlin and some vendors use it; Klipper uses BED_MESH_CALIBRATE. Bambu start G-code also triggers leveling through its own routine. |
G90 / G91 | Absolute / relative positioning (XYZ) | Absolute is the norm; relative is used for small hops and retractions. |
M82 / M83 | Absolute / relative extruder mode | Relative (M83) is preferred since E never grows large. |
G92 | Set current position without moving | G92 E0 resets the extruder counter (needed with absolute E). |
M104 / M109 | Set hotend temperature / set and wait | M104 S210 starts heating; M109 S210 blocks until reached. |
M140 / M190 | Set bed temperature / set and wait | M140 S60 then M190 S60 later. |
M106 / M107 | Part-cooling fan speed / off | M106 S255 is 100 %; S range 0–255. M106 P1 S128 can address a second fan. |
M204 | Set acceleration | M204 S3000 (some firmware uses P/T for print and travel). |
M205 | Set jerk or junction deviation limits | M205 X8 Y8 in Marlin; Klipper uses SET_VELOCITY_LIMIT instead. |
M900 K… | Linear/pressure advance factor (Marlin, Bambu) | M900 K0.04. Klipper: SET_PRESSURE_ADVANCE ADVANCE=0.04. RepRapFirmware: M572 D0 S0.04. |
M220 / M221 | Speed / flow override (percent) | M221 S95 reduces flow to 95 %. |
M600 | Filament change (pause, unload, wait) | Used for color changes on single-extruder machines. |
T0, T1… | Select tool/extruder | Tool changers and multi-extruder machines. Dual-nozzle and AMS printers wrap tool or filament change in vendor-specific sequences (for example, Bambu uses M620/M621 blocks, which you should not edit). |
G4 | Dwell (wait) | G4 P500 waits 500 ms. |
M84 | Disable stepper motors | End-of-print command. |
M73 | Progress and time remaining | Updates the printer display. |
A command with the same name can behave differently between firmwares, or may not exist. Always check the documentation of your printer's firmware before copying lines from forums.
Arcs and relative moves
Line-by-line: a first-layer sample
This simplified sample shows what a typical job looks like from the start. It is a generic, Marlin-style example for teaching, not a profile for any specific printer: real start G-code from vendors includes many extra steps.
; ===== start G-code =====
M140 S60 ; start heating bed to 60 C (do not wait yet)
M104 S150 ; pre-heat nozzle to a safe probing temperature
G28 ; home X, Y, Z
G29 ; probe the bed and build a leveling mesh
M190 S60 ; wait for the bed to reach 60 C
M109 S210 ; heat nozzle to 210 C and wait
G90 ; absolute XYZ positioning
M83 ; relative extruder moves
G92 E0 ; reset extruder position
G1 Z2.0 F600 ; lift the nozzle
G1 X10 Y10 F6000 ; travel to the purge line start
G1 Z0.3 F600 ; lower to first-layer height
G1 X110 Y10 E10 F1200 ; purge line: slow, thick bead
G1 Z2.0 F600 ; lift away
; ===== layer 1 =====
;LAYER_CHANGE
;Z:0.2
M106 S0 ; fan off for the first layer
G1 Z0.2 F600 ; move to layer height 0.2
G1 X60.0 Y60.0 F6000 ; travel to the start of the outer wall
G1 E0.8 F1800 ; un-retract (prime the nozzle)
G1 F1200 ; set first-layer print speed (20 mm/s)
G1 X80.0 Y60.0 E0.66 ; draw 20 mm of line; E is filament pushed
G1 X80.0 Y80.0 E0.66 ; next side of the square
G1 E-0.8 F2100 ; retract before travel
G1 Z0.6 F600 ; z-hop
G1 X120.0 Y60.0 F6000 ; travel to the next island
; ===== end G-code =====
M104 S0 ; heater off
M140 S0 ; bed off
M107 ; fan off
G91 ; relative positioning
G1 Z10 F600 ; raise the nozzle
G90 ; back to absolute
G1 X0 Y200 F6000 ; park the toolhead
M84 ; release the motors
E is the length of filament pushed, in millimeters of 1.75 mm filament. A rough check: line volume ≈ line width × layer height × length, e.g. 0.42 × 0.2 × 20 mm = 1.68 mm³. Filament cross-section for 1.75 mm is 2.405 mm², so E ≈ 1.68 ÷ 2.405 ≈ 0.70 mm; the sample's 0.66 is in the right range, with differences caused by flow ratio and line-shape assumptions.
Bambu .gcode.3mf and binary G-code
Bambu Studio does not send a plain text file. It produces a .gcode.3mf, which is a ZIP-compressed 3MF package containing the sliced G-code (Metadata/plate_1.gcode and related files), plate thumbnails, per-plate settings and a checksum used by the printer. You can rename the file to .zip and open it to look at the contents. The G-code inside contains many Bambu-specific commands for calibration, AMS handling, noise and chamber control, so it will not run unchanged on other printers. Prusa printers use a different compact container: .bgcode, a binary G-code format that stores metadata and compressed blocks, and can be converted back to text with Prusa's tools. In both cases the slicer's preview, not the raw file, is the right place to inspect a job.
On printers with proprietary firmware (such as Bambu Lab), the start and end sequences, AMS or tool-change blocks, calibration routines and some M commands are tightly coupled to the firmware. Editing them without knowing exactly what each line does can cause collisions, nozzle crashes, failed calibrations or a printer that refuses to run the job. Read freely; change only the customizable fields the slicer offers, in small steps.
What firmware does
Firmware is the software running on the printer's controller board. It reads G-code (from an SD card, USB, or over a network), plans motion, reads temperature sensors, runs the heater control loops, watches for faults, and drives the display. It is the layer between the slicer's intent and the physical machine, and it decides what is possible: input shaping, pressure advance, networking, and safety features all live here.
Firmware families
Marlin is the most widespread open-source firmware, running on 8-bit and 32-bit boards in many budget printers. Features are compiled in: configuration is in Configuration.h and Configuration_adv.h, and changing it means editing source and re-flashing. It supports linear advance (M900), input shaping on newer versions, unified bed leveling and a rich M-code set. Strengths: simple, compatible, runs on cheap hardware. Limits: tuning requires rebuilding; planner throughput on weak boards caps speed.
Klipper splits the work: a host computer (often a Raspberry Pi or similar) runs the planner and kinematics in Python/C, and the microcontroller only executes precisely timed step schedules. Configuration lives in a text file (printer.cfg) that you edit and apply with a restart, no compiling. It offers pressure advance, input shaper, bed mesh, macros and many accessories. Typical front ends are Mainsail and Fluidd, talking through Moonraker, an API server. Strengths: high speed, deep tuning, scripting. Limits: needs a second computer and some Linux comfort.
RepRapFirmware runs on Duet boards (32-bit, with a built-in web interface and network). Configuration uses G-code files (config.g, homeall.g, bed.g) and macro files you can edit in the browser. Features include dynamic acceleration tuning, input shaping, tool changers and a strong multi-tool model. Strengths: integrated, flexible, polished for tool changers and research use. Limits: hardware is pricier, and the ecosystem is smaller than Marlin or Klipper.
Prusa printers run a Marlin-derived firmware (Buddy on current boards) with many vendor features: crash detection, power-loss recovery, filament sensing, network connect, and binary G-code (.bgcode) support. The source is public, but only Prusa-supplied builds are supported. Strengths: reliable out of the box, tightly integrated with PrusaSlicer profiles. Limits: customization is more constrained than in pure Klipper.
Bambu Lab printers run proprietary, closed-source firmware tightly coupled to Bambu Studio, the Handy app and Bambu's cloud. Many functions (calibration, AMS handling, AI monitoring, motion tuning, noise control) work with little user setup, and updates arrive as signed packages, roughly every few months. Strengths: very low setup effort, fast, consistent. Limits: you cannot swap in your own firmware, deep motion-level changes are not exposed, and some network features rely on vendor services or limited local modes (see network and security). For X2D specifics see settings and profiles.
Creality ships a range: older models use Marlin variants, while newer models (for example Creality's K-series) ship with Klipper-based firmware and their own front end. Because vendor builds are often customized and may lag upstream, check what your specific model runs, and whether the vendor provides configuration files and update instructions. Community firmware projects exist for popular models, but flashing them carries a risk of voiding warranty or bricking the board.
| Family | Config style | Tuning depth | Network | Open source | Best for |
|---|---|---|---|---|---|
| Marlin | Compile + flash | Medium | Via add-ons | Yes | Budget and DIY machines |
| Klipper | Text file, restart | Very high | Moonraker API | Yes | Speed and tuning enthusiasts |
| RepRapFirmware | G-code config files | High | Built-in web UI | Yes | Tool changers, research |
| Prusa Buddy | Vendor menus + G-code | Medium | Prusa Connect, local | Source available | Reliable appliance use |
| Bambu | Studio profiles + app | Low | Cloud, LAN mode | No | Fast, low-effort printing |
| Creality | Varies by model | Varies | Vendor cloud / local | Partly | Budget entry machines |
Motion planning and pressure advance
Firmware does not simply move from point to point at the requested feed rate. A planner looks ahead at upcoming moves and builds a velocity profile with an acceleration ramp, cruise phase and deceleration ramp, limited by the maximum acceleration and by the allowed speed at each corner (jerk or junction deviation). Short segments, like those on a curve, may never reach the target speed, which is why detailed models print slower than the feed-rate settings suggest.
Pressure advance (linear advance, flow dynamics)
Molten plastic in the nozzle behaves like a compressible spring. When the extruder speeds up, pressure lags and the line starts thin; when it slows, the stored pressure keeps pushing and you get a bulge at corners. Pressure advance models this with a factor K (in seconds): the extruder speed gets a boost proportional to its acceleration. The right K depends on filament, temperature and hardware: direct-drive extruders with short paths typically need small values (around 0.02–0.08 for many filaments), while long Bowden tubes need larger ones (often 0.5 or more). Different firmware use different names and commands:
| Firmware | Name | Command |
|---|---|---|
| Marlin | Linear advance | M900 K0.05 |
| Klipper | Pressure advance | SET_PRESSURE_ADVANCE ADVANCE=0.05 |
| RepRapFirmware | Pressure advance | M572 D0 S0.05 |
| Bambu | Flow dynamics (K, with N for shaping) | Calibrated in Studio; applied by the printer via M900 in the file |
Flow Dynamics Calibration applies to the main nozzle only; the auxiliary nozzle runs conservatively and is limited to roughly 200 mm/s and 1,000 mm/s². See dual-nozzle printing. Calibration fundamentals are in calibration.
Input shaping and resonance
Every printer frame and toolhead has resonant frequencies. Rapid direction changes excite them, leaving ripples ("ringing" or "ghosting") after sharp corners. Input shaping pre-filters motion commands so they cancel the resonance. An accelerometer (built in on many modern printers, or a small add-on board on Klipper machines) measures the frequency response; the firmware stores a shaper type and frequency for each axis. Gains: you can use higher accelerations with less ringing. The trade-off is slight rounding of fine corners when strong shapers are used, so firmware picks the mildest shaper that works.
Bed mesh compensation
No bed is perfectly flat. A probe measures height at a grid of points, and firmware interpolates a surface. While printing, it nudges Z (and sometimes blends it out with height) so the first layer follows the actual surface. Large meshes cost time; many printers cache or limit the area to the print region.
Klipper concepts
Klipper is popular with tinkerers because everything is a text file and a few commands. The key building blocks:
- printer.cfg: the main config. Sections such as
[stepper_x],[extruder],[heater_bed],[probe],[bed_mesh],[input_shaper]. Pin names, rotation distance, limits and sensors are defined here. - Macros: named G-code snippets with Jinja templating, defined in
[gcode_macro NAME].PRINT_STARTandPRINT_ENDare the conventional hooks, so the slicer's start G-code only calls them with parameters. - Pressure advance:
pressure_advanceunder[extruder], adjustable on the fly withSET_PRESSURE_ADVANCE. - Input shaper:
[input_shaper]withshaper_freq_x/yand type; measured withSHAPER_CALIBRATEusing an accelerometer. - Bed mesh:
BED_MESH_CALIBRATEprobes andBED_MESH_PROFILEsaves or loads named meshes. - SAVE_CONFIG: stores calibration results at the bottom of
printer.cfgin an auto-generated block. Do not hand-edit that block.
# printer.cfg excerpt: a minimal PRINT_START macro
[gcode_macro PRINT_START]
gcode:
{% set BED = params.BED|default(60)|float %}
{% set EXTRUDER = params.EXTRUDER|default(210)|float %}
M140 S{BED} # start heating bed
G28 # home
BED_MESH_CALIBRATE # probe
M190 S{BED} # wait for bed
M109 S{EXTRUDER} # heat and wait for nozzle
G92 E0
G1 X10 Y10 Z0.3 F3000
G1 X110 Y10 E12 F600 # purge line
The slicer's start G-code then becomes one line: PRINT_START BED=[bed_temperature_initial_layer_single] EXTRUDER=[nozzle_temperature_initial_layer] (placeholder names vary by slicer). This keeps hardware logic with the printer, where it belongs, and the slicer profile portable.
Host software
A host is a program (or computer) that sits between you and the printer: it uploads files, starts and pauses jobs, shows temperatures and a camera view, and records history. The printer's firmware keeps doing the real-time work; the host adds comfort and remote access.
OctoPrint
The classic Python host, often run on a Raspberry Pi connected to the printer by USB. A large plugin ecosystem (bed visualizer, timelapse, failure detection). Best with Marlin-style firmware. Maintain it: keep the server updated and do not expose it directly to the internet.
Mainsail / Fluidd (with Moonraker)
Web interfaces for Klipper. Moonraker is the API layer that provides file management, job queue, history, webcam streams, update manager and integrations. Both show macros as buttons and the config in an editor.
Obico
Camera-based failure detection and remote monitoring, available as a hosted service or self-hosted. It works with OctoPrint and Klipper setups and can pause a print if it detects "spaghetti". Check current plans and what data is sent where.
Repetier-Server and others
Repetier-Server manages multiple printers from one host. Other options include vendor tools such as Prusa Connect and Duet Web Control. Pick the one your firmware speaks natively.
Network, security and privacy
A connected printer is a small computer with a heater and moving parts. Treat it like any other device on your network: limit who can reach it, keep it updated and understand where your data goes. Details below are general; vendors change features, so read their current documentation.
Cloud mode vs LAN mode
Cloud (vendor service)
- Print from anywhere, view camera, get notifications, sync profiles and models.
- The printer keeps an outbound, authenticated connection to the vendor's servers; jobs and status pass through them.
- You rely on the vendor's uptime, account security and privacy policy.
LAN mode (local only)
- The slicer or app talks directly to the printer on your local network, often using a device-specific access code (a short password shown on the printer's screen).
- Fewer outside dependencies; works if the internet is down.
- Some vendor features (remote viewing, certain notifications, cloud sync) may be reduced or unavailable. Check the current feature list.
The X2D works with Bambu Studio and the Handy app via Bambu Cloud, and offers a LAN mode for local use. Firmware updates arrive roughly every three months, and the printer's cameras support AI monitoring such as spaghetti and foreign-object detection. Setup steps are in setup and first print.
Practical security rules
- Keep printer firmware, slicer and host software updated. Updates fix security bugs as well as print bugs; skip them only after reading the notes for a known regression.
- Never forward printer or OctoPrint/Mainsail ports from your router to the internet. Use a VPN into your network instead.
- Treat access codes, API keys and tokens as passwords: do not paste them into screenshots, forum posts or public config repositories.
- Use unique, strong passwords on vendor accounts and enable two-factor authentication where offered.
- Put printers and cameras on a guest or IoT network when your router supports it.
- Check what the camera and cloud features send and store, and disable features you do not use. Point cameras away from private spaces.
- Download plugins and macros only from sources you trust, and read what they do: a macro runs with the printer's full authority.
- Be careful with files from unknown sources: G-code is a program for a machine with a heater. Review unfamiliar G-code before running it.
Remote control is convenient, but a printer is still a heat source. Keep thermal-runaway protection enabled, use a smoke detector in the room, and do not leave long prints unobserved unless you accept the risks. See safety and workspace.
Monitoring and timelapse
Cameras let you check a print without walking to the room. A small USB or built-in camera streams video; a host or the printer's own software captures a frame at each layer change for timelapse (parking the toolhead briefly gives a smoother, less cluttered movie). Beyond watching, software can run AI detection on the images: "spaghetti" (detached prints), foreign objects on the bed, a clean first layer or a blocked nozzle. Treat detection as a safety net, not a guarantee: it misses unusual failures, and false alarms happen. Good practice is to set the response to "pause and notify", not "cancel", so you can decide.
- Lighting matters more than camera resolution: a steady LED beats a better sensor in the dark.
- Placement: view the bed from the front or above; avoid fogged enclosure glass.
- Notifications: use push messages only for events that matter (done, paused, error) to avoid ignoring them.
Automation and integrations
Most hosts and vendor apps expose state (progress, temperatures, errors) through an API, a message feed or webhooks. That makes small automations possible:
| Idea | How | Caution |
|---|---|---|
| Notify when a print finishes | Webhook or push plugin on the host | Avoid including private info in messages |
| Dashboard in Home Assistant | Official or community integration reads status (temperature, progress, camera) | Integrations may stop working after firmware or API changes; read recent issue reports first |
| Turn on enclosure lights or exhaust fan when printing | Automation triggered by job state | Do not switch off power to the printer automatically during a job or while the hotend is hot |
| Auto-start a queue | Klipper/Moonraker job queue, OctoPrint plugins | Requires a reliable bed-clearing routine; unattended chains increase risk |
| Log filament usage and cost | Spoolman and similar inventory tools | Keep inventory in sync with real spools |
Home Assistant, in particular, is a popular open-source smart-home hub; when you connect a printer to it, keep the local-network rules above in mind and prefer integrations that talk to the printer locally.
G-code post-processing
Slicers can run scripts on the finished G-code, passing the file path as an argument. Typical uses: insert color-change or pause commands at specific layers, embed a thumbnail, rewrite arc commands, add timestamps or compress the file. Scripts are plain programs (often Python) that read the file, modify lines and save it back.
# add_comment.py: a minimal post-processing script
import sys
path = sys.argv[1]
with open(path, "r", encoding="utf-8") as f:
lines = f.readlines()
out = []
for line in lines:
out.append(line)
if line.startswith(";LAYER_CHANGE"):
out.append("; layer marker inserted by script\n")
with open(path, "w", encoding="utf-8") as f:
f.writelines(out)
A post-processing script is a program running on your computer. Use only scripts you trust or have read, test them on a copy of the file, and keep the original. Closed printers may reject modified .gcode.3mf packages that fail the checksum or signature check; this is normal and not a printer fault.
Editing start and end G-code safely
Slicer profiles include machine start G-code, machine end G-code and optional blocks for layer change, filament change and pause. Editing them lets you add a purge line, call a macro, change the park position, or start a fan. A safe approach:
- Copy the profile first. Never edit the only copy of a vendor preset.
- Change one thing at a time and keep a note of why.
- Check the preview and the first lines of the exported file to confirm your edit appears where you expect.
- Run a dry test with the nozzle high above the bed, or with the first moves observed closely, with a finger near the stop button.
- Mind the order: heat before probing or extruding; home before any absolute move; avoid
M109waits that stall the queue longer than needed. - Keep safety lines: do not remove temperature waits, thermal protection commands or the end-of-print heater-off.
- Use placeholders (variables) provided by the slicer instead of hard-coded temperatures, so one profile works for all filaments.
On Bambu Lab and other closed printers, start and end G-code contains tuned calibration, vibration, AMS or tool-change and homing routines that depend on the firmware version. Removing or reordering lines can skip safety checks, drag filament, crash the toolhead into the purge or cutting area, or leave the printer in an unknown state. If you must change something, use the slicer's documented customization fields, copy the vendor profile, make tiny changes and test with care. When in doubt, restore the default profile and ask the community or support.
Reading G-code to debug
When a print behaves unexpectedly, the G-code is the ground truth of what was asked. A few habits pay off:
- Search for the layer marker (
;LAYER_CHANGE,;Z:or similar) near the failure height and read the lines around it. - Check temperatures and fan: find the last
M104/M109andM106before the problem. - Look at feed rates (
F) of outer walls and bridges. A surprising speed often explains a quality issue. - Compare E per XY distance on lines that look under- or over-extruded: it should match the line-volume estimate from earlier in this page.
- Look for retractions and z-hops around stringing and blobs; they appear as negative and positive E moves.
- Use a viewer, such as the slicer preview or a standalone G-code viewer, to scrub the file visually, and read the raw text only for the layers that matter.
Find a long straight outer-wall line: divide its E value by its XY length. Multiply by the filament cross-section (2.405 mm² for 1.75 mm) to get the extruded cross-section area, and compare with line width × layer height. A match within roughly 10 % means flow settings are as intended.
Quick self-check
What does M109 S210 do that M104 S210 does not?
M104 sets the target and continues; M109 blocks until the temperature is reached.
Which is the safest way to remote-monitor a self-hosted printer from outside your home?
A VPN avoids exposing the printer to the internet.
What problem does pressure advance fix?
It adjusts extruder speed to compensate for nozzle pressure that lags behind motion.
You want to change the start G-code on a closed-firmware printer. What is the best approach?
Vendor sequences are tuned to the firmware; small, tested changes reduce the chance of crashes.
Key takeaways
- G-code is a plain list of moves and settings; reading it shows exactly what the printer was told to do.
- Firmware plans motion, controls heaters and adds features such as pressure advance, input shaping and bed mesh; families differ in openness and tuning depth.
- Klipper moves configuration into editable text files and macros; Bambu trades openness for low effort.
- Segment your network, keep firmware updated, never expose printers directly to the internet, and guard access codes.
- Edit start and end G-code in small, tested steps, and treat closed-printer sequences as read-only unless you know exactly what you are doing.
Back to slicers, starting profiles and files and meshes. For printer-specific details, see X2D settings and profiles, troubleshooting and maintenance.