News Tutorials

Friday Facts 21: Python to Makelangelo

Makelangelo a great way to tinker with algorithmic art, procedural art, generative code, and more. Python is a popular language for building generative art. To send G-code to a Makelangelo plotter over a serial connection using Python, you can use the pyserial library. Here is an example script that demonstrates how to establish the connection and send G-code commands.

First make sure you have pyserial installed.

pip install pyserial

Then, open a serial connection to a USB connected Makelangelo.

import serial
import time

def send_gcode(port, baudrate, commands):
    try:
        # Open the serial port
        with serial.Serial(port, baudrate, timeout=1) as ser:
            time.sleep(2)  # Wait for the connection to establish

            # Send each G-code command
            for command in commands:
                ser.write((command + '\n').encode('utf-8'))
                time.sleep(0.1)  # Short delay between commands
                response = ser.readline().decode('utf-8').strip()
                print(f"Response: {response}")

    except serial.SerialException as e:
        print(f"Serial error: {e}")

# Define the G-code commands to send
gcode_commands = [
    "G28",  # Home all axes
    "G1 X10 Y10 Z0 F3000",  # Move to (10, 10, 0) at 3000 mm/min
    "G1 X20 Y20 Z0 F3000",  # Move to (20, 20, 0) at 3000 mm/min
    # Add more G-code commands as needed
]

# Send G-code commands to Makelangelo plotter
send_gcode('/dev/TTY0', 250000, gcode_commands)

Explanation

  1. Import serial and time: Import necessary modules for serial communication and timing.
  2. Define send_gcode function: This function takes the serial port, baudrate, and a list of G-code commands as arguments. It opens the serial port, sends the G-code commands one by one, and prints the responses from the plotter.
  3. Open the serial port: Using a with statement to ensure the port is properly closed after use.
  4. Send commands: Iterate through the list of G-code commands, send each command, and print the response from the plotter.
  5. Define G-code commands: A list of G-code commands to be sent to the plotter.
  6. Call send_gcode: Pass the serial port, baudrate, and G-code commands to the function.

Ensure that the port (/dev/TTY0) and baudrate (250000) match your Makelangelo plotter’s configuration. Adjust the G-code commands as needed for your specific tasks.

Final thoughts

You might also be interested in related plotter projects like vpype and vsketch.