Pyserial and Arduino every Time new Connect problem I have a potentiometer and I want this to change the location of my cube. My script run is on the cube, connected to an "Always" actuator with True Toggle.

My problem is this line:

ser = serial.Serial('COM6',9600, timeout=1)


The script throws an error: ser is not defined

This line is read every Time, so my arduino must connect every Time. I need to perform a new connect every second, but I want float move.

So I try this, because the serial line is only executed once:

import serial
import time
import bge
import bpy

cont = bge.logic.getCurrentController()
ob = bpy.data.objects["Cube"]
scene = bge.logic.getCurrentScene().objects["Cube"]
own = cont.owner
PSerial=own['SerialVerbunden']

print (PSerial)
if (PSerial==False):
    ser = serial.Serial('COM6',9600, timeout=1)
    time.sleep(1)
    count = 0
    own['SerialVerbunden']=True




a = int(ser.readline().strip())
print (a)
count = count + 1
scene.worldPosition = [a, 0, 0]
ob.location = scene.worldPosition
ob.keyframe_insert(data_path="location", frame=count)


The script throws the error mentioned above: ser is not defined.

Yes this is true, because it is loading and at the end it forgets.
The variable count have the same problem. It can't count.
But how I can solve it?
If I write a while loop, so I cant see my cube is moving, Blender freezes.
I strongly suggest you separate connecting from communication. Do not forget you should execute a closing when the connection is not needed anymore.

Basically you need this three operations in this order over multiple frames:


establish a connection
communicate (receive/send) via connection
close connection [which seams not to apply at serial)


I suggest to implement it that way:

import serial
import bge

INTERNAL_PROPERTY_CONNECTION = "_connection"

listener = bge.logic.getCurrentController().owner

connection = listener.get(INTERNAL_PROPERTY_CONNECTION)
if not connection:
    connection = serial.Serial('COM6',9600, timeout=0)
    listener[INTERNAL_PROPERTY_CONNECTION] = connection

# your communciation
a = int(connection.readline().strip())
cube = bge.logic.getCurrentScene().objects["Cube"]
cube.worldPosition.x = a