MATLAB has a fairly new (R2019B+) serial port interface,
Serialport. Some of my arduino control code had previously used the
serial command that MATLAB has now deprecated. So I was curious to compare the old and new interfaces. In addition I also compared
IOPort, the PTB serial controller.
For the test I basically toggled the state of a digital pin on a Seeduino Xiao as fast as possible. I used the legacy MATLAB arduino interface sketch, which receives and sends the data via USB serial commands. Baudrate was set to 115200. MATLAB R2020B on Ubutnu 20.10.
t = tic; for i = 1:10000 digitalWrite(PIN,mod(i,2)); end fprintf('It took %.4f seconds for 10,000 iterations\n',toc(t));
I used an oscilloscope to ensure the output signal was well formed, and used its measurement function to measure average rise-time widths. I also used a simplistic method to generate a 1ms TTL using
digitalWrite(1);WaitSecs(0.001);digitalWrite(0) to see how close to 1ms we got:
10,000 iterations = 6.1 seconds
Risetime range = 540 - 790 µs
1ms pulse width = 3.27 ms
10,000 iterations = 3.4 seconds
Risetime range = 320 - 350 µs
1ms pulse width = 2.52 ms
10,000 iterations = 0.7 seconds
Risetime range = 50 - 74 µs
1ms pulse width = 1.28 ms
serialport is clearly faster than the old one, and the variance is considerably lower. However,
IOPort is still much faster than either MATLAB option, I was quite surprised as normally you cannot achieve such fast command-response times with USB devices (the Seeduino Xiao is faster than an Arduino Uno and uses USB 3). If you need to send triggers in a PTB drawing loop and you don’t have much overhead (i.e. fast monitor or complex stimuli), then this should help…
 for timed TTLs, it is better to send the timing command to the Arduino, that way MATLAB returns immediately and doesn’t wait for the digitalWrite to finish. See Arduino · Psychtoolbox-3/Psychtoolbox-3 Wiki · GitHub for details.