Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I just need some guidance as to how to detect the frequency from a sine wave. I generated the sinewave via a DtoA converter. Now, I'm putting that signal back through an AtoD to monitor and verify the output.
I don't know how to detect the frequency of the sine wave. Apparently, I'm supposed to get the period from the sine wave and apply hysteresis to compensate for noise.
Any hint is much appreciated. thanks.
If this is about sine waves only, I'd check for zero crossings, and calculate the average time between zero crossings for a couple of hundred cycles, that would give an accurate half period length, and from that, you can calculate the frequency.
("zero" might not be trivial, as most uC have 0-Vdd range ADC inputs only, so zero in that case might happen to be Vdd/2...)
(very simple) pseudocode could be
const zero = 0; //or vdd/2 if that's the case
while(cyclesSoFar<enoughCycles) {
currentSample=adcRead();
//detect zero crossing (needs hysteresis added)
if((lastSample>zero&¤tSample<=zero) || (lastSample<zero&¤tSample>=zero) ) {
period = getTicks()-ticksAtLastCrossing; //might have to check for over/underflow to get correct value
avgPeriod = avgPeriod * (cyclesSoFar)/(cyclesSoFar+1) + period/(cyclesSoFar+1);
cyclesSoFar++;
}
lastSample = currentSample;
}
freq = ticksFreq/(avgPeriod*2);
Where: enoughCycles is the number of cycles to measure, zero is the DC offset of the sine wave, and ticksFreq is the frequency of the CPU, the most precise time available. Of course, this is very-very simplified, lots of fluff and checks need to be added.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have designed a board that samples audio input using a 16 bit DAC at 48kHz. It stores the data as signed 16-bit integers. I have also implemented a 16 bit ADC on the board and I am able to pass audio through the board successfully.
I would like to design a low pass filter using MATLAB and implement it on this board. I understand how to create basic filters using MATLAB but I cant quite grasp how to bridge the gap between creating the filter in MATLAB and implementing this filter using C code on my board. I would like to be able to pass the signal into the board and observe the filtered signal on the output in 'real-time'.
How can this be achieved?
ok, you said that you get your coefficients from a [B,A]= butter(..) likewise filter (try getting them in Z domain AKA digital filter), those A,B coefficients correspond to a simple transfer function you know
H(z) = B(z)/A(z) = (b(1)+b(2) z^−1+⋯+b(n+1) z^−n)/(a(1)+a(2) z^−1+⋯+a(n+1) z^−n)
right?
you just need to remember that the output y = H(z)*x or in other words
y = B(z)/A(z) * x and finally A(z)*y = b(z)*x
and what was x(t) * z^-1 equals? yep x(t-1)
that means that you'll end with an ecuation similar to:
y(t)*a(1)+y(t-1)*a(2)+⋯+y(t-n)a(n+1) = x(t)*b(1)+x(t-1)*b(2)+⋯+x(t-n)b(n+1)
and what we need is the actual value of y(t) with the known values of actual x(t) and past x(t-1) etc, and also with known and stored values of past y(t-1) etc...
y(t) = 1/a(1) * (x(t)*b(1)+x(t-1)*b(2)+⋯+x(t-n)b(n+1) - y(t-1)*a(2)-⋯-y(t-n)a(n+1))
that means you need two arrays for x and y, and apply the equation with the B and A arrays you got from matlab...
sadly, this assumes you ALREADY took in consideration the sampling time in the butter() (hence Wn should be normalized) and make sure you take your samples at that exact sampling time (and ideally calculate your output at the exact time too)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to classify the events above as 1 or 0. 1 would be the lower values and 0 would be the higher values. Usually the data is does not look as clean as this. Currently the approach I am taking is to have two different thresholds so that in order to go from 0 to 1 it has to go past the 1 to 0 threshold and it has to be above for 20 sensor values. This threshold is set to the highest value I receive minus ten percent of that value. I dont think a machine learning approach will work because I have too few features to work with and also the implementation has to take up minimal code space. I am hoping someone may be able to point me in the direction of a known algorithm that would apply well to this sort of problem, googling it and checking my other sources isnt producing great results. The current implementation is very effective and the hardware inst going to change.
Currently the approach I am taking is to have two different thresholds so that in order to go from 0 to 1 it has to go past the 1 to 0 threshold and it has to be above for 20 sensor values
Calculate the area on your graph of those 20 sensor values. If the area is greater than a threshold (perhaps half the peak value) assign it as 1, else assign it as 0.
Since your measurements are one unit wide (pixels, or sensor readings) the area ends up being the sum of the 20 sensor values.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Given arrival and departure times of N trains that reach a railway station, for a given k platforms, return the maximum number of trains that we can house on the k platforms.
k <<< N
Arrival and departure time Array
Input: arr[] = {9:00, 9:40, 9:50, 11:00, 15:00, 18:00}
dep[] = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00}
This question was asked of me in some interview, so what is best algorithm for that? This question is slightly modified from this question.
I tried greedy algorithm for this question but it is not working for all test cases.
For eg:for k=2
We are given time intervals
arr[]={1:00,1:30,2:00}
dept[]={1:40,2:10,3:30}
'
be removing the {1:30 and 2:10 interval we can do the task for k=2
{1:00-1:40} and {2:00-3:30} as no other train occurs between this time
It seems to me(I do not have a rigorous proof for it) that a greedy algorithm should work:
Sort the trains by their departure time.
Let's maintain an array lastDeparture of size k, where the lastDeparture[i] is the time when the last train leaves the i platform(initially filled with zeros).
Let's iterate over the trains array and do the following:
Find all such platforms that lastDeparture[i] <= currentTrain.arrival.
If there are no such platforms, continue.
Otherwise, choose the one with the largest lastDeparture value(if there are several such platforms, we can pick any of them).
increase the answer by one and add the current train to this platform(that is, assign lastDeparture[i] = currentTrain.departure.
A sketch of a proof:
Let's assume that our solution is not optimal. Let's find the first train that is in our answer but not in the optimal one. There should be some other train instead of it. But it's departure time is greater. Thus, the total cannot increase when we exchange these two trains.
Time complexity: O(n log n)(step 3 can be handled efficiently using a balanced binary search tree that keeps platforms sorted by the last departure time).
I think I previously misunderstood the question.
If we have a limited number of platforms I now think we're being asked to cancel a minimum number of trains so that the schedule never overwhelms the platforms.
Brute force:
Merge & Sort the Arrivals and Departures (but keeping track of which is which and identifying which train arrives/departs).
Walk through the array adding one to a counter for each arrival and subtracting one for each departure.
If the counter is k and a train arrives cancel a train which is at the station with the longest time left on the platform at the time of the 'overflowing' arrival. NB: This may be the arriving train or a train already on a platform.
The answer is the total number of trains minus the number of cancelled trains.
Notice that by cancelling a train at the station with the longest time left on the platform we cancel the minimum number of trains. We have to cancel a train at the station to release a platform and the ones with the most time left have maximal potential to free space for future arrivals.
This will be O(N*K) complexity in the worst case if the arrivals and departures are given sorted and can be quickly riffled together. I notice the given example is nearly so.
The complexity is the worst case of the sort and O(N*K) tallying.
If I understand the problem correctly, I believe this can be done by using a stack of size k that will contain the trains currently on a platform. For each train (in sorted order by departure times):
while current.ArrivalTime > stack.Last.DepartureTime:
remove the top element (train) from the stack
push the current train IF there is room, else ignore it
answer = max(answer, stack.Size)
The maximum size that your stack reaches would be the answer to the problem.
This should be O(n log n) because of the sort, since each train enters / leaves the stack at most once.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have 8 data points that form the peak of a partial sine wave. I am trying to fit these to get an equation so I discover the point of the true maximum position (which most likely lies between the data points). The coding will be in C. Does anyone have any info on algorithms or ideally code samples?
Since the data points are all near a maximum, the wave y = A*sin(B*x + C) + D can be approximated as a parabola much like the first 2 terms of cos(x) = (1.0 - x*x/2! + ...).
So find the best fit parabola for the 8 data points and calculate the maximum.
C- Peak detection via quadratic fit
Lots of google examples exist. Example
Provided your sample-values form a "hump", i.e. increasing followed by decreasing samples, you could try viewing the samplevalues as "weights" and compute the "center of gravity":
float cog = 0f;
for (i=0; i<num_samples; ii+) {
cog += i * samples[i];
}
cog /= num_samples;
I've used that in similar cases in the past.
NOTE: This scheme only works if the set of samples used contain a single peak, which the question phrasing certainly made me think was the case. Finding locations of interest can easily be done by monitoring, if sample values are increasing or decreasing, selecting an "interesting" range of samples and computing the peak location as described.
Also note, that if the actual goal is to determine the sine wave phase or frequency of an input signal, it would be a lot better to correlate the signal against reference set of sine-waves (in other words, do a Fourier transform).
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I'm studying programming on my own and I would like to have an idea how to solve this problem.
I have been given the set of resistors with given resistances and a given value restot. I can pick a given number of those resistors. How can I make a circuit which resistance is as near as possible to restot? A programmer told me that that one can use genetic algorithms but I'm not limited to use such.
I guess I have to make a linear system of equations using Kirchoff's laws to make equations but as I don't have very much experience on electricity problems nor numerical algorithms to linear systems so I would like to have some guidance about how can I make those equations automatically to computers memory as the system changes all the time. And how can I make sure that the algorithm converges to a better solutions?
The problem is from a Finnish discussion forum.
Resistors can either exist in series or in parallel, and their resistances add up differently (add values for series, add reciprocals for parallel).
You can also have networks for resistors in series and parallel.
This sounds to me like a classic case of a recursive data structure, and you could probably represent it as a tree, in a similar way to a binary expression tree: http://en.wikipedia.org/wiki/Binary_expression_tree
Combine that some exploratory tree building (you should look into the way Prolog does this) and you can find the best combination of resistors that gets close to your total.
No genetic algorithms in this approach, although you could take a genetic approach to building and refining the tree.
To apply a genetic algorithm you would need to find a way to represent, mutate and combine the "DNA" of a resistor network.
One way would be to:
Add some number of 0 ohm resistors to your resister set (representing wires).
Number the resistors from 1 to N
For some M, imagine a set of M junctions including the source (1) and sink (M).
You could define which junctions the two endpoints of each resistor are connected to as the unique identifier of a network. This is just an N-tuple of integer pairs in the range 1..M. This tuple can be the "DNA".
Then:
Generate a bunch of random networks from random tuples.
Calculate each networks resistence
Discard some amount of the population farthest from the target resistence.
Combine random pairs of them to form new networks. (perhaps by randomly selecting each resistor endpoint from either parent A or parent B with 50% probability)
Randomly change a few endpoints (mutation).
Goto 2
Not sure if it would actually work exactly like this, but you get the general idea.
There is undoubtably a better non-genetic algorithm, but you specifically asked for a genetic one so there you go.
If you are not limited to genetic algorithm, then I think you can also solve this problem with help of linear programming. You can encode the problem as below and ask a solver to give the answer for you.
Required Resistance Of Circuit = x ohms
// We want to have total 33 resistors.
selected_in_series_1 + selected_in_series_2 +... + selected_in_series_211 + selected_in_parallel_1 + selected_in_parallel_2 + ... + selected_in_parallel_211 = 33
// Resistor in Series
(selected_in_series_1 * Resistor_1) + (selected_in_series_2 * Resistor_2) + ..(selected_in_series_211 * Resistor_211) = total_resistence_in series
// Similarly write formula for parallel
(selected_in_parallel_1 * 1/Resistor_1) + (selected_in_parallel_2 * 1/Resistor_2) + ..(selected_in_parallel_211 * 1/Resistor_211) = 1/total_resistence_in parallel
total_resistence_in series + total_resistence_in parallel = Required Resistance Of Circuit