Blender arduino problem, sensor reading stops or slows down after a while

(Kyra) #1


I’m trying to rotate an object in blender in real time, using sensor readings send by an arduino. I send the data via pyserial and use a timed modal operator in order not to block blender. My setup is the following:

import bpy
import serial
import time
import mathutils

class op(bpy.types.Operator):
    """Operator which runs its self from a timer"""
    bl_idname = "object.op"
    bl_label = "Modal Timer Operator"

    _timer = None
    ser = None
    obj = None
    def __init__(self):
        self.ser = serial.Serial("/dev/cu.Devicename",57600, timeout=1)
        self.ser.write('x'.encode('ascii'))     #tell the arduino to begin sending data
        self.obj =['cube']
    def modal(self, context, event):
        if event.type in {'RIGHTMOUSE', 'ESC'}:
            return {'CANCELLED'}

        if event.type == 'TIMER':
            try :
                x = self.ser.readline().decode().strip('
                # .... noramlly there is a lot of code here to properly rotate the cube
            except ValueError:
                error = "SomeError"  
        return {'PASS_THROUGH'}

    def execute(self, context):
        wm = context.window_manager
        self._timer = wm.event_timer_add(0.1, context.window)
        return {'RUNNING_MODAL'}

    def cancel(self, context):
        wm = context.window_manager
        return {'CANCELLED'}

def register():

def unregister():

if __name__ == "__main__":

This works, but only sometimes. Sometimes it works just fine, but then after like five minutes or so, it gets really slow. Other times, it is slow from the beginning, and by slow I mean about 5 seconds delay. I don’t understand what could cause the problem.
I’ve ruled out that the Arduino side is the problem, because using the Arduino IDE only, it works all the time.

Does anyone have any ideas why such an irregular problem may occure, especially given that it works sometimes?

(paulmelis) #2

Did you try replacing the serial stuff by something that merely generates random data (in the form that you need)? This might help in determining if the issue is related to the Blender event loop, or has something to do with the serial module.

(Kyra) #3

Thank you for responding. I figured it out. Adding while self.ser.in_waiting !=0: after if event.type == ‘TIMER’: solves it.