Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Signal sources: oscillators, CORDIC and waveforms

ProblemGenerate sinusoids, quadrature carriers, periodic waveforms and noise at exact frequencies, cheaply and reproducibly, and shift signals in frequency
Devised byJack Volder (1959), CORDIC; John Walther (1971), the unified CORDIC; Joseph Tierney, Charles Rader and Bernard Gold (1971), the direct digital synthesiser
AccuracyThe 64-bit phase accumulator has a frequency resolution of ; a 32-bit CORDIC gains about one bit per iteration (table below)
CostOne addition per sample for the phase; one sin_cos or shift-and-add steps for the waveform
Read firstBackground: frequency responses
APINco, NcoSource (with SineWave, QuadratureWave, SquareWave, TriangleWave, RampWave, PulseTrainWave, NoiseWave), Cordic32, Cordic64, cordic_sin_cos, FrequencyMixer

Overview

Test signals, carriers and local oscillators all start from a numerically controlled oscillator (NCO): an integer phase accumulator that wraps around once per cycle, advanced by a fixed tuning word each sample. A waveform function turns the phase into a sample: a sine, a quadrature pair , a ramp, triangle, square or pulse train, or held noise. Integer phase makes the frequency exact and the phase free of drift. The sine itself can come from the floating-point sin or from CORDIC, which rotates a vector by shifts and additions only, as hardware does. A frequency mixer multiplies a signal by a complex exponential to move its spectrum.

Where it is used

Almost every signal in a digital system starts as a number generated by an oscillator, a table or an algorithm.

  • Software-defined radio. Local oscillators and quadrature carriers are generated digitally (and cheaply, with CORDIC) to mix signals to baseband.
  • Test and measurement. Signal generators and arbitrary-waveform generators produce sines, squares, sweeps and noise at exact frequencies; the same code makes test signals for your own filters.
  • Audio and music. Synthesisers and tone generators are oscillators with careful control of frequency and phase.

History

Jack Volder (1959) devised CORDIC (coordinate rotation digital computer) at Convair for the navigation computer of the B-58 bomber, which had to compute trigonometric functions without a multiplier. John Walther (1971) at Hewlett-Packard unified it to cover hyperbolic and linear functions, and it became the algorithm of the HP-35 calculator. Joseph Tierney, Charles Rader and Bernard Gold (1971) described the direct digital frequency synthesiser: a phase accumulator addressing a sine table. NCOs of this kind are in every software radio.

The idea

Phase accumulation

A numerically controlled oscillator (NCO) generates the samples of a sinusoid, , one after another. It does so in two stages: keep track of the phase, then convert the phase to an amplitude.

The phase advances by the same amount, of a full turn, at every sample. The obvious implementation adds that amount to a floating-point variable, and has two flaws: each addition rounds, so the phase slowly drifts, and the phase must be wrapped back into one turn from time to time. Both disappear if the phase is kept as an unsigned integer that represents a fraction of a turn. With a -bit phase accumulator, the value stands for one full turn. The tuning word for frequency at rate is

and the phase after samples is . Integer addition is exact, so no error accumulates however long the oscillator runs, and the overflow of the integer is the wrap-around of the phase, at no cost. The only error is the rounding of itself, which makes the frequency inexact by at most . The library uses , so the frequency is exact to (about Hz at 1 MHz). next_phase_modulated adds a per-sample offset to the phase, giving frequency modulation.

CORDIC

The second stage converts the phase to and . A table lookup or a library call would do, but hardware and fixed-point processors often have no multiplier to spare. CORDIC (coordinate rotation digital computer) computes sines and cosines using only shifts and additions.

The idea. The point is the vector rotated by the angle . A rotation by an angle can be written

If is a power of two, , the multiplications inside the brackets are just shifts of a binary number. So CORDIC builds the rotation by out of micro-rotations by the fixed angles (, , , , …), each applied either forwards or backwards. Any angle in the first quadrant can be approximated by such a sum of signed angles, much as a number is approximated by binary digits. A third variable holds the angle still to be rotated, and the sign of each micro-rotation is chosen to drive towards zero:

Each step is two shifts and three additions; the angles come from a small table.

The gain. The formulas above omit the factor of each micro-rotation, so every step also stretches the vector slightly, by . Because every micro-rotation is performed, in one direction or the other, the total stretch is the same for every angle: . It is compensated in advance by starting from the vector .

The quadrant is taken from the top two bits of the phase first, so the iterations only have to cover . Each iteration adds about one bit of accuracy:

Table 16.1. CORDIC accuracy against the number of iterations.

CORDIC iterations (32-bit)largest error in sin and cosequivalent bits
87.7e-37.0
124.8e-411.0
163.0e-515.0
201.9e-619.0
241.2e-723.0
281.3e-826.2

A short CORDIC’s errors are periodic in the phase, so they appear in the spectrum as spurs, not noise:

Figure 16.1. NCO spurs.

Cordic32 uses 32-bit integers and reaches about ; Cordic64 takes the oscillator’s full 64-bit phase and reaches double precision with 52 or more iterations.

Waveforms and noise

The other waveforms read the phase directly. A ramp is the phase itself, scaled to . A triangle folds it. A square wave or pulse train compares it with a duty cycle. Noise sources draw a new uniform or Gaussian value every sample (white), or each time the phase wraps (sample-and-hold, a crude band-limited noise). All are seeded, so a test signal is reproducible.

Frequency mixing

Multiplying a complex signal by shifts its spectrum by : down-conversion to baseband in a receiver, or up-conversion in a transmitter. Multiplying a real signal by a real cosine instead produces both the sum and the difference frequencies, which is why receivers mix with a quadrature (complex) oscillator. FrequencyMixer keeps a floating-point phase, wrapped every cycle.

Algorithm

Oscillator (next_phase): return the current value of the 64-bit phase accumulator, then add the tuning word to it, letting the addition wrap round.

CORDIC, converting a phase to a cosine and sine, in integer arithmetic.

  1. Quadrant. The top two bits of the phase say which quarter turn it lies in. Remove them; what remains is an angle in .
  2. Start from the vector , already rotated by that number of quarter turns (a quarter turn only exchanges the two components and changes signs), with set to the remaining angle.
  3. Iterate for up to the chosen number of iterations: let if and otherwise; replace by , where is a right shift by bits, with rounding; subtract , read from a table, from .
  4. Return as the cosine and as the sine.

The cost is three additions and two shifts per iteration.

A waveform sample: take the next phase; map it to a value by the waveform’s rule (the CORDIC for a sinusoid, the phase itself for a ramp, a fold for a triangle, a comparison with the duty cycle for a square wave); multiply by the amplitude and add the offset.

Frequency mixer: multiply each input sample by , then advance by and wrap it into one cycle.

Implementation

    pub fn next_phase(&mut self) -> Phase {
        let current = Phase(self.phase);
        self.phase = self.phase.wrapping_add(self.increment);
        current
    }
                let (mut x, mut y): ($W, $W) = match angle >> ($ABITS - 2) {
                    0 => (inv_gain, 0),
                    1 => (0, inv_gain),
                    2 => (-inv_gain, 0),
                    _ => (0, -inv_gain),
                };
                let mut z = (angle & (<$A>::MAX >> 2)) as $W;
                for i in 0..self.iterations {
                    let (dx, dy) = (Self::shr_round(y, i), Self::shr_round(x, i));
                    let theta = $ATAN[i as usize] as $W;
                    if z >= 0 {
                        x -= dx;
                        y += dy;
                        z -= theta;
                    } else {
                        x += dx;
                        y -= dy;
                        z += theta;
                    }
                }
                (y, x)
            }
  • The CORDIC types are generated by one macro for 32-bit and 64-bit arithmetic. The arctangent table and the gain compensations for every iteration count are constants.
  • NcoSource::generate(n) returns n samples; every source also implements Waveform, so new shapes plug into the same oscillator.

In practice

//! Signal sources: numerically controlled oscillators, CORDIC and periodic waveforms.

use lib_jsl_dsp::discrete::sources::cordic::{Cordic32, cordic_sin_cos};
use lib_jsl_dsp::discrete::sources::nco::{Nco, NcoSource};
use lib_jsl_dsp::discrete::sources::quadrature::{Polarity, QuadratureWave};
use lib_jsl_dsp::discrete::sources::sinusoid::SineWave;
use lib_jsl_dsp::discrete::sources::square::SquareWave;

fn main() {
    // A 1 kHz tone at 48 kHz: the 64-bit phase accumulator steps by f/fs of a turn.
    let mut nco = Nco::new(1000.0, 48000.0).unwrap();
    for _ in 0..12 {
        nco.next_phase();
    }
    println!("phase after 12 samples: {:.6} turns (exact 0.25)", nco.phase().turns());
    let mut sine = NcoSource::<SineWave>::sinusoid(1000.0, 48000.0).unwrap();
    println!("sine: {:.4?}", sine.generate(4));
    let mut iq = NcoSource::<QuadratureWave>::quadrature(1000.0, 48000.0, Polarity::Positive).unwrap();
    println!("quadrature: {}", iq.generate(2).iter().map(|c| format!("{c:.4}")).collect::<Vec<_>>().join(", "));
    let mut square = NcoSource::<SquareWave>::square_with_duty(12000.0, 48000.0, 0.25).unwrap();
    println!("square, duty 0.25: {:?}", square.generate(8));
    let (s, c) = cordic_sin_cos(0.5);
    println!("CORDIC sin/cos(0.5) = {s:.9}, {c:.9} (exact {:.9}, {:.9})", 0.5f64.sin(), 0.5f64.cos());
    let coarse = Cordic32::new(10).unwrap();
    println!("10-iteration CORDIC: sin(0.5) = {:.5}, gain constant {:.6}", coarse.sin_cos(0.5).0, coarse.gain());
}
phase after 12 samples: 0.250000 turns (exact 0.25)
sine: [0.0000, 0.1305, 0.2588, 0.3827]
quadrature: 1.0000+0.0000i, 0.9914+0.1305i
square, duty 0.25: [1.0, -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, -1.0]
CORDIC sin/cos(0.5) = 0.479425540, 0.877582562 (exact 0.479425539, 0.877582562)
10-iteration CORDIC: sin(0.5) = 0.47850, gain constant 1.646759

Strengths

  • Exact frequencies and drift-free phase; multiplier-free sines and cosines with CORDIC.
  • Reproducible, composable sources for testing every other algorithm.

Weaknesses

  • Square, ramp and pulse waveforms are not band-limited: their harmonics alias.
  • Short CORDICs and truncated phases produce spurs, not white noise.

Exercises

  1. Find the tuning word and the actual frequency for 1 kHz at 48 kHz with a 32-bit accumulator, and the frequency error.
  2. Show that the CORDIC gain converges to about 1.64676 as the number of iterations grows.
  3. Show that , so CORDIC covers a quarter turn.
  4. Mix a real 1 kHz tone with a real 1.1 kHz cosine and identify the two products; repeat with a complex exponential.
  5. Generate a band-limited square wave by summing odd harmonics below Nyquist, and compare its spectrum with SquareWave’s.
Hints and answers
  1. The tuning word is and the actual frequency is Hz, an error of about Hz.
  2. ; the product converges quickly because the factors approach 1 like .
  3. .
  4. A real mix of 1 kHz and 1.1 kHz tones gives products at 100 Hz and 2.1 kHz; a complex exponential mixed with a complex exponential gives only one product, at the sum or difference frequency, without the mirror image.
  5. Sum for ; the library’s square wave is not band-limited unless the entry says so, so compare the harmonic levels and the aliases of the rest.

Further reading

  • J. E. Volder, “The CORDIC trigonometric computing technique”, IRE Transactions on Electronic Computers 8 (1959) 330–334.
  • J. S. Walther, “A unified algorithm for elementary functions”, Proceedings of the Spring Joint Computer Conference (1971) 379–385.
  • J. Tierney, C. M. Rader and B. Gold, “A digital frequency synthesizer”, IEEE Transactions on Audio and Electroacoustics 19 (1971) 48–57.
  • R. Andraka, “A survey of CORDIC algorithms for FPGA based computers”, Proceedings of the ACM/SIGDA FPGA Symposium (1998) 191–200.