# This script is used to set up the system for sending triggers to the # EEG recording software (e.g., BrainVision Recorder). The code # automatically looks for an available serial port at the beginning # of the session. If there are any available ports, a connection is # established to the first port in the list. If there are no available # ports, no connection is established, and a warning is shown on # the screen, informing the user that no triggers will be sent to the # EEG recorder. In the latter case, the triggers are only printed in # the Python console of OpenSesame. # # The code is in part based on a tutorial by Kate Stone, available at # https://stonekate.github.io/blog/opensesame, and on an answer # on StackOverflow by user 'quamrana', available at # https://stackoverflow.com/a/76829646/7050882. # The rest is based on pyserial: # https://pyserial.readthedocs.io/en/latest/pyserial_api.html # For development purposes, the test mode can be set to 'yes' # below, which will prevent attempting to connect to a port. # As a result, no triggers will be sent to the EEG recorder, # and instead, the triggers will be printed in the Python # console of OpenSesame. var.test_mode = 'no' #_______________________________________________________________ import serial import serial.tools.list_ports import time # If no serial ports are available, activate test mode if serial.tools.list_ports.comports() == []: var.test_mode = 'yes' # Define `send_trigger` function, which should be used in inline # scripts as in the following example: `send_trigger(1)` # If we are not in test mode... if(var.test_mode == 'no'): # Open the first serial port available serialport = serial.Serial(serial.tools.list_ports.comports()[0].device) # Send triggers to the port def send_trigger(trigger): serialport.write(trigger.to_bytes(length = 1, byteorder = 'big')) time.sleep(0.01) # 10 ms separation from next trigger (see manual of BrainVision Recorder) serialport.write(int(0).to_bytes(length = 1, byteorder = 'big')) # reset port return; # When in test mode, show warning at the beginning of the experiment. # To continue, the letter C must be pressed twice. else: test_canvas = Canvas(color = 'red', font_size = 38, font_family = 'sans'); test_canvas.text('
WARNING. Triggers cannot be sent to the EEG recorder, either because test_mode is activated in the trigger-setup script, or because no serial ports are available. Press Esc to quit the session, or press C twice to continue. If you continue, the triggers will only be printed in the Python console of OpenSesame.
'); test_canvas.show(); my_keyboard = Keyboard(); key, end_time = my_keyboard.get_key(keylist=['c']); key, end_time = my_keyboard.get_key(keylist=['c']); # In the `send_trigger` function, only print the triggers def send_trigger(trigger): print(trigger) time.sleep(0.01) # 10 ms separation from next trigger print(0) return; # Reset EEG port at the beginning of the session send_trigger(0)