8
$\begingroup$

i have the following code to receive serial data from arduino and rotate the cube...

import bpy
from bpy import context
import serial
from time import sleep
from bpy.props import IntProperty, FloatProperty


value = 0
i=0
j=0
degree = 0
ser = serial.Serial("COM77", 9600)

class ModalOperator(bpy.types.Operator):
  bl_idname = "object.modal_operator"
  bl_label = "Simple Modal Operator"

x = IntProperty()

def modal(self, context, event):
   if ser.inWaiting()>0 :
        value = ser.read(2)
        print(value)
        self.x = int(value)
        print(self.x)
        self.x += 1000
        degree = self.x * 3.14/180
        print(degree)
        bpy.context.object.rotation_euler[0] = degree

   if event.type  == 'LEFTMOUSE':
       return {'FINISHED'}
       ser.close()

   return {'RUNNING_MODAL'}

def invoke(self, context, event):
    if context.object:

        print("hi")

        context.window_manager.modal_handler_add(self)
        return {'RUNNING_MODAL'}
    else:
        self.report({'WARNING'}, "No active object, could not finish")
        return {'CANCELLED'}


def register():
   bpy.utils.register_class(ModalOperator)


def unregister():
   bpy.utils.unregister_class(ModalOperator)


   register()

# test call

bpy.ops.object.modal_operator('INVOKE_DEFAULT')

the code under invoke function executes immediately when i run the script..but the statements under modal function executes only if i move the mouse or press any key...

I think it doesn't consider incoming serial data as an event...

i want the serial data to be read as and wen it comes...not only wen the mouse is moved..

Is there any way to check serial event.... like 'MOUSE_MOVE' or 'LEFTMOUSE'....

$\endgroup$
9
$\begingroup$

What you are looking for probably, is running a timer alongside the modal operator, so you can check the serial data whenever the operator gets executed with a timer event.

There already is a code template in blender, that shows you how to do this. Look for the Template menu entry at the bottom of the Text Editor and select Python > Operator Modal Timer

The relevant code is in the execute function:

wm = context.window_manager
self._timer = wm.event_timer_add(0.1, context.window)

The 0.1 controls the time interval between successive timer events in seconds.

Then you can check for a timer event in modal with:

if event.type == 'TIMER':

And for cleanup in the cancel function:

wm = context.window_manager
wm.event_timer_remove(self._timer)
| improve this answer | |
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.