Send trigger codes based on stimulus status

Hello,

I am trying to send trigger codes based on the status of my stimulus (1 for stim onset and 0 for stim offset) in the code component of builder. I know that my port is working well and is sending trigger codes each frame with stimulus onset. However, whenever I include port.write inside a conditional statement for when a stimulus starts/ends, it does not read it. Here’s my current code:

##begin exp
import serial
port = serial.Serial(“COM4”, baudrate = 115200)
if not port.isOpen():
port.open()
triggerN = 0

##begin routine
onset_trigger_sent = False
offset_trigger_sent = False
triggerN == 0

##each frame
if click_sound.status == STARTED and not onset_trigger_sent:
triggerN = 1
port.write(triggerN.to_bytes(length = 1, byteorder = ‘little’))
onset_trigger_sent = True

if click_sound.status == FINISHED and not offset_trigger_sent:
triggerN = 0
port.write(triggerN.to_bytes(length = 1, byteorder = ‘little’))
offset_trigger_sent = True