Measuring Frequency of Square wave in MATLAB using USB 1024HLS - matlab

I'm trying to measure the frequency of a square wave which is read through a USB 1024 HLS Daq module through MATLAB. What I've done is create a loop which reads 100 values from the digitial input and that gives me vector of 0's and 1's. There is also a timer in this loop which measures the duration for which the loop runs.
After getting the vector, I then count the number of 1's and then use frequency = num_transitions/time to give me the frequency. However, this doesn't seem to work well :( I keep getting different frequencies for different number of iterations of the loop. Any suggestions?

I would suggest trying the following code:
vec = ...(the 100-element vector of digital values)...
dur = ...(the time required to collect the above vector)...
edges = find(diff(vec)); % Finds the indices of transitions between 0 and 1
period = 2*mean(diff(edges)); % Finds the mean period, in number of samples
frequency = 100/(dur*period);
First, the code finds the indices of the transitions from 0 to 1 or 1 to 0. Next, the differences between these indices are computed and averaged, giving the average duration (in number of samples) for the lengths of zeroes and ones. Multiplying this number by two then gives the average period (in number of samples) of the square wave. This number is then multiplied by dur/100 to get the period in whatever the time units of dur are (i.e. seconds, milliseconds, etc.). Taking the reciprocal then gives the average frequency.
One additional caveat: in order to get a good estimate of the frequency, you might have to make sure the 100 samples you collect contain at least a few repeated periods.
Functions of interest used above: DIFF, FIND, MEAN

First of all, you have to make sure that your 100 samples contain at least one full period of the signal, otherwise you'll get false results. You need a good compromise of sample rate (i.e. the more samples per period you have the better the measurement is) and and number of samples.
To be really precise, you should either have a timestamp associated with every measurement (as you usually can't be sure that you get equidistant time spacing in the for loop) or perhaps it's possible to switch your USB module in some "running" mode which doesn't only get one sample at a time but a complete waveform with fixed samplerate.
Concerning the calculation of the frequency, gnovice already pointed out the right way. If you have individual timestamps (in seconds), the following changes are necessary:
tst = ...(the timestamps associated with every sample)...
period = 2*mean(diff(tst(edges)));
frequency = 1/period;

I can't figure out the problem, but if the boolean vector were v then,
frequency = sum(v)/time_to_give_me_the_frequency

Based on your description, it doesn't sound like a problem with the software, UNLESS you are using the Windows system timer, which is notoriously inaccurate (it is only accurate to about 15 milliseconds).
There are high-resolution timers available in Windows, but I don't know how to use them in Matlab. If you have access to the .NET framework, the Stopwatch class has 1 microsecond accuracy (or better), as does the QueryPerformanceCounter API in Win32.
Other than that, you might have some jitter. There could be something in your signal chain that is causing false triggers, etc.
UPDATE: The following CodeProject article should solve the timing problem, if there is one. You should check the Matlab documentation of your version of Matlab to see if it has a native high-resolution timer. Otherwise, you can use this:
C++/Mex wrapper adds microsecond resolution timer to Matlab under WinXP
http://www.codeproject.com/KB/cpp/Matlab_Microsecond_Timer.aspx

mersenne31:
Thanks everyone for your responses. I have tried the solutions that gnovice and groovingandi mentioned and I'm sure they will work as soon as the timing issue is solved.
The code I've used is shown below:
for i=1:100 tic; value = getvalue(portCH); vector(i) = value(1); tst(i) = toc; % gets an individual time sample end
% to get the total time I put total_time = toc after the for loop
totaltime = sum(tst); edges = find(diff(vec)); % Finds the indices of transitions between 0 and 1 period = 2*mean(diff(edges)); % Finds the mean period, in number of samples frequency = 100/(totaltime*period);
The problem is that measuring the time for one sample doesn't really help because it is nearly the same for all samples. What is needed is, as groovingandi mentioned, some "running" mode which reads 100 samples for 3 seconds.
So something like for(3 seconds) and then we do the data capture. But I can't find anything like this. Is there any function in MATLAB that could do this?

This won't answer your question, but it's what I thought of after reading you question. square waves have infinite frequency. The FFT of a square wave it sin(x)/x, which goes from -inf to +inf.
Also try counting only the rising edges in matlab. You can quantize the signal to just +1 and 0, and then only increment the count when you see [0 1] slice of your vector.
OR
You can quantize, decimate, then just sum. This will only work if the each square pulse is the same length and your sampling frequency is constant. I think this one would be harder to do.

Related

Remove Spikes from Periodic Data with MATLAB

I have some data which is time-stamped by a NMEA GPS string that I decode in order to obtain the single data point Year, Month, Day, etcetera.
The problem is is that in few occasions the GPS (probably due to some signal loss) goes boinks and it spits out very very wrong stuff. This generates spikes in the time-stamp data as you can see from the attached picture which plots the vector of Days as outputted by the GPS.
As you can see, the GPS data are generally well behaved, and the days go between 1 and 30/31 each month before falling back to 1 at the next month. In certain moments though, the GPS spits out a random day.
I tried all the standard MATLAB functions for despiking (such as medfilt1 and findpeaks), but either they are not suited to the task, either I do not know how to set them up properly.
My other idea was to loop over differences between adjacent elements, but the vector is so big that the computer cannot really handle it.
Is there any vectorized way to go down such a road and detect those spikes?
Thanks so much!
you need to filter your data using a simple low pass to get rid of the outliers:
windowSize = 5;
b = (1/windowSize)*ones(1,windowSize);
a = 1;
FILTERED_DATA = filter(b,a,YOUR_DATA);
just play a bit with the windowSize until you get the smoothness you want.

Random number generation with Poisson distribution in Matlab

I am trying to simulate an arrival process of vehicles to an intersection in Matlab. The vehicles are randomly generated with Poisson distribution.
Let´s say that in one diraction there is the intensity of the traffic flow 600 vehicles per hour. From what I understood from theory, the lambda of the Poisson distribution should be 600/3600 (3600 sec in 1 hour).
Then I run this cycle:
for i = 1:3600
vehicle(i) = poissrnd(600/3600);
end
There is one problem: when I count the "ones" in the array vehicle there are never 600 ones, it is always some number around, like 567, 595 and so on.
The question is, am I doing it wrong, i.e. should lambda be different? Or is it normal, that the numbers will never be equal?
If you generate a random number, you can have an expectation of the output.
If you actually knew the output it would not be random anymore.
As such you are not doing anything wrong.
You could make your code a bit more elegant though.
Consider this vectorized approach:
vehicle = poissrnd(600/3600,3600,1)
If you always want the numbers to be the same (for example to reproduce results) try setting the state of your random generator.
If you have a modern version (without old code) you could do it like so:
rng(983722)

Equivalent moment using Rainflow

I am trying to make a fatigue analysis from a load series and I woudl like to extract the equivalent moment for
number cycles=1000000
years=25
I have a time series for one hour that looks like:
Then I have read that Rainflow Analysis is a very good tool to extract the cycles from a time history. Therefore I apply:
%Rainflow moment
dt=time(2)-time(1);
[timeSeriesSig, extt] = sig2ext(timeSeries, dt);
rf = rainflow(timeSeriesSig,extt);
I read that
OUTPUT
rf - rainflow cycles: matrix 3xn or 5xn dependend on input,
rf(1,:) Cycles amplitude,
rf(2,:) Cycles mean value,
rf(3,:) Number of cycles (0.5 or 1.0),
rf(4,:) Begining time (when input includes dt or extt data),
rf(5,:) Cycle period (when input includes dt or extt data),
If I am interested in the number of cycles what does the term rf(3,:) mean? It is only containing 0.5 and 1 in the vector. I want to obtain an histogram with the number of cycles per bin amplitude. Thanks
If you are using code from the File Exchange or another source, it helps to link to where you obtained it.
Here, rf(3,:) is showing you whether the amplitudes and other outputs refer to half or full cycles. The rainflow algorithm finds half-cycles first, and then matches tensile and compressive half-cycles of equal amplitude to find full cycles. There are normally some residual half-cycles.
If you examine the rfhist function contained within that same File Exchange submission, you will see how they handle full and half amplitudes. Basically, two half-cycles at any given load amplitude will be counted as one full cycle when creating the histogram.

How to find out carrier signal strength programmatically

Here is the code that I have used to find out carrier signal strength:
int getSignalStrength()
{
void *libHandle = dlopen("/System/Library/Frameworks/CoreTelephony.framework/CoreTelephony", RTLD_LAZY);
int (*CTGetSignalStrength)();
CTGetSignalStrength = dlsym(libHandle, "CTGetSignalStrength");
if( CTGetSignalStrength == NULL) NSLog(#"Could not find CTGetSignalStrength");
int result = CTGetSignalStrength();
dlclose(libHandle);
return result;
}
It is giving me values between 60 to 100, but when I test the signal strength in device by calling to this *3001#12345#* number it showed me as -65. Below I have attached the screenshot. Is the value coming from getSignalStrength() accurate? Then why is it returning positive values always?
getSignalStrength() is showing negated dB attenuation, e.g. -(-60) == 60. The call in is displaying it more conventionally as a measurement less than zero. Yes, these kinds of variations are typical. Even in strictly controlled conditions you can get +/- 20 decibels. One way you can fix it is to take a series of measurements over time, say every second, and keep a running list of the last 10 or so measurements. Then report the mean or median or some other statistic. In my experience this cuts down the variation a lot. You can also do standard deviation to provide a measure of reliability.
My observation on CTGetSignalStrength() in CoreTelephony is that, it returns the
RSSI(Received Signal Strength Indication) value of carrier's signal strength. My experiments with this returns values between the range 0 - 100, which I believe is the "percent signal strength" of the carrier according to this .
Also iOS does not measure signal strength in a linear manner according to this
I also noticed that, even when we have 5 bars in status bar, RSSI value may not be 100.
getSignalStrength() provides the result in negative scale. The difference can be controlled using high pass filter.
You should gather the results of last 10 observations. At the time of adding new observation, take the average of last 10 observations. Multiply it by 0.1. Take the current reading and multiply it by 0.9. Add both. If total observations are greater than 10, remove the oldest observation for next calculation.
It will make your result more reliable and you can also handle sudden changes in the signal strength effectively.
I would recommend reading up on decibel measure. The following link should help.
How to Read Signal Strength
As for many signals getSignalStrength() should be used cojointly with a high-pass filter algorithm.
Also make sure to have an average measurement over some time (10-15 successive measurements).
And it's normal that it gives negative result, dB signals for telephony are like that ;-)

Sine LUT VHDL wont simulate below 800 hz

I made a sine LUT for VHDL, using 256 elements.
Im using MIDI input, so values range 8.17Hz (note #0) to 12543.85z (note #127).
I have another LUT that calculates how many value must be sent to my 48 kHz codec in order to play the sound (the 8.17Hz frequency will need 48000/8.17 = 5870 values).
I have another LUT that contains an index factor, which is 256/num_Values, which is used to call values from the sin table (ex: 100*256/5870 = 4 (with integer rounding)).
I send this index factor to another VHDL file, which is used to calculate which value should be sent back. (ex: index = index_factor*step_counter)
When I get this index, I divide it by 100, and call sineLUT[index] to get the value that I need to generate a sine wave at the desired frequency.
The problem is, only the last 51 notes seem to work for me, and I do not know why. It seems to get stuck on a constant note at anything below that frequency (<650 hz) , and just decrease in volume every time I try to lower the note.
If you need parts of my code, let me know.
Just guessing, I suspect your step_counter isn't going through enough cycles, so your index (into the sine lut) doesn't go through a full 360 degrees for the lower frequencies.
For anything more helpful, you'll probably have to post code.
As an aside, why aren't you using something more like a conventional DDS? Analog Devices has a nice write-up on the basics: DDS Tutorial