Python and global variables - I think

Yes it’s python time again and this is where I discover I’ve forgotten the little I managed to learn last time I used it.

My problem… I am trying to use an Ultrasonic ranging sensor as input to Blender. For those interested it is the SRF02 sensor which is connected through the USB-I2C unit from Robot Electronics.

I got it to work but not very well. The USB-I2C pretends to be a comm port and you have to open the port and set it up before using it. I am using pySerial to talk to it.

I have found that setting up the port seems to stop blender in its tracks briefly so I want to do it once, when the BGE is initialised.

My trouble is…

If I open and set up the port with one script, how do I address the port with another script. I have tried all sorts of things

the port is initialised by this:

import serial
ser = serial.Serial(2, 19200, timeout = 1 , bytesize=8, parity=‘N’, stopbits=2) #comm 3
then you can address the port like this:

ser.write(chr(0x02))
But if I want to write to the port from another script thats actuated at a different time it doesn’t work.

I think its because I don’t understand what type of variable “ser” is here… and don’t know how to reference it elsewhere…

Did that make sense? Any help gratefully received.

ser is a Serial() instance, you could store it in GameLogic

eg:
in serial_init.py

import serial
import GameLogic
GameLogic.ser = serial.Serial(2, 19200, timeout = 1 , bytesize=8, parity='N', stopbits=2)

in serial_act.py

import GameLogic
GameLogic.ser.write(chr(0x02)) 

Before somebody says that the import GameLogic is not needed, know that we are removing the autoimporting in future versions

Thanks Cyborg_ar
Its now working smooth as silk!