Anytime Help Center

Controlling MUSE Serial Ports with Python Code

Rating

​The below Python code controls a serial port on a MUSE controller.  It contains code for configuring ports, sending and receiving strings, and reporting port errors.



from mojo import context

context.log.info('Sample Python program')


#Create objects for the controller (idevice) and touch panel (AMX-11241)
dvidevice = context.devices.get("idevice")
dvTP = context.devices.get("AMX-11241")


#Create a variable to access just the serial port
serialPort1 = dvidevice.serial[0]


#This creates a buffer for incoming serial strings, if a string is longer than 64 characters
#it will trigger multiple events, this allows building the string until a delimiter is reached
serialBuffer = ""


#As long as the idevice is online it will set the baud rate of the serial port
if(dvidevice.isOnline()):
    context.log.info("idevice online, setting baud rate.")
    serialPort1.setCommParams("9600",8,1,"NONE","232")


#This function processes incoming strings utilizing the serialBuffer variable declared above
#Once a carriage return is seen in the string it prints what has been received
def receiveString(event):
    global serialBuffer

    serialBuffer += event.arguments['data'].decode()
    
    if (serialBuffer.find("\r") >= 0):
        print(f"Full string: {serialBuffer}")
        serialBuffer = ""

serialPort1.receive.listen(receiveString)


#An example of sending an ASCII string from the serial port
def sendASCII(event):
    serialPort1.send("ASCII string\r".encode())
    
dvTP.port[1].button[1].watch(sendASCII)


#An example of sending a hexadecimal string from the serial port
def sendHEX(event):
    serialPort1.send("\x02 \x68 \x65 \x6c \x6c \x6f \x03 \x0d".encode())
    
dvTP.port[1].button[2].watch(sendHEX)


#An example of sending a mixed hex/ASCII string from the serial port
def sendMIX(event):
    serialPort1.send("\x02 Mixed string \x03 \r".encode())
    
dvTP.port[1].button[3].watch(sendMIX)


#This function is triggered by a fault detection in the serial port, it will print out the error 
def receiveFault(event):
    context.log.info(f"Serial port fault: {event.arguments['value']}".encode())

serialPort1.fault.listen(receiveFault)


# leave this as the last line in the Python script
context.run(globals())



Downloads

Product

 

Topic

Programming

Related Articles

Last modified at 3/20/2025 4:47 PM by PRO Knowledge Base
Top