Hi Nicola
If my understanding is correct, you assembled a state matrix to send a single pulse on BNC+PWM, and ran it in a loop where MATLAB controls the inter-pulse timing (with the pause() function?).
When MATLAB sends data to serial port hardware, it actually sends data to the OS (Windows/Ubuntu), which decides when to send to the serial port. Hundreds of milliseconds of jitter and latency are not uncommon. The point of Bpod is that once a state matrix is running (i.e. once a trial starts), the trial's events and state transitions will be measured and executed by the microcontroller's clock, so they will have precise timing. The inter-trial interval is still controlled by MATLAB, so it has some randomness that the OS controls. Take-home message - when the interval between two events is time-critical, you'll have to make them part of the same state matrix.
Below is a code example derived from your setup, where all of the pulse timing takes place on the state machine. Please let me know how it looks!
% Params
nTrials = 50;
pulseDuration = 0.01;
pulseInterval = 0.1;
currentState = 0;
sma = NewStateMatrix();
for currentTrial = 1:nTrials;
currentState = currentState + 1;
sma = AddState(sma, 'Name', num2str(currentState), ...
'Timer', pulseDuration,...
'StateChangeConditions', {'Tup', num2str(currentState+1)},...
'OutputActions', {'BNCState', 2, 'PWM1', 255});
currentState = currentState + 1;
sma = AddState(sma, 'Name', num2str(currentState), ...
'Timer', pulseInterval,...
'StateChangeConditions', {'Tup', num2str(currentState+1)},...
'OutputActions', {});
end
currentState = currentState + 1;
sma = AddState(sma, 'Name', num2str(currentState), ...
'Timer', pulseDuration,...
'StateChangeConditions', {'Tup', 'exit'},...
'OutputActions', {});
SendStateMatrix(sma);
RawEvents = RunStateMatrix;