Serial input response from arduino in builder

OS (e.g. Win10): Win10
PsychoPy version (e.g. 1.84.x): V2021.2.3
Standard Standalone? (y/n) : yes / Builder

Hello,
I would like to create a button response with arduino. It works with the coder but not with the builder.
I try to insert the following code in the code component of the Builder but i don’t know if it is possible and how to do it.
The subject has to react to a basic visual stimulus with the button response emulated with an arduino.
Thanks for your help!

Here is my python code which deal with input from arduino:

import serial
import time
from psychopy.hardware import keyboard
from psychopy import core

kb = keyboard.Keyboard()

port = serial.Serial("COM3", 19200, timeout=1)
time.sleep(2)
port.flushInput() # Clear buffer serial port
DI = port.read()
print(DI)
inc=0
start=time.time()
tps=[]
rep_list=[]
rt_list=[]
t0=0  

while True:   
    DI = port.read()
    kb.clock.reset()  # when you want to start the timer from
    keys = kb.getKeys(['q'], waitRelease=True)
    
    ####### Define here PsychopY stimuli (disp img for ex)
    
    
    if 'q' in keys:
        port.close()
        print(rt_list)
        core.quit()  
    
    elif DI == b'\x04':
        rep_list.append('blue')
        rt=time.time()-start
        rt_list.append(rt)
        print('blue')
    elif  DI == b'\x07':
        rep_list.append('yellow')
        rt=time.time()-start
        rt_list.append(rt)
        print('yellow')
    elif  DI == b'\x08':
        rep_list.append('black')
        rt=time.time()-start
        rt_list.append(rt)
        print('black')
    elif  DI == b'\x12':
        rep_list.append('red')
        rt=time.time()-start
        rt_list.append(rt)
        print('red')
    elif  DI == b'\x13':
        rep_list.append('white')
        rt=time.time()-start
        rt_list.append(rt)
        print('white')
port.close()

You should be able to break up the code and add it to a custom code component in Builder. Assuming you only need to check for data from the arduino from one routine within your experiment, add a code component to that routine with something like the following:

In “Begin Experiment” tab

import serial
aport = serial.Serial("COM3", 19200, timeout=1)
aport.flushInput() # Clear buffer serial port

In the “Each Frame” tab

DI = aport.read()
if DI:
    # received data from arduino serial
    # do what you want with it
    print("Rx: ", DI)

In the “End Experiment” tab:

aport.close()

You may also want to flush out any input at the beginning of the routine (in the Begin Routine tab of the code component) if you do not want to get data that was received prior to the routine starting.

Hello,
Thanks it work!
Now i try to record the response time from the button connected to my arduino in the data file…
I have good hope!
Bye