Use the Motion Control core as an XYZ positioning stage for a sampler, camera rig, test fixture or measuring system. Python sends a move, waits for it to finish, reads a separate sensor, then moves to the next position. grblHAL handles motion, while Python controls the experiment. Connect the sensor to your computer through USB, a network or its vendor's library.
Use grblHAL firmware for this guide. If you installed ESPHome for Home Assistant, restore grblHAL before continuing.
Consider using Python through Ooznest Control. See Ooznest Control: API and MCP Server — Using Python. This approach requires Ooznest Control to be running and connected to the controller. Python can load, run and monitor jobs through the MCP server's HTTP API while Ooznest Control manages the controller connection, G-code queue, acknowledgements, pause/resume/stop, alarms, errors and job-completion checks. You can focus your Python code on positioning sequences, sensor readings and recording results, with the job also visible in Control. No AI assistant is required.
The direct USB/TCP examples below provide a basic sender. You are responsible for maintaining or extending its connection handling, streaming and recovery logic for your project.
The job API additions are pending release. See the linked guide for the required app/backend and MCP server versions before choosing this approach.
Coordinates are in millimetres relative to G54. Check the positions and clearance height for your fixture before running any movement commands, and keep a hardware stop available. The examples assume positive Z moves upwards.
Install Python, then download the Python examples (.zip) and extract them into C:\examples (or a folder of your choice).
The download includes USB and network connections, a CSV sampler, a G-code file streamer, a terminal status panel and sample data.
On Windows, open C:\examples in File Explorer, right-click an empty area and choose Open in Terminal. On macOS or Linux, open a terminal in the folder containing the examples.
Type the following command in the terminal and press Enter to install pySerial:
python -m pip install pyserial
On Windows, use
pyinstead ofpythonif needed. On macOS or Linux, usepython3ifpythonis not found—for example,python3 -m pip install pyserial. Use the same command name for all Python commands in this guide. The examples use the includedmotion_core.pyfile.
Choose how Python will communicate with the Motion Control core: through a USB serial port, or over Wi-Fi or Ethernet using its IP address and TCP port. Identify the connection details below, then use the matching option when running a script. Use one connection method at a time; the same scripts support all three.
| Connection | What to do |
|---|---|
| USB serial |
|
| Wi-Fi / Ethernet |
|
| Connection Method | Option | Example |
|---|---|---|
| USB Serial on Windows | --serial PORT |
--serial COM11 |
| USB Serial on macOS | --serial PORT |
--serial /dev/cu.usbmodem1101 |
| USB Serial on Linux | --serial PORT |
--serial /dev/ttyACM0 |
| USB speed; default 115200 | --baud RATE |
--serial COM11 --baud 115200 |
| Wi-Fi or Ethernet | --ip ADDRESS |
--ip 192.168.0.55 |
| Network Telnet port; default 23 | --tcp-port PORT |
--ip 192.168.0.55 --tcp-port 2323 |
Do not combine
--serialand--ip. For network connections, use the Motion Control core's IP address, not your computer's.
The script below checks the connection status without moving the machine. It is included in the examples as check_connection.py.
import argparse
from motion_core import MotionCore, add_connection_arguments, connection_address
parser = argparse.ArgumentParser()
add_connection_arguments(parser)
args = parser.parse_args()
with MotionCore(connection_address(args), baudrate=args.baud) as core:
print(core.status())
Run check_connection.py using the connection option from the table above and your Motion Control core's port or IP address. For example:
python check_connection.py --serial COM11
The result is the Motion Control core's status, such as <Idle|MPos:...>.
Save the following example as move_and_measure.py.
The example
read_sensor()function returns 123.4 as a placeholder. Replace the example sensor function with your instrument's Python API.
Adjust the positions and clearance height to suit your machine and fixture before running this example.
import argparse
import time
from motion_core import MotionCore, add_connection_arguments, connection_address
def read_sensor():
return 123.4 # Replace with your instrument's Python API.
parser = argparse.ArgumentParser()
add_connection_arguments(parser)
args = parser.parse_args()
with MotionCore(connection_address(args), baudrate=args.baud) as core:
core.command("G21 G90 G94 G54")
core.move(z=5, feed=200)
core.move(x=10, y=10, feed=600)
core.move(z=-2, feed=100)
time.sleep(0.25)
print(read_sensor())
core.move(z=5, feed=200)
Run move_and_measure.py using the connection option from the table above and your Motion Control core's port or IP address. For example:
python move_and_measure.py --serial COM11
move() waits for completion before returning. Feed rates are mm/min, so F600 is 10 mm/s. Lifting Z, travelling in XY and lowering Z as separate moves avoids a diagonal sweep through your samples; the clearance height still has to be suitable for your fixture.
grblHAL queues motion. A move's ok response confirms that the command was accepted; the movement may still be running.
The MotionCore class is defined in the downloaded motion_core.py file and imported by the example scripts. Every call to core.move() automatically calls wait(), which sends G4 P0 and then checks that the Motion Control core reports Idle.
The delay after core.move() in the measurement example is only for sensor settling. Open-loop position reports come from commanded steps; use separate position feedback if your experiment requires it.
The script below visits positions from a CSV file and records sensor readings. It is included in the examples as sample_positions.py.
"""Visit a CSV of G54 millimetre positions; record a simulated sensor value."""
import argparse
import csv
import math
import time
from datetime import datetime, timezone
from motion_core import MotionCore, add_connection_arguments, connection_address
def read_sensor():
# Replace with your separate sensor's USB/network/vendor Python API.
return 123.4 # Simulated measurement, not data from the Motion Control Core.
def load_positions(path, safe_z):
with open(path, newline="", encoding="utf-8-sig") as source:
rows = list(csv.DictReader(source))
if not rows:
raise ValueError("CSV has no positions")
points = []
for row in rows:
x, y, z = (float(row[a]) for a in ("x", "y", "z"))
if not all(math.isfinite(v) for v in (x, y, z)) or z > safe_z:
raise ValueError("Invalid coordinate or sample Z above clearance Z")
points.append((row["sample"], x, y, z))
return points
def main():
parser = argparse.ArgumentParser()
add_connection_arguments(parser)
parser.add_argument("csv_file")
parser.add_argument("--safe-z", type=float, required=True, help="Verified G54 clearance height, mm")
parser.add_argument("--output", default="measurements.csv")
parser.add_argument("--run", action="store_true", help="Actually move the machine")
args = parser.parse_args()
if not math.isfinite(args.safe_z):
parser.error("safe-z must be finite")
points = load_positions(args.csv_file, args.safe_z)
for point in points:
print(point)
if not args.run:
print("Preview only. Verify clearance, G54 origin and travel, then add --run.")
return
# Exclusive creation prevents overwriting an earlier results file.
with open(args.output, "x", newline="", encoding="utf-8") as output:
writer = csv.writer(output)
writer.writerow(["utc", "sample", "x_commanded", "y_commanded", "z_commanded", "simulated_reading"])
output.flush()
with MotionCore(connection_address(args), baudrate=args.baud) as core:
core.command("G21 G90 G94 G54")
for sample, x, y, z in points:
core.move(z=args.safe_z, feed=200)
core.move(x=x, y=y, feed=600)
core.move(z=z, feed=100)
time.sleep(0.25) # Let the sensor settle after motion has completed.
value = read_sensor()
writer.writerow([datetime.now(timezone.utc).isoformat(), sample, x, y, z, value])
output.flush()
core.move(z=args.safe_z, feed=200)
if __name__ == "__main__":
main()
Edit positions.csv in a text editor or spreadsheet and save it as CSV:
sample,x,y,z
A1,10,10,-2
A2,20,10,-2
A3,30,10,-2
Run sample_positions.py using the connection option from the table above and your Motion Control core's port or IP address. Specify the CSV file and a verified clearance height with --safe-z. For example:
python sample_positions.py --serial COM11 positions.csv --safe-z 5
This previews the positions without opening a connection or moving the machine. Check the fixture, G54 origin, coordinates and clearance height before adding
--runto the command to start the sequence.
The script raises Z, moves XY, lowers Z, waits, reads the sensor, writes a row and retracts. The example read_sensor() function returns 123.4 as a placeholder. Replace the example sensor function with your instrument's Python API. Results go to measurements.csv, with UTC time, sample ID, commanded XYZ and the reading. Use --output new-results.csv for another run; existing result files are not overwritten.
The script below streams a G-code file to the Motion Control core. It is included in the examples as stream_file.py.
"""Conservative send-one-line/wait-for-ok streaming of a plain G-code file."""
import argparse
import re
from pathlib import Path
from motion_core import MotionCore, add_connection_arguments, connection_address
def load_blocks(path):
blocks = []
for number, raw in enumerate(Path(path).read_text(encoding="ascii").splitlines(), 1):
text = re.sub(r"\([^()]*\)", "", raw.split(";", 1)[0]).strip()
if not text or text == "%":
continue
if any(c in text for c in "()!?~$") or len(text) > 70:
raise ValueError(f"Line {number}: use plain blocks <=70 characters, no nested comments or system/realtime commands")
if any(ord(c) < 32 or ord(c) > 126 for c in text):
raise ValueError(f"Line {number}: control characters are not allowed")
blocks.append((number, text))
if not blocks:
raise ValueError("No G-code blocks found")
return blocks
def main():
parser = argparse.ArgumentParser()
add_connection_arguments(parser)
parser.add_argument("file")
parser.add_argument("--run", action="store_true")
args = parser.parse_args()
blocks = load_blocks(args.file)
if not args.run:
for number, block in blocks:
print(f"{number}: {block}")
print("Preview only; add --run after reviewing the complete path.")
return
with MotionCore(connection_address(args), baudrate=args.baud) as core:
for number, block in blocks:
print(f"Sending line {number}: {block}")
core.command(block)
core.wait()
print("File finished; controller is Idle.")
if __name__ == "__main__":
main()
Review demo.nc and adapt it to your machine. It visits two positions at a clearance height:
G21 G90 G94 G54
G1 Z5 F200
G1 X10 Y10 F300
G1 X20 Y10 F300
G1 Z5 F200
M2
Run stream_file.py using the connection option from the table above and your Motion Control core's port or IP address, followed by the G-code filename. For example:
python stream_file.py --serial COM11 demo.nc
This previews the G-code without moving the machine. Review the complete path and check it is suitable for your machine before adding
--runto the command to stream the file.
The streamer sends one line, waits for ok, then sends the next. It finishes with the same motion-completion check. This executes the file from the computer; it does not upload it to the SD card.
The example accepts plain ASCII blocks up to 70 characters after removing simple comments. It stops on errors, alarms, unexpected resets or a timeout. It is deliberately conservative, so short-segment jobs may run less smoothly than with a full sender. Use Ooznest Control for complex CNC jobs, tool-change workflows or jobs requiring operator prompts. Do not use this example for M0/M6 pause workflows.
The script below displays the Motion Control core's live status in a terminal panel. It is included in the examples as status_ui.py.
"""Read-only curses status panel with best-effort feed hold; no automatic resume."""
import argparse
import curses
import time
from motion_core import MotionCore, add_connection_arguments, connection_address
def panel(screen, core):
screen.nodelay(True)
last = 0
report = "Connecting..."
while True:
key = screen.getch()
if key in (ord("q"), ord("Q"), 27):
core.hold()
return
if key == ord(" "):
core.hold()
if time.monotonic() - last >= 0.3:
report = core.status()
last = time.monotonic()
screen.erase()
height, width = screen.getmaxyx()
lines = ["Motion Control Core | grblHAL", "SPACE: feed hold Q: hold and quit", report,
"Read-only monitor. Resume/recovery uses your normal sender."]
for row, text in enumerate(lines[:max(0, height - 1)]):
screen.addnstr(row, 0, text, max(0, width - 1))
screen.refresh()
time.sleep(0.05)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
add_connection_arguments(parser)
args = parser.parse_args()
with MotionCore(connection_address(args), baudrate=args.baud) as controller:
curses.wrapper(panel, controller)
On Windows, install the curses package before running the panel:
python -m pip install windows-curses
Run status_ui.py using the connection option from the table above and your Motion Control core's port or IP address. For example:
python status_ui.py --serial COM11
| Key | Action |
|---|---|
| Space | Request feed hold. |
| Q or Esc | Request feed hold and close the panel. |
The panel refreshes the raw status report and does not send moves or automatically resume. It demonstrates a terminal interface you can extend with sample selection and instrument readings. Quit it before running the sampler or streamer.
The connection code in motion_core.py stops sending commands on an error or timeout and requests feed hold if the connection is still available.
Feed hold pauses the queue; it does not cancel it. Inspect the job and recover through your normal sender rather than retrying an uncertain command. Investigate and resolve any alarms before moving the machine.
The default command timeout is 120 seconds; use MotionCore("COM11", timeout=300) for a longer operation.
| Project | Python's job |
|---|---|
| Lab sampler | Visit tube positions, control a separate pump and log sample IDs. |
| Surface scan | Move a distance sensor through a grid and save measurements to CSV. |
| Camera inspection | Position a camera, capture an image and name it by location. |
| Test fixture | Move a probe between test points and read a separate meter. |