Sending multiple triggers using a for loop within a code component

Psychopy version 2022.2.5
What are you trying to achieve?:
I’m able to send a single trigger within a routine using the code provided in the “sending triggers via serial port” help page, but id like to modify it to send 4 triggers while a sound component is playing. For now, I am just trying to get this to work within a 15 second-ish clip of the song.

This code is sending triggers to a thermal stimulator, where “L” triggers heat and “A” stops it.

What did you try to make it work?:
I created a for loop within the “Each frame” section of the code component

Begin routine:

stimulus_pulse_started = False
stimulus_pulse_ended = False

Each frame:

for stim in [1,2,3,4]:
    if sound1.status == STARTED and not stimulus_pulse_started:
        print("starting " + str(stim))
        win.callOnFlip(port.write, str.encode('L'))
        stimulus_pulse_start_time = globalClock.getTime()
        stimulus_pulse_started  = True
    if stimulus_pulse_started and not stimulus_pulse_ended:
     if globalClock.getTime() - stimulus_pulse_start_time >= 4: #I want a 4 second gap between stims
        print("stopping " + str(stim))
        win.callOnFlip(port.write,  str.encode('A'))
        stimulus_pulse_started = False

What specifically went wrong when you tried that?:

The triggers do not send as expected, instead they are sent like this:
starting 1
stopping 1
starting 2
stopping 1
starting 2
stopping 1
starting 2
stopping 1
starting 2

I think this is probably due to how I have set up the for loop, but I’m not quite sure how I would fix this as im not sure where i’m going wrong. any help is much appreciated !

Update: I ended up abandoning this method! I’m assuming its because EachFrame refreshes too fast to accomplish this in the way I would like. I initially wanted to do this so I could have a music component playing throughout the routine. Instead I ended up using a builder interface loop for the triggers, and ended up playing the music using sound.Sound().