Sync two FPGAs to generate same Sine Wave - verilog

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.

Related

Sound synthesis with PWM output

I'm trying to synthesize sound on the Arduboy, which is a handheld gaming device with an AVR ATMega32u4 microcontroller and a speaker attached between its pins C6 and C7.
My plan is to use timer 4 to generate a high-frequency PWM signal on C7, and then use timer 3 to change timer 4's duty cycle. For a "hello world"-level program, I'm trying to read 3906 8-bit samples per second from PROGMEM.
First of all, to make sure my sample file is really in the format I think it is, I have used SoX to play it on a computer:
$ play -e unsigned-integer -r 3906 -b 8 sample2.raw
Here's the relevant parts of my code:
pub fn setup() {
without_interrupts(|| {
PLLFRQ::unset(PLLFRQ::PLLTM1);
PLLFRQ::set(PLLFRQ::PLLTM0);
TCCR4A::write(TCCR4A::COM4A1 | TCCR4A::PWM4A); // Set output C7 to high between 0x00 and OCR4A
TCCR4B::write(TCCR4B::CS40); // Enable with clock divider of 1
TCCR4C::write(0x00);
TCCR4D::write(0x00);
TC4H::write(0x00);
OCR4C::write(0xff); // One full period = 256 cycles
OCR4A::write(0x00); // Duty cycle = OCR4A / 256
TCCR3B::write(TCCR3B::CS32 | TCCR3B::CS30); // Divide by 1024
OCR3A::write(3u16); // 4 cycles per period => 3906 samples per second
TCCR3A::write(0);
TCCR3B::set(TCCR3B::WGM30); // count up to OCR3A
TIMSK3::set(TIMSK3::OCIE3A); // Interrupt on OCR3A match
// Speaker
port::C6::set_output();
port::C6::set_low();
port::C7::set_output();
});
}
progmem_file_bytes!{
static progmem SAMPLE = "sample2.raw"
}
// TIMER3_COMPA
#[no_mangle]
pub unsafe extern "avr-interrupt" fn __vector_32() {
static mut PTR: usize = 0;
// This runs at 3906 Hz, so at each tick we just replace the duty cycle of the PWM
let sample: u8 = SAMPLE.load_at(PTR);
OCR4A::write(sample);
PTR += 1;
if PTR == SAMPLE.len() {
PTR = 0;
}
}
The basic problem is that it just doesn't work: instead of hearing the audio sample, I just hear garbled noise from the speaker.
Note that it is not "fully wrong", there is some semblance of the intended operation. For example, I can hear that the noise has a repeating structure with the right length. If I set the duty cycle sample to 0 when PTR < SAMPLE.len() / 2, then I can clearly hear that there is no sound for half of my sample length. So I think timer 3 and its interrupt handler are certainly working as intended.
So this leaves me thinking either I am configuring timer 4 incorrectly, or I am misunderstanding the role of OCR4A and how the duty cycle needs to be set, or I could just have a fundamentally wrong understanding of how PWM-based audio synthesis is supposed to work.
Irrespective of the code you have written above, it seems your design suffers from several flaws:
a) speakers require alternating current to flow through it; it is achieved by varying the tension between a positive and a negative voltage. In your design, the output of your PWM is likely to be between 0 and 5V. If your PWM has a duty cycle of 50%, it turns into an average offset voltage of 2.5V constantly applied to your speaker. This could be fatal to it (the saving grace potentially being flaw 3 below, i.e. not enough current). A common way to fix this is to cut off DC current by connecting the speaker through a capacitor, to filter out any DC current. The value of the capacitor must be adjusted such as it doesn't filter out the signal you wish to use on low frequencies.
b) you shouldn't connect a speaker directly to your microcontroller PINs, for several reasons:
Your microcontroller is likely the expensive device of your board, and should be preserved from devices malfunctions (like shortcuts) that could lead to destroy it.
Your microcontroller can drive max 40mA per io PIN, as described in datasheet, 29.1 Absolute Maximum Ratings . A typical speaker has a resistance varying between 8 Ohms and 32 Ohms, and if we consider a duty cycle of 50%, you are passing in average 20mA across it. To drive your HP efficiently, you would need much more current to flow through. That's why speakers are generally driven by an amplifier stage.
Speakers are devices with coils inside. As such, they store magnetic energy that they yield back to the circuit when the voltage drops, injecting reverse currents. These reverse currents can easily destroy transistor gates if not properly handled. In your case, luckily, the amount of inverse current is low, since you don't drive the HP enough. But you should avoid that situation at all times.
c) Using a PWM to produce sound seems awkward. Since they produce square waves , these are plenty of harmonics that will add a lot of parasitic noises to the sound. But more importantly, PWM output does not allow you to vary the intensity (voltage) of the output, which is normally needed to reproduce sound properly.
To produce sound, you need an digital to analogue converter (DAC), then the proper circuitry to condition that signal and amplify it for a speaker. Unfortunately, the ATMega32u4 doesn't seem to have that feature. You should pick another microcontroller.
For questions on electronic designs, I suggest you to search on https://electronics.stackexchange.com.

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

Pause input into enabled subsystem when valid signal = 0 Simulink

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.

Circuit goes wrong when synthesized with a tight constraint

I have a RTL code.
At first, I synthesized the circuit at 10 ns and run post-synthesis simulation. The circuit worked well.
After that, I changed the timing constraint to 7 ns and re-synthesized the code using:
compile_ultra -retime
DC reported that the circuit has met timing requirements (slack = 0) and there is no design rule violation either. However, the netlist couldn't pass post-synthesis simulation. Does anyone know why?
I have found that Xilinx gate level simulation have (had?) a flaw when running at very high frequencies. This was 10+ years ago so things might have changed!
In my case I was simulating logic running at 300MHz. The results where baffling so I pulled in the most important signals in the waveform display.
The problem turned out to be the clock. The delay in the clock tree is simulated by lumping all the delay in the IBUF buffer. The clock tree behaviour is that of a net- or transport delay: The pulse going in will come out after a while. The IBUF delay model should therefore use a non-blocking delay:
always #( I)
O <= #delay_time I;
But it does not. Instead it uses a standard O = I; blocking statement which gets SDF annotated.
Thus if the high/low period of the input frequency to the buffer is longer then the IBUF delay, clock edges get lost and your gate level simulation fails.
I don't know if Xilinx have fixed that but I would say check your clock.

How to set a signal high X-time before rising edge of clock cycle?

I have a signal that checks if the data is available in memory block and does some computation/logic (Which is irrelevant).
I want a signal called "START_SIG" to go high X-time (nanoseconds) before the first rising edge of the clock cycle that is at 10 MHz Frequency. This only goes high if it detects there is data available and does further computation as needed.
Now, how can this be done? Also, I cannot set a delay since this must be RTL Verilog. Therefore, it must be synthensizable on an FPGA (Artix7 Series).
Any suggestions?
I suspect an XY problem, if start sig is produced by logic in the same clock domain as your processing then timing will likely be met without any work on your part (10MHz is dead slow in FPGA terms), but if you really needed to do something like this there are a few ways (But seriously you are doing it wrong!).
FPGA logic is usually synchronous to one or more clocks,generally needing vernier control within a clock period is a sign of doing it wrong.
Use a {PLL/MCM/Whatever} to generate two clocks, one dead slow at 10Mhz, and something much faster, then count the fast one from the previous edge of the 10MHz clock to get your timing.
Use an MCMPLL or such (platform dependent) to generate two 10Mhz clocks with a small phase shift, then gate one of em.
Use a long line of inverter pairs (attribute KEEP (VHDL But verilog will have something similar) will be your friend), calibrate against your known clock periodically (it will drift with temperature, day of the week and sign of the zodiac), this is neat for things like time to digital converters, possibly combined with option two for fine trimming. Shades of ring oscs about this one, but whatever works.

Resources