pythonpyserialg-code3d-printing

How to send one gcode command over USB?


I am trying to write a simple python script that sends a gcode command to my wanhao D9 motherboard printer, running Marlin. I am running the python script on a raspberry pi that is connected to the printer via USB.

import serial

ser = serial.Serial("/dev/ttyUSB0", 115200)
ser.write("G28\n")

I have read over 20 forum pages with simular problems and tried their answers such as changing the baud rate to 250000 and the following changes to the write function parameter:

ser.write("G28\r\n")
ser.write(b'G28\r\n')
ser.write(b'G28\n')
ser.write(b'G28')
ser.write("G28")

I have tried all these combinations, and I have also added:

time.sleep(5)

along with the relevant import statement for the time module at the top of my file. I added this line of code between my ser declaration and my ser.write function call.

I have also tried adding:

ser.close()

to see if that would make a difference but it has not, as I know this is best practice anyway.

No matter what combination of this code I used, when I run my python script my printer seems to restart (the screen changes from the home page to the opening wanhao logo and back to the home page)

I look forward to any help anyone can give me in regards to my code and what I may be doing wrong.


Solution

  • Adding an extra sleep period after my command fixed my issue. I can also now read back the initial set up feedback from the printer.

    My final code without this is:

    import serial
    import time
    
    ser = serial.Serial('/dev/ttyUSB0', 115200)
    
    time.sleep(2)
    ser.write("G28\r\n")
    time.sleep(1)
    ser.close()
    

    Thank you, to the users in this post for guiding me in the right direction Full examples of using pySerial package

    This code works for me, I hope someone else finds it useful in the future too.