Pause input into enabled subsystem when valid signal = 0 Simulink - delay

My simplified Simulink model involves plotting a sine wave going through an enabled subsystem. The simulation time step is 1/(125e6) seconds and the subsystem is only enabled once every 1/(250e3) seconds using a pulse generator. When the subsystem is disabled then the input sine data is 'lost' which is why the output looks like a jagged sine wave in the picture.
I need a way to pause the input data from flowing when the subsystem is disabled so that no sine data is 'lost'. The result should look like a very spread out sine wave. A simple way to accomplish this is to make the sine wave output at a frequency of 250kHz so that it's perfectly synced with the enabled subsystem, but this is not possible for my application.

I need to use an upsample block that has an upsample factor = 125e6/250e3 = 500. This will pad out my sample with an exact amount of 0's so that no data is missed when the enable block is disabled.

Related

ESP8266 analogRead() microphone Input into playable audio

My goal is to record audio using an electret microphone hooked into the analog pin of an esp8266 (12E) and then be able to play this audio on another device. My circuit is:
In order to check the output of the microphone I connected the circuit to the oscilloscope and got this:
In the "gif" above you can see the waves made by my voice when talking to microphone.
here is my code on esp8266:
void loop() {
sensorValue = analogRead(sensorPin);
Serial.print(sensorValue);
Serial.print(" ");
}
I would like to play the audio on the "Audacity" software in order to have an understanding of the result. Therefore, I copied the numbers from the serial monitor and paste it into the python code that maps the data to (-1,1) interval:
def mapPoint(value, currentMin, currentMax, targetMin, targetMax):
currentInterval = currentMax - currentMin
targetInterval = targetMax - targetMin
valueScaled = float(value - currentMin) / float(currentInterval)
return round(targetMin + (valueScaled * targetInterval),5)
class mapper():
def __init__(self,raws):
self.raws=raws.split(" ")
self.raws=[float(i) for i in self.raws]
def mapAll(self):
self.mappeds=[mapPoint(i,min(self.raws),max(self.raws),-1,1) for i in self.raws ]
self.strmappeds=str(self.mappeds).replace(",","").replace("]","").replace("[","")
return self.strmappeds
Which takes the string of numbers, map them on the target interval (-1 ,+1) and return a space (" ") separated string of data ready to import into Audacity software. (Tools>Sample Data Import and then select the text file including the data). The result of importing data from almost 5 seconds voice:
which is about half a second and when I play I hear unintelligible noise. I also tried lower frequencies but there was only noise there, too.
The suspected causes for the problem are:
1- Esp8266 has not the capability to read the analog pin fast enough to return meaningful data (which is probably not the case since it's clock speed is around 100MHz).
2- The way software is gathering the data and outputs it is not the most optimized way (In the loop, Serial.print, etc.)
3- The microphone circuit output is too noisy. (which might be, but as observed from the oscilloscope test, my voice has to make a difference in the output audio. Which was not audible from the audacity)
4- The way I mapped and prepared the data for the Audacity.
Is there something else I could try?
Are there similar projects out there? (which to my surprise I couldn't find anything which was done transparently!)
What can be the right way to do this? (since it can be a very useful and economic method for recording, transmitting and analyzing audio.)
There are many issues with your project:
You do not set a bias voltage on A0. The ADC can only measure voltages between Ground and VCC. When removing the microphone from the circuit, the voltage at A0 should be close to VCC/2. This is usually achieved by adding a voltage divider between VCC and GND made of 2 resistors, and connected directly to A0. Between the cap and A0.
Also, your circuit looks weird... Is the 47uF cap connected directly to the 3.3V ? If that's the case, you should connect it to pin 2 of the microphone instead. This would also indicate that right now your ADC is only recording noise (no bias voltage will do that).
You do not pace you input, meaning that you do not have a constant sampling rate. That is a very important issue. I suggest you set yourself a realistic target that is well within the limits of the ADC, and the limits of your serial port. The transfer rate in bytes/sec of a serial port is usually equal to baud-rate / 8. For 9600 bauds, that's only about 1200 bytes/sec, which means that once converted to text, you max transfer rate drops to about 400 samples per second. This issue needs to be addressed and the max calculated before you begin, as the max attainable overall sample rate is the maximum of the sample rate from the ADC and the transfer rate of the serial port.
The way to grab samples depends a lot on your needs and what you are trying to do with this project, your audio bandwidth, resolution and audio quality requirements for the application and the amount of work you can put into it. Reading from a loop as you are doing now may work with a fast enough serial port, but the quality will always be poor.
The way that is usually done is with a timer interrupt starting the ADC measurement and an ADC interrupt grabbing the result and storing it in a small FIFO, while the main loop transfers from this ADC fifo to the serial port, along the other tasks assigned to the chip. This cannot be done directly with the Arduino libraries, as you need to control the ADC directly to do that.
Here a short checklist of things to do:
Get the full ESP8266 datasheet from Expressif. Look up the actual specs of the ADC, mainly: the sample rates and resolutions available with your oscillator, and also its electrical constraints, at least its input voltage range and input impedance.
Once you know these numbers, set yourself some target, the math needed for successful project need input numbers. What is your application? Do you want to record audio or just detect a nondescript noise? What are the minimum requirements needed for things to work?
Look up in the Arduino documentartion how to set up a timer interrupt and an ADC interrupt.
Look up in the datasheet which registers you'll need to access to configure and run the ADC.
Fix the voltage bias issue on the ADC input. Nothing can work before that's done, and you do not want to destroy your processor.
Make sure the input AC voltage (the 'swing' voltage) is large enough to give you the results you want. It is not unusual to have to amplify a mic signal (with an opamp or a transistor), just for impedance matching.
Then you can start writing code.
This may sound awfully complex for such a small task, but that's what the average day of an embedded programmer looks like.
[EDIT] Your circuit would work a lot better if you simply replaced the 47uF DC blocking capacitor by a series resistor. Its value should be in the 2.2k to 7.6k range, to keep the circuit impedance within the 10k Ohms or so needed for the ADC. This would insure that the input voltage to A0 is within the operating limits of the ADC (GND-3.3V on the NodeMCU board, 0-1V with bare chip).
The signal may still be too weak for your application, though. What is the amplitude of the signal on your scope? How many bits of resolution does that range cover once converted by the ADC? Example, for a .1V peak to peak signal (SIG = 0.1), an ADC range of 0-3.3V (RNG = 3.3) and 10 bits of resolution (RES = 1024), you'll have
binary-range = RES * (SIG / RNG)
= 1024 * (0.1 / 3.3)
= 1024 * .03
= 31.03
A range of 31, which means around Log2(31) (~= 5) useful bits of resolution, is that enough for your application ?
As an aside note: The ADC will give you positive values, with a DC offset, You will probably need to filter the digital output with a DC blocking filter before playback. https://manual.audacityteam.org/man/dc_offset.html

Sync two FPGAs to generate same Sine Wave

I am using the Spartan 3e Xilinx FPGA board, and I am trying to sync two FPGAs to generate the same sine wave. Due to limited I/O pins there is only one connection from the Master to Slave. Is there a way to sync them up and set the phase of the sine wave?
For example when the master hits zero phase a flag raises and the slave is set to zero phase too.
The function prototype of the sine lut is given below. I am just starting out so any help is appreciated thank you.
sine sine_lut (
.ce(clock_enable), // input ce
.clk(CLK_50MHZ&& clock_enable), // input clk
.sclr(!clock_enable),
.pinc_in(line_freq[31:0]), // input [31 : 0] pinc_in
.poff_in(0), // input [31 : 0] poff_in
.sine(sine_generate[12:0]), // output [12 : 0] sine
.phase_out(phase_out) // output [31 : 0] phase_out
);
The method mentioned in the question would work to some extent:
If the jitter of the clocks is not that big to cause a significant desynchronisation during the period of the sine wave
If some discontinuity in the slave output is tolerable.
In order to overcome the discontinuity you can modify the method as following. Instead of just resetting the waveform, simply readjust the frequency of the signal on the slave to be slightly higher or lower for the next period, depending on whether it is too fast or too slow. You can do this using PID control technique, for example (the adjustment will be proportional to the phase error). Or simply recalculate the frequency based on the measured time between sync pulses.
If the sine wave frequencies are much slower than the clock frequency, you can utilise the PWM technique to encode the sine values of the master as a signal Duty Cycle, measure it on the slave and output the same value. A very small phase shift is expected, but again, it shouldn't be noticeable if the clock is much faster than the sine.

Generate sine wave using ADC

I have a adc module on my board. I create a sine wave on signal generator. And I give output of this generator to a adc pin. Finally I read value of this pin periodically. I try to create a sine wave on my software.
x = t,
y = Asin(wt),
A : amptitute value of the generator,
w : 2πf, f : I set its value on my software.(difference time between two read operation)
t : time
And I don't use value of adc pin. Isn't this value important to create wave?
I will try to provide you with some hints based on what I understood from your post.
The ADC is supposed to sample the analogue signal generated at a defined frequency in order to yield a digital signal. In your case, you need two information to trace your curve:
Data:
data to be traced (samples) which represents the amplitude of the signal all along sampling time (at each sampling instant).
Time:
you need to know the period in time at which ADC is sampling the signal then associate each data with its corresponding instant in time. Period can be deduced from the frequency at which ADC samples signal T = 1/f.
ADC stores each sampled data in a register and an interrupt would be generated to notify processor about a new coming data. Your interrupt service routine (in case you are proceeding with interrupts) must be able to extract that data before it will be replaced by the next sample. As a suggestion, you may create a buffer within your application where your interrupt routine could store data in it. Then, your application can extract data from buffer and use it to draw the curve if your system has a display output or send it to a desktop application that will do the job.
You don't need to stick to the equation in your post; it is for analogue. Rather you can think of the digitized curve as f(t) = Data(t).
As you are using linux, if you don't want to deal with interrupts you may proceed with reading data using /sysfs interface. Note that opening a file to read data for every single sample could be slow depending on your application requirements.

Overlap add in audio analysis-synthesis

I wrote some code that takes an audio signal (currently a sine wave) as an input and does the following:
Take frames of n (1024) samples
Apply FFT
Apply iFFT
Play output
With this process the output signal is basically the same as the input signal.
Now, in a second attempt I do:
Take overlapping frames from the input
Apply a window function
FFT
iFFT
Overlap the output frames
In step 1, if I take overlapping frames using a hop size (number of samples to jump to take next frame) of a power of 2 (4, 8, 256...) the output sound is smooth and resembles the original input sound, but with any other hop size, the sound starts to crack down. This happens for any frequency of the input signal. Question 1. Why is the sound smooth only if the hop size is 2^n?.
Currently I use a Hanning window. When the hop size is large (e.g. 512) the output sound has a lower volume than when the hop size is small (e.g.64). This seems an expected behavior, because a small hop-size implies that a sample is reconstructed with more frames, so more signals are added. Question 2. Is there a way to properly scale the output signal so that the volume resembles the original signal?
Thank you!
This should not be happening, Overlap-add method can reconstruct your signal without the problems described, we not know exactly what are you doing, I did it some time ago and its works for any hop size and window size, a small secret is apply zeros after and before your signal to ensure a continuous signal, if you look calmly will realize that your window function works like a fade-in/fade-out if you just concatenate the frames you will notice some clicks or the output signal will look like a vibrato, gets a little tricky to tell where your problem actually find !
Just for Debug, skip the FFT and iFFT steps and see if your signal was correctly constructed, if yes your overlap-add process works, and your problem can be in your FFT/iFFT ...
Overlap-add is normally done without using a non-rectangular window function. Zero-pad instead.
If you do use a window function, then you have to make sure that all the offset window functions sum to a constant level, which for a Von Hann window happens with certain offsets (except at the very beginning or end of the series sum). As
2 - (cos(x)+cos(x+Pi)) == 2
Sum more windows into a result without any scaling, and of course the level of the sum will increase.

Does ADPCM has some sample rate?

ADPCM is adaptive, so it has varible sample rate. But does it have some average rate or something? Does it have frames of fixed time duration?
You misunderstood it here :-). "Adaptive" doesn't mean that sample rate is adjusted according to the signal it contains.
"Adaptive" means that the limited available delta steps (4Bit = only 16 possibilities to encode a sample) are adapted to the signal by prediction. It attempts to approximate from a given sample which value the next sample may have and adapts the delta steps to that.
If the signal has less change from sample to sample, the steps are chosen closer togheter than if the signal has much change. It is very unlikely that the signal goes from very oscillating to quiet from one sample to the next.
You notice that behavior if you encode a square wave with 100Hz using such algorithm and re-open it in an audio editor that makes the waveform visible. When the waveform changes from one polarity to other, the signal "speeds up" (the steps are more and more apart) until it reaches the other end and then it slows down again (The steps are more and more close togheter).
It still has a fixed sample rate. The one you will give to it. In RIFF WAVE, the sample rate is stored in the header.

Resources