1
$\begingroup$

This is my first time using Blender. I have made a CPLD device that can transmit ASCII binary when pressing push buttons. It has been tested to work well on Spyder IDLE using pyserial.

However, whenever I run this simple test to print input from COM4 in Blender (Text.py), it hangs when I press P to run the Blender game.

import serial, bge, bpy

ser = serial.Serial()
ser.baudrate = 115200
ser.port = "COM4"
ser.close()
ser.open()

def MoveCube():
    cont = bge.logic.getCurrentController()
    obj = cont.owner
    a = ser.read()
    if (a != b''):
        print (a.decode('utf-8'))
        obj.applyMovement([3,0,0], False) #just a random testing

def execute_after_game(scene):
    ser.close()

bpy.app.handlers.game_post.append(execute_after_game)

enter image description here

What is going on? Thanks in advance.

$\endgroup$

migrated from stackoverflow.com Apr 24 at 5:39

This question came from our site for professional and enthusiast programmers.

2
$\begingroup$

From the pySerial API for read():

With no timeout it will block until the requested number of bytes is read.

Blender only has one thread, so blocking this thread will cause the game engine to hang as it waits for the read() command to finish.

Right now I can think of two possible solutions:

  1. Set a timeout using timeout = x. Again from the API:

    Possible values for the parameter timeout which controls the behavior of read():

    • timeout = None: wait forever / until requested number of bytes are received
    • timeout = 0: non-blocking mode, return immediately in any case, returning zero or more, up to the requested number of bytes
    • timeout = x: set timeout to x seconds (float allowed) returns immediately when the requested number of bytes are available, otherwise wait until the timeout expires and return all bytes that were received until then.
  2. Create another thread and execute MoveCube() in it. This will cause ser.read() not to be executed in the Game Engines main thread and thus it will not be blocked, but the newly created thread will be blocked.

As the first suggestion is simpler to implement and uses less resources, I'd prefer it.

On another note: the bpy module is Blender's API and not the Game Engine's API. So if you want to export your game and use it outside of Blender as a standalone, I'd recommend not using bpy at all, as it will not work. See this post for more information.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy