[Solved][B2.55] 'non-blocking' connection w/ Arduino & pyserial

Hey guys,

I’m trying to connect my Arduino board with Blender 2.55 and pyserial. When I start my python script, I read data send by the Arduino board in the terminal but Blender itself is freezed until I unplug my Arduino board… Btw, I don’t want to use BGE, I’d like to get data for animating purpose. Any ideas ?


import serial, bpy

ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0)

while 1:
    value = ser.readline()
    v = value.decode('utf8')
    print(v)

Late reply, I almost forgot to close the topic :eek:
So mindrones helped me out on #blendercoders… He suggested me to look at Threads, here is a basic setup that works for me:


import threading
import serial

class SerialThread (threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run (self):
        ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=50)
        while 1:
            value = ser.readline()
            v = value.decode("utf-8").rstrip('
')
            print(int(v))
            
SerialThread().start()

And the Arduino sketch (just a LED w/ a potentiometer - the board output the analog value of the potentiometer):


int sensorPin = 0;
int ledPin = 9;
int sensorValue = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  sensorValue = analogRead(sensorPin) / 4;
  analogWrite(ledPin, sensorValue);
  Serial.println(sensorValue);
  delay(50);
}

Note that the timeout for the serial connection must match the timeout of the loop function (50ms here).