Single key press results in multiple EEG triggers when routine is not ended

Dear Psychopy community,

I am adding EEG markers to a N-back task using a triggerbox. Specifically, I am adding a marker when the square appears on the screen and when the subjects press the spacebar in the 2 s trial window.

I correctly get the markers when the square appear on the screen but, surprisingly, I get multiple random markers (trains of 4-7 markers) when the spacebar is pressed.

Importantly, I manage to get a single marker if I set to terminate the routine once the spacebar is pressed so the problem must be linked to the fact that the trial is not ended when the key is pressed.

Does anyone have experienced something like this and can provide a suggestion on how to fix this?

Here is the code:

trialResp updates

    waitOnFlip = False
    if trialResp.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        trialResp.frameNStart = frameN  # exact frame index
        trialResp.tStart = t  # local t and not account for scr refresh
        trialResp.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(trialResp, 'tStartRefresh')  # time at next scr refresh
        trialResp.status = STARTED
        # keyboard checking is just starting
        waitOnFlip = True
        win.callOnFlip(trialResp.clock.reset)  # t=0 on next screen flip
        win.callOnFlip(trialResp.clearEvents, eventType='keyboard')  # clear events on next screen flip
    if trialResp.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > trialResp.tStartRefresh + 2-frameTolerance:
            # keep track of stop time/frame for later
            trialResp.tStop = t  # not accounting for scr refresh
            trialResp.frameNStop = frameN  # exact frame index
            win.timeOnFlip(trialResp, 'tStopRefresh')  # time at next scr refresh
            trialResp.status = FINISHED
    if trialResp.status == STARTED and not waitOnFlip:
        theseKeys = trialResp.getKeys(keyList=['space'], waitRelease=False)
        _trialResp_allKeys.extend(theseKeys)
        if len(_trialResp_allKeys):
            trialResp.keys = _trialResp_allKeys[-1].name  # just the last key pressed
            trialResp.rt = _trialResp_allKeys[-1].rt
            # was this correct?
            if (trialResp.keys == str(corrAns)) or (trialResp.keys == corrAns):
                trialResp.corr = 1
            else:
                trialResp.corr = 0

             **sendtrigger(device)**

#check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=[“escape”]):
core.quit()

    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in trialComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
trials1.addData('trialGrid.started', trialGrid.tStartRefresh)
trials1.addData('trialGrid.stopped', trialGrid.tStopRefresh)
trials1.addData('trialSquare.started', trialSquare.tStartRefresh)
trials1.addData('trialSquare.stopped', trialSquare.tStopRefresh)
trials1.addData('trialFix.started', trialFix.tStartRefresh)
trials1.addData('trialFix.stopped', trialFix.tStopRefresh)
# check responses
if trialResp.keys in ['', [], None]:  # No response was made
    trialResp.keys = None
    # was no response the correct answer?!
    if str(corrAns).lower() == 'none':
       trialResp.corr = 1;  # correct non-response
    else:
       trialResp.corr = 0;  # failed to respond (incorrectly)
# store data for trials1 (TrialHandler)
trials1.addData('trialResp.keys',trialResp.keys)
trials1.addData('trialResp.corr', trialResp.corr)
if trialResp.keys != None:  # we had a response
    trials1.addData('trialResp.rt', trialResp.rt)
trials1.addData('trialResp.started', trialResp.tStartRefresh)
trials1.addData('trialResp.stopped', trialResp.tStopRefresh)
thisExp.nextEntry()

Thank you very much!

Elisa