Detect some frequencies on ADC signal - FFT or similar

Status
Not open for further replies.

luisonoff

Member
INTRODUCTION
Hello everyone,
My name's Luis, I live in Alicante, Spain, and I am starting a new project using teensy 3.1. I have been some days reading and collecting interesting info at this forum, so useful. Just wanted to write here what I am trying to do, maybe somebody has done it before or can give me some advice.


MY PROJECT
I have 2 leds in different rooms that flash at different frequencies (rigth now 45 and 50Hz, but could be changed).
I have a receiver led connected directly to my teensy's ADC. (rigth now I measure this signal at 200Hz).
My goal is to be able to detect if I am close to one led or the other, looking for this frequencies (45 and 50Hz) in the ADC signal.
I have tried with an oscilloscope first instead of the adc and looks good, I can easily see the modulated signal from both leds (not both at the same time, maybe in the future).
Of course, this signal has lots of noise, variable amplitude, etc. Depending on how I move the receiver led, how close it is, ligth from other sources, etc.


HELP
Any advise on how should I process this signal to check if any of those frequencies is present?


MORE DETAILS
My approach rigth now: I read the ADC at 200Hz and store it in a buffer. Every half a second (I have 100 measures) I process that signal and want to know if there is any noticeable component at the frequency I am looking for. Haven't tried this last step yet.
My options: First of all I wanted to try a fast fourier transform FFT. Found the one implemented in Audio library and the one in adafruits webpage (https://learn.adafruit.com/fft-fun-with-fourier-transforms/overview-1) and some others. They all look complex, cpu consuming... Maybe it is easier in my case that I have so little measures to analyze and such low frequencies?? I am a bit lost here...
My other option is to implement a matched filter or goertzel filter (https://netwerkt.wordpress.com/2011/08/25/goertzel-filter/) but I realised I will have to do it twice as I want to distinguish 2 frequencies...

How would you do it? Is there a easier way? Am I missing something?

Thank you very much for your help.
 
Last edited:
I suspect the FFT examples would be the way to go but with a greater delta between the two and such that they don't share harmonics. If you have control over both LEDs I'd suggest synchronizing them so they run at the same frequency but different phasing/duty cycle. So for example define a 5 step cycle, for the first two LED1 is on, for the 3rd all are off, for fourth LED2 is on and for the fifth both are off. Then your code code can do a running average looking for peaks. If peak lasted 1/5 X then it's LED2, if 2/5 X then LED1.

There are a range of ways to extract this information of varying levels of complexity, but all are going to be reasonably CPU intensive if they base on processing ADC measurements.

You may find positional information hard to extract from LED beams based on power due to reflections and the effects of lens fitted to the detector and transmitter optics making it more dependent on relative angle rather than distance.
 
Although the FFT is pretty CPU intensive, in your case the data rate is so low and the teensy is so powerfull that you wil not even notice it. The FFT can be done in approx 0.1 ms. Remember, you already spent half a second just waiting for the input data.
Instead of an FFT you could use a Goerzel filter or just a two-tone DFT. Processing the data twice is more efficient than a full fft. For two tones the compexity is N*log2(N)=896 for the FFT and 2*N=256 for a DFT, assuming N=128.
If you have multilpe leds flashing, you need to have an aliasing filter, which prevents any frequency contents (harmonics) above the Nyquist frequency to fold back into the baseband.
Also for any algorithm, the frequency separation is a bit too close for just 100 samples. Including windowing, your resolution will be approximately 4 Hz. If there is a large ratio between the received signals of both LEDs, you will not be able to measure the lower one.
Finally if you are worried about processing power, you can offload processing to an audio board and implement two bandpass filters or high/lowpass filter combination inside the codec (Set the MCLK to a very low sampling frequency).

Edit: furthermore, to avoid disturbance, frequencies around the mains frequency (50 Hz) should in general be avoided.
If you can please shift it a bit futher away from the mains.

Edit2: Although I say 2-tone DFT, you do not have to have the tones on a grid of fsample/2^N. Since it boils down to a simple correlation, you are free to choose any frequency you like to correlate with.
 
Last edited:
Thank you very much for your answers,

I'd suggest synchronizing them so they run at the same frequency but different phasing/duty cycle.
Hard to synchronize them because each led and the receiver are 3 different products with a teensy each and I would have to connect them wirelessly... that's why I thougth 2 frequencies was easier.

You may find positional information hard to extract from LED beams
I dont want to get positional information as distance, etc. I just want to know if one of the emitting leds is near me (of course my receiver has to face it and be near enough to get its ligth).

Although the FFT is pretty CPU intensive, in your case the data rate is so low and the teensy is so powerfull that you wil not even notice it. The FFT can be done in approx 0.1 ms. ... Instead of an FFT you could use a Goerzel filter or just a two-tone DFT.
That sounds good. Any idea where can I find an example of how to implement this FFT or the two-tone DFT?


If you have multilpe leds flashing, you need to have an aliasing filter
Some aliasing filter already implemented in Teensy or arduino? I will google it...


Finally if you are worried about processing power, you can offload processing to an audio board
I would preffer not to use any extra HW.


Thank you very much for your help, I really appreciate it.
I will try some options saturday morning and look for more info.
So far I learnt I have to separate more the frequencies, maybe 40 and 60 Hz? And avoid the 50Hz. I also realized my first intentions were not far away from my goal. Thank you again. :)
 
I think for you the easiest way is to use the FFT.
You could look at the Audio library. I assume you can take 128 samples instead of 100. Or perform FFT's with an overlap of 28, if you need an interval of exactly 0.5 second.
The audio library uses the CMSIS FFT. This first needs to be initialized as is done in the header of analyze_fft256.h
arm_cfft_radix4_init_q15(&fft_inst, 256, 0, 1);
Then the data should be placed in a buffer of size 256*2.
Every even index should have the sample, every odd index should be zero (ie. complex part = 0)
To generate 256 samples, just double every sample of the 128.
buffer[0] = value[0];
buffer[1] = 0;
buffer[2] = value[0];
buffer[3] = 0;
buffer[4] = value[1];
...
Then multiply every sample by a window function.
Finally perform the FFT
arm_cfft_radix4_q15(&fft_inst, buffer);
the magnitude can be calculated as:
mag[0] = sqrt(bufffer[0]^2+buffer[1]^2)
mag[1] = sqrt(bufffer[2]^2+buffer[3]^2)
The frequencies associated with a bin is f_sample/N * bin

Correlating a frequency is just multiplying by the complex exponential (and the window)
C = sum(value*window*exp(j*w*t))
where w = 2*pi*f;
and t is the time index.
the window times the complex exponential can be precalculated.
Again you might want to take the absolute value.
If you are not familiar with complex numbers, the C is:
Cre = sum(value*window*cos(w*t))
Cim = sum(value*window*sin(w*t))
abs(C) = sqrt(Cre^2+Cim^2)
 
Last edited:
As for the anti aliasing. Either do it in an analog fashion, eg a simple RC filter, or try oversampling and lowpass filtering. A very crude way of low-pass filtering is averaging. If you are worried about processing power, I know the teensy ADC can perform averaging in hardware (never used it knowingly).
 
Hoping to use an FFT to capture sounds events I started with the sinewave sample and then my mic and using the 256 sample versus 1024 takes (reported) 12% versus 50% of the measured cpu as reported by the analog library. My 256 sampling was taking 2x longer than 1024 - because by default the 'myFFT.averageTogether(1);' is set at 8. Taking that to '1' my sketch is getting 160 complete sets reported myFFT.available() in 464 millis().

Problem would be each 256_FFT bucket resolution would be > 150Hz wide. So unless you have a wider spread of frequencies they may get lost in the noise. Also wondering if your sensor distance is not fixed then modulating the signal for on/off cycle time difference might appear to blend with signal intensity at varied distance/directionality if you sum for average magnitude.

I was looking at 1024_FFT on another thread trying to make it more efficient and was given a formula for the peak frequency that relies on adjacent bucket magnitude around the peak - problem is being in the lowest bucket, there is no bucket below that to factor into the math.
 
In this case since the sampling frequency is 100 Hz and not 44117 Hz, the resolution increases. The resolution of an fft is fsample/N. So you can either increase the N to get a better resolution, or lower the sampling frequency, provided you keep the input frequency below the Nyquist frequency.
@defreagster, if you are using the audio shield, I posted some code in another post to easily adjust the sample clock.
Edit: https://forum.pjrc.com/threads/27736-variable-I2S-master-clock-%28and-sampling%29-frequency
 
Last edited:
Given the drive for the transmit LED is a square wave, will a FFT successfully extract the base frequency or is that going to be swamped by the non linearity in the system? I hit wave theory from the RF end where it was all about minimizing the wasted transmit power, so my class time doesn't help with this.

If the objective is just to find if one or other transmitter is in vicinity rather than using analog measurement an alternative is to use the IR remote code with the two base stations setup to transmit short codes on different time delays (transmit time n, use 5n and 7n) to minimize collisions. This may take longer to 'fix' a location than the FFT method, and would need the IR receiver modules that produce a digital output.
 
The linearity of the transmitter should not matter, as long as the detector remains linear. Since the transmitter transmits a square wave, the fundamental frequency is not harmed. It will only generate harmonics. (These need to be filtered, hence my remark about alias filtering). On the other hand, if the receiver is nonlinear, it will generate all kinds of intermods, and it will be very difficult to tell the original tones. However it could still be solved, knowing there are only two tones.
BTW: I also have an RF/Microwave background.
 
KPC: Indeed - I was relating to my audio sampling experience. If you control the sample rate and collect them you could adjust. I don't have the audio shield to work with.
 
Fast update
It works!

Using kpc advice, and looking at code from the Teensy Audio library and adafruits fft example (https://learn.adafruit.com/fft-fun-with-fourier-transforms/spectrum-analyzer) I have been able to implement a FFT algorithm and detect my leds' frequencies.


More details
I did lots of testing, and finally I am using a FFT with q15 data type, 512 Hz sampling rate, 128 FFT size (repeating values in a 256 sized FFT as kpc explained), adc with 10 bits resolution and no filtering.
From buffer data to magnitude value it takes 500-600 microseconds. Noise from many sources makes magnitude of my slot vary from [0 to 10], and when I face the modulated led from 2.5 meters, magnitude goes to 30 or even 40. :)

Tomorrow I will test further with sun ligth, etc.

With these parameters I have 4 Hz resolution, which is also the frequency at which I can run the FFT and get results, I modulated my leds to 48 and 56 Hz, to make them multiples of 4 and separated by 1 slot.


Some more questions
Is there any improvement if I use prime frequencies instead, for my leds?
What happens if I make the adc resolution 12 bits?
And if I activate the adc averaging to 16 samples for example?



Thank you all very much (especially kpc) :D
 
That is great - did you use the Adafruit code to start? Can you post yours?

<edit> I got to the Adafruit code and it is informative for self sampling - but slow doing the math itself. next step : kpc - indicated passing my sample data to Audio FFT code.
 
Last edited:
@luisonoff: Wrt you questions:
Setting the frequencies at the center of each bin (as you did) will help generate a nice spectrum. Furthermore like someone said earlier, it helps selecting frequencies that do not have harmonics in common. Your selection will have harmonics in common at the 84th bin, respectively for the 7th and the 6th harmonic. I would not worry about this term too much. Choosing primes in general makes your first common bin to be reasonably large, but this is not always the case, due to aliasing etc.. Anyway primes will be a good start when using multiple (>2) leds.

As for the averaging and more bits. This depends on the nature of your noise/disturbance. Is the noise gaussian or pulsed? (Maybe make a histogram). Is it due to quantization? (You can multiply your signal by 32 to make use of the full dynamic range of 16 bits, and thus keeping the truncation noise due to the FFT away) Is it additive or multiplicative? (If it is the same with/without the signal it is additive).

If you are certain the frequencies will stay at the centers of your bins, you might remove the window for a little more S/N.

Edit:
Another idea to improve detection is to generate a matched filter. Since the input is a square wave, the matched filter is just addition/subtraction. Assuming a square wave with 50% duty cycle, the optimum sample frequency would then be 672 Hz and a matched filter length of 84 samples (or multiples of this).
This will give you the best S/N ratio possible, but at the cost of some more processing power.
Before anyone reacts: I know multiplies are as fast as additions, but eg. the multiplies in a DFT needs looking up the twiddle factors. With just addition/subtraction this is not needed, so it can be three times as fast.

Also now that you implemented it. Just being curious does your application require all the processing power you need for other things besides detecting LEDs? Or were you just afraid of the processing power needed for the detection?
 
Last edited:
Status
Not open for further replies.
Back
Top