Reputation: 77
I have an animation (just an object that changes positions) created with blender and I would like to start playing the animation when I push a button at the arduino. I am new to python and trying to understand it.
I did the connection with the arduino and it works.
Here is the python code:
#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---")
When I hit "Run Script" everything seem to work I can see the connection and next position messages appear but my Sphere is not moving. Can someone explain to me why the sphere is not moving and how can I achieve starting the animation when I push the button? What I have to add to make this happen?
Upvotes: 0
Views: 1358
Reputation: 7079
While the script works, the result isn't what you seem to want. The script simply creates a number of keyframes for the sphere. While it reads (once) the serial input it doesn't do anything with that, so there is no response to the button push.
To respond to input from the arduino, you need to constantly read the serial input and choose an action based on that input.
In theory what you want is something like:
while True:
x = serial.read(size=1)
if x == 'p':
# this will play/pause
bpy.ops.screen.animation_play()
The drawback is that that loop will take over blender and prevent any window updates. To get around that you can put the steps from the loop into a modal operator, blender will repeatedly call the modal method in the operator and update the screen in between each call.
Starting with the modal operator template included with blender, change the modal method to something like
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'}
You can find some more complete examples of interacting with an arduino at blender.stackexchange
Upvotes: 0