Created
May 30, 2025 00:49
-
-
Save jdbrice/f4897d7dfb739d52c12c93bbc0e0dde4 to your computer and use it in GitHub Desktop.
Serial connection and g-code sending to CNC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from serial import Serial | |
from serial.tools import list_ports | |
from tqdm import tqdm | |
from contextlib import closing | |
# TODO: arg parse for port and baudrate | |
# TODO: arg parse for X/Y coordinates and to select initial home machine, just unlock, or none (if machine is already unlocked) | |
x = 20 | |
y = 20 | |
z=0 | |
codes = [ | |
"$X ; Unlock the machine (if locked)", | |
"G92 X0 Y0 Z0 ; Set current position as zero" | |
"G90 ; Absolute positioning mode", | |
"G21 ; Set units to millimeters", | |
"G17 ; Select XY plane", | |
f'G1 X{x} Y{y} Z{z} F1000 ; Move to initial position (X={x}, Y={y})', | |
] | |
# codes = [ "$H"] | |
print("Codes to be sent:") | |
for code in codes: | |
print(f" {code}") | |
def list_serial_ports(): | |
return [p.device for p in list_ports.comports()] | |
def send_and_wait_ok(ser, line, timeout=15): | |
ser.write((line.strip() + '\n').encode()) | |
deadline = time.time() + timeout | |
while time.time() < deadline: | |
resp = ser.readline().decode('ascii', errors='ignore').strip() | |
if resp: | |
print(f"<- {resp}") | |
if resp.lower().startswith('ok'): | |
return True | |
raise RuntimeError(f"No OK received for: {line}") | |
if __name__ == '__main__': | |
ports = list_serial_ports() | |
print("Available ports:", ports) | |
port = '/dev/tty.usbmodem11101' # pick one from the list | |
try: | |
with closing(Serial(port, baudrate=115200, timeout=0.1)) as s: | |
# wake/reset & consume banner | |
s.write(b"\r\n\r\n") | |
time.sleep(2) | |
while True: | |
line = s.readline().decode('ascii', errors='ignore').strip() | |
if not line: | |
break | |
print(f"<- {line}") | |
for code in tqdm(codes, unit=" cmd", ncols=100): | |
if not code.strip() or code.strip().startswith(';'): | |
continue | |
tqdm.write(f">> {code}") | |
send_and_wait_ok(s, code) | |
print("\nAll codes have been sent successfully. 🎉") | |
except Exception as e: | |
print("Serial error:", e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment