Psychtoolbox flip time issue - matlab

I am running a psychophysics task on psychtoolbox that need to show each image for 16, 30, 60, and 120 milliseconds. Although my system monitor refresh rate is 16.66 ms (60 Hz) but the lowest time I get is almost 33 ms (I check this time by recording video from the screen while showing these images).
I've searched a lot and now I use flip with specifying the time with ifi and nextFrameInterval but still can't show my image for 16 milliseconds. Why is this happening and how can I fix this?
ifi = Screen('GetFlipInterval',window);
Screen('DrawTexture',window,fixation,[],fixRect);
[~,lastVisualInterval] = Screen('Flip', window);
nextStimFrameDelta= (p.pre_mask_time/ifi);
Screen('DrawTexture',window,stimulus(rec(TrialNum, 3)),[],rectStim);
[~,lastVisualInterval] = Screen('Flip', window,lastVisualInterval +((nextStimFrameDelta-0.5)*ifi));
nextStimFrameDelta= ((rec(TrialNum,2)/1000)/ifi) % rec(TrialNum,2) is the duration of peresenting images (16,30,... ms)
Screen('DrawTexture',window,mask(TrialNum),[],rectStim);
[~,lastVisualInterval] = Screen('Flip', window,lastVisualInterval +((nextStimFrameDelta-0.5)*ifi));
% And here the facial expression must be replaced by a mask after 16 or 30,... ms

Related

STM32 HAL Nucleo F446RE Quadrature Encoder

I have a problem with the quadrature encoder mode on timer TIM3 of my
STM32F446RE /
NUCLEO-F446RE:
TIM3 counts on every rising edge on the first signal.
The CNT register counts up and I read the value with 1 Hz and then
I set the register to 0.
When I look on the
oscilloscope
the frequency is half as high as the value from the
CNT register output (1hz).
Why?
TIM3 counts on both edges on the first signal.
The
CNT register output (1 Hz)
is completely wrong.
My configuration is:
GPIO_InitTypeDef sInitEncoderPin1;
sInitEncoderPin1.Pin = pin1Encoder.pin; // A GPIO_PIN_6
sInitEncoderPin1.Mode = GPIO_MODE_AF_PP;
sInitEncoderPin1.Pull = GPIO_PULLUP;
sInitEncoderPin1.Speed = GPIO_SPEED_HIGH;
sInitEncoderPin1.Alternate = altFunctionEncoder; // GPIO_AF2_TIM3
GPIO_InitTypeDef sInitEncoderPin2;
sInitEncoderPin2.Pin = pin2Encoder.pin; // A GPIO_PIN_7
sInitEncoderPin2.Mode = GPIO_MODE_AF_PP;
sInitEncoderPin2.Pull = GPIO_PULLUP;
sInitEncoderPin2.Speed = GPIO_SPEED_HIGH;
sInitEncoderPin2.Alternate = altFunctionEncoder; // GPIO_AF2_TIM3
HAL_GPIO_Init(GPIOA, &sInitEncoderPin1);
HAL_GPIO_Init(GPIOA, &sInitEncoderPin2);
encoderTimer.Init.Period = 0xffff;
encoderTimer.Init.Prescaler = 0;
encoderTimer.Init.CounterMode = TIM_COUNTERMODE_UP;
encoderTimer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
encoderTimer.Init.RepetitionCounter = 0;
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 1);
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
encoder.IC1Filter = 0x0f;
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING; // TIM_INPUTCHANNELPOLARITY_BOTHEDGE
encoder.IC1Prescaler = TIM_ICPSC_DIV1;
encoder.IC1Selection = TIM_ICSELECTION_DIRECTTI;
encoder.IC2Filter = 0x0f;
encoder.IC2Polarity = TIM_INPUTCHANNELPOLARITY_RISING;
encoder.IC2Prescaler = TIM_ICPSC_DIV1;
encoder.IC2Selection = TIM_ICSELECTION_DIRECTTI;
HAL_TIM_Encoder_Init(&encoderTimer, &encoder);
HAL_TIM_Encoder_Start_IT(&encoderTimer, TIM_CHANNEL_ALL);
The
oscilloscope screenshot
shows a frequency of about 416 Hz.
The values shown in the
first shell output
are (very roughly!) twice as high (as the question points out already).
This appears (nearly...) correct to me since the shown configuration
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
selects the "X2 resolution encoder mode", which counts 2 CNT increments per signal period.
In an application note on
timer overview,
(Sec. 4.3.4 / Fig. 7) there is an illustrative diagram how the encoder mode works in detail.
The
second screenshot
results from an incorrect TIM3 configuration:
The encoder mode (TIM_ENCODERMODE_TI1) assumes that both channels trigger only upon directed flanks in an alternating way (see the AN link above).
If one of the two channels triggers twice as many events due to
configuration
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE,
the counter will only count up one position and then "recognize" a "reversal" event (= change of direction).
Keeping in mind that
65535u = 0xFFFF = -1
the second screenshot only shows values -1, 0, +1 - which fits perfectly with this explanation.
The question remains why the first screenshot shows (reproducible) measurements between 800 and 822.
I assume that
the physical source of the encoder signal runs at a constant pace
the 1 Hz timer that triggered shell output is independent from TIM3, and
it has been started before the encoder timer
(i.e., above the shown code sample).
This may explain why the first two values look like nonsense (0: TIM3 has not been started yet. 545: TIM3 has been started during the shell output timer period).
Discarding the first two measurement samples, the average and standard deviation, resp., of the measured signal frequency are
808,9091 +/- 0,5950 [X2 increments per second]
404,4545 +/- 0,2975 [Hz]
which corresponds to a period of
2,4331 +/- 0,003 [ms].
Hence, the measured frequency is too low by about 11 Hz, i.e., measured period too high by nearly 30 µs, and this error is clearly beyond the statistical noise.
The question gives a hint where this error might come from:
The CNT register counts up and I read the value with 1 Hz and then I set the register to 0.
Whenever the 1 Hz "polling timer" expires, it triggers an interrupt
(or a logical event in polling software).
Processing of this interrupt/event may be delayed a little,
depending on other software (IRQ: deactivation times elsewhere in the software,
Polling: loop duration until event is polled).
Software reads CNT value.
Software resets CNT value to zero,
discarding further increments since the CNT value has been read.
TIM3 continues counting (from zero).
This hints that software needs 30 µs between (3.) and (4.), which would be quite a lot of time on an STM32F4.
Edit: I just re-checked the oscilloscope screenshot. The error is visible, but I believe it is smaller than I originally assumed (from counting flanks in the picture).

How to make oscillator-based kick drum sound exactly the same every time

I’m trying to create a kick drum sound that must sound exactly the same when looped at different tempi. The implementation below sounds exactly the same when repeated once every second, but it sounds to me like every other kick has a higher pitch when played every half second. It’s like there is a clipping sound or something.
var context = new AudioContext();
function playKick(when) {
var oscillator = context.createOscillator();
var gain = context.createGain();
oscillator.connect(gain);
gain.connect(context.destination);
oscillator.frequency.setValueAtTime(150, when);
gain.gain.setValueAtTime(1, when);
oscillator.frequency.exponentialRampToValueAtTime(0.001, when + 0.5);
gain.gain.exponentialRampToValueAtTime(0.001, when + 0.5);
oscillator.start(when);
oscillator.stop(when + 0.5);
}
for (var i = 0; i < 16; i++) {
playKick(i * 0.5); // Sounds fine with multiplier set to 1
}
Here’s the same code on JSFiddle: https://jsfiddle.net/1kLn26p4/3/
Not true; oscillator.start will begin the phase at 0. The problem is that you're starting the "when" parameter at zero; you should start it at context.currentTime.
for (var i = 0; i < 16; i++) {
playKick(context.current time + i * 0.5); // Sounds fine with multiplier set to 1
}
The oscillator is set to start at the same time as the change from the default frequency of 440 Hz to 150 Hz. Sometimes this results in a glitch as the transition is momentarily audible.
The glitch can be prevented by setting the frequency of the oscillator node to 150 Hz at the time of creation. So add:
oscillator.frequency.value = 150;
If you want to make the glitch more obvious out of curiosity, try:
oscillator.frequency.value = 5000;
and you should be able to hear what is happening.
Updated fiddle.
EDIT
In addition the same problem is interacting with the timing of the ramp. You can further improve the sound by ensuring that the setValueAtTime event always occurs a short time after playback starts:
oscillator.frequency.setValueAtTime(3500, when + 0.001);
Again, not perfect at 3500 Hz, but it's an improvement, and I'm not sure you'll achieve sonic perfection with Web Audio. The best you can do is try to mask these glitches until implementations improve. At actual kick drum frequencies (e.g. the 150 Hz in your original Q.), I can't tell any difference between successive sounds. Hopefully that's good enough.
Revised fiddle.

Flicker frequencies in PTB

I'm trying to present a 4Hz flickering stimuli in PsychToolbox for 5 seconds followed by a 500Hz tone. Does anyone have an idea of how to do this? I've been using the vbl or screen refresh rate to calculate the flicker frequency but I'm not sure if I'm on the right track at all. I also have no idea how to present an auditory stimuli in PTB (I tried the sound function already). Any help is greatly appreciated!
I'm not sure about sound presentation in PTB (I've never done it), but you seem to be on the right track for the flicker frequency.
The way I do it is to determine the screen refresh rate, divide the total length of time you want the stimulus presented by this refresh rate (this will give you the number of frames that will be drawn during this time), and then have a frame counter that increases by 1 after every flip. You can then use this frame counter to switch commands on or off.
A minimal example (randomly changes the background colour at 4Hz for 5 seconds):
[w, wRect]=Screen('OpenWindow', 0);
MaxTime = 5; %Set maximum time for all stimuli to be presented in seconds
Hz = 4; %Set Hz for stimulus flicker
Screen('Flip',w);
Frametime=Screen('GetFlipInterval',w); %Find refresh rate in seconds
FramesPerFull = round(5/Frametime); % Number of frames for all stimuli
FramesPerStim = round((1/Hz)/Frametime); %Number of frames for each stimulus
StartT = GetSecs; %Measure start time of session
Framecounter = 0; %Frame counter begins at 0
while 1
if Framecounter==FramesPerFull
break; %End session
end
if ~mod(Framecounter,FramesPerStim)
randomcolour = rand(1, 3)*255; %Change background stimulus colour
end
Screen('FillRect', w, randomcolour, wRect);
Screen('Flip',w);
Framecounter = Framecounter + 1; %Increase frame counter
end
EndT = GetSecs; %Measure end time of session
Screen('CloseAll');
EndT - StartT %Shows full length of time all stimuli were presented
The timing precision will depend on your particular refresh rate.
Hope this helps!

Unable to acquire *precisely* timed videos in Matlab (using ImgAcq toolbox)

When I try to record using the code below, the resulting videos have the correct number of frames and file lengths, but the recorded time is always slightly longer (as measured by filming a digital clock), a 60min recordings capture ~61min, and 5min recordings have extra 3-5sec (so time is skipped during recordings). Occasionally, the camera clearly show time skipping when it records for some time, then pauses for up to hour or so, and then resumes.
I am using a Basler GigE acA1300-60gm (http://www.baslerweb.com/en/products/area-scan-cameras/ace/aca1300-60gm) camera set to continuous triggering for several hours, and I need the acquired videos to have millisecond resolution. I am not sure why the recording times are so varied, am I using a wrong script for the job or does it have something to do with the hardware settings?
(Matlab R2014a on Windows 7)
vid = videoinput(adapter, deviceIDVar{1,1}, formatVar);
vid.FramesPerTrigger = NoOfFramesPerFile;
src = getselectedsource(vid);
src.FrameStartTriggerMode = 'On';
src.FrameStartTriggerSource = 'Line1';
src.FrameStartTriggerActivation = 'RisingEdge';
src.FrameStartTriggerMode = 'Off';
src.PacketSize = 8000;
triggerconfig(vid, 'hardware', 'DeviceSpecific', 'DeviceSpecific');
vid.TriggerRepeat = 0;
vid.LoggingMode = 'disk';
for i=1:FileLimit
%file path and format settings
diskLogger = VideoWriter(filenameWithExt, 'MPEG-4');
diskLogger.FrameRate = 25;
vid.DiskLogger = diskLogger;
start(vid)
wait(vid, Inf);
end
stop(vid)
delete(vid)
clear
Are here any better ways to acquire precisely timed videos (at 25FPS)? Thanks in advance!

dynamic size for microphone input

i am using unity3d to record some input from the microphone using:
getAudioSource.clip = Microphone.Start(null, true,20, 44100);
The problem is that this records for a standard time period of 20 secs, which i don't want. I would like to record untill a finish a recording by:
Microphone.End(deviceName);
and the resulting clip should have the exact size i recorded, not a standard 20 secs. Right now, if i end the recording after 3 secs, the resulting audio is 20 secs in length. I would like it to have 3 secs.
How can this be done?
the size isn't changeable, it's fixed size.. but i did manage to trim the audio to the actual size.
UPDATE
AudioClip ac = getAudioSource.clip;
float lengthL = ac.length;
float samplesL = ac.samples;
float samplesPerSec = (float)samplesL/lengthL;
float[] samples = new float[(int)(samplesPerSec * timeSinceRecordStarted)];
ac.GetData(samples,0);
getAudioSource.clip = AudioClip.Create("RecordedSound",(int)(timeSinceRecordStarted*samplesPerSec),1,44100,false,false);
getAudioSource.clip.SetData(samples,0);
where timeSinceRecordStarted is the length in secs of the recording and getAudioSource initially holds the microphone audio clip.