Adding a loop in my code without messing up the timing

Dear all,

I used the Builder to build my experiment, and I wanted to add some changes with the Coder.

Each trial consists of this, in seconds:

  • 0->6 : nothing
  • 6->7 : image presentation
  • 7->13 : nothing
  • 13->17 : rating scale

During those 12 seconds of “nothing”, I want to insert a few code lines to connect to an Arduino board and record some data (heart beats). Basically, the Arduino code is a 6 second loop that checks for incoming data from the USB port. The heartbeats will then be saved for each trial with addData:

The problem is, to control for timing, Psychopy seems to be tracking each frame, and adding my 6 second loop seems to mess up the times.
I thought the Static Screen might be good for this, but when I add a 6 second Static Screen with some code, I cannot find that code in the file when I compile and search the file.
I also thought about using the Code Component, but it applies to either the start of the routine or the end, but I also need my code in between (seconds 7 to 13).

Perhaps you can recommend a way of achieving this?

Thank you very much,
Santiago

Hi Santiago,

You’re right, Builder scripts are based on drawing frames on every screen refresh interval. So you should avoid inserting any code that will last longer than a reasonable proportion of a single frame interval. So six second loops, calls to event.waitKeys(), etc are out.

If it is sufficient for you to check the USB interface just once every screen refresh, then the easiest way to stay within the Builder event loop is indeed to use a code component. Your code should go in the Each frame tab, something like this:

if t <= 6.0 or (t >= 7.0 and t <= 13.0):
    result = check_your_USB_port()
    add_data_if_necessary(result)

i.e. for a typical 60 Hz display, this would result in checking the USB port 60 times per second, but just during the specified portions of the trial.

Of course, as long as those functions take little time, there is no reason why they also can’t be running during the stimulus presentation & rating scale portions of the trial (just drop the first line of code).

1 Like

Thanks a lot for this explanation Michael! Very clear. I tried it, and it works like I wanted.
I hadn’t thought about using conditionals (if t <=) in the each frame window. And it’s great that I can also check the USB port during stimulus presentation & rating scale, I hadn’t thought about it either.

Thanks! :slight_smile:

1 Like