从Arduino到搅拌机的串行信号

时间:2019-06-03 16:03:11

标签: python animation scripting arduino blender

我有一个用Blender创建的动画(只是一个改变位置的对象),当我按下arduino上的一个按钮时,我想开始播放动画。我是python的新手,正试图了解它。

我与arduino建立了连接,并且可以正常工作。

这是python代码:

#part of the code was found from Olav3D tutorials on youtube"
import serial
import bpy

try:
    serial = serial.Serial("COM3", 9600, timeout = 10)
    print("Connection succeed")
except:
    print("Connection failed")

positions = (5,0,-2), (0,0,2), (0,0,5), (0,0,1), (0,0,7), (0,0,5)


ob = bpy.data.objects['Sphere']
frame_num = 0

x = serial.read(size=1)

for position in positions:
        bpy.context.scene.frame_set(frame_num)
        ob.location = position
        ob.keyframe_insert(data_path="location",index=-1)
        frame_num+=20
        print("Next position---")

当我点击“运行脚本”时,一切似乎都可以正常工作,我可以看到连接并出现下一个位置消息,但是我的球体没有移动。有人可以向我解释为什么球体不移动以及如何在按下按钮时实现动画的开始吗?我必须添加些什么才能使这种情况发生?

1 个答案:

答案 0 :(得分:0)

尽管脚本可以运行,但结果却不是您想要的。该脚本仅为该球体创建了多个关键帧。在读取(一次)串行输入时,它不会执行任何操作,因此对按钮的按下没有响应。

要响应来自arduino的输入,您需要不断读取串行输入并根据该输入选择一个操作。

理论上,您想要的是这样的:

while True:
    x = serial.read(size=1)
    if x == 'p':
        # this will play/pause
        bpy.ops.screen.animation_play()

缺点是该循环将接管搅拌器并阻止任何窗口更新。为了解决这个问题,您可以将循环中的步骤放入模态运算符中,blender将在运算符中反复调用模态方法,并在每次调用之间更新屏幕。

从搅拌机随附的modal operator template开始,将模态方法更改为类似的

def modal(self, context, event):
    x = serial.read(size=1)
    if x == 'p':
        # this will play/pause
        bpy.ops.screen.animation_play()
    if x == 's':
        bpy.ops.screen.animation_cancel()
    if event.type == 'ESC':
        # press esc to stop the operator
        return {'CANCELLED'}
    return {'RUNNING_MODAL'}

您可以在blender.stackexchange

上找到一些与arduino交互的更完整的示例。