1

I would like to read the data printed by an Arduino in Blender but the Arduino is reset each time Blender reads the data.
Here is my Blender code:

import bge
import mathutils
import serial

from math import pi
def Player():
cont = bge.logic.getCurrentController()
obj = cont.owner

serialport = serial.Serial('COM3', 115200)

# tell Arduino to send values
serialport.write('a'.encode('ascii'))

# read a line from the serial port
line=serialport.readline()

# Pi radians = 180 degrees so, since Arduino sends values between 0 and
# 255, we devide by 255 in order to spread the 255 over pi radians (from
# -90 to +90 degrees).


# There is one angle for each axis, and there are 3 axes.
Angles=[0.0,0.0,0.0]  # inicial angles for X, Y and Z axes
AnglesNumber=3       # number/quantity of angles/axes
for i in range(AnglesNumber):
     Angles[i] = Angles[i] + (float)(line.split()[i])
     # And we convert each value to radians (from -pi/2 to +pi/2).

mat_rot_z = mathutils.Matrix.Rotation(Angles[0], 3, 'X')
mat_rot_x = mathutils.Matrix.Rotation(Angles[1], 3, 'Y')
mat_rot_y = mathutils.Matrix.Rotation(Angles[2], 3, 'Z')

obj.localOrientation = mat_rot_x * mat_rot_y * mat_rot_z
J Sargent
  • 19,269
  • 9
  • 79
  • 131
evilcursed
  • 11
  • 1

1 Answers1

1

You create a new Serial each time you call that script.

It is better to create it once and communicate with the connection as long as it is established.

Unfortunately I can't provide you with working code due to non-existence environment.

Connecting

One script gets executed and establishes the connection once:

serial = serial.Serial('COM3', 115200)
owner["serial"] = serial 

Communicating

A second script handles communication (polls for data) running at each single frame.

serial = owner["serial"]
serial.write('a'.encode('ascii'))
line = serial.readline()
...

Combined

Due to the strong dependency between connecting and communicating, you might want to combine both operations:

serial = owner.get("serial");
if not serial:
    serial = serial.Serial('COM3', 115200)
    owner["serial"] = serial  

serial.write('a'.encode('ascii'))
line = serial.readline()
...
Monster
  • 8,178
  • 1
  • 11
  • 27