in ,

Homemade GPS Receiver (2011), Hacker News

[15]

************** [1] ************************ [15:0,31:16] Pictured above is the front-end, first mixer and IF amplifier of an experimental GPS receiver. The leftmost SMA is connected to a commercial antenna with integral LNA and SAW filter. A synthesized first local oscillator drives the bottom SMA. Pin headers to the right are power input and IF output. The latter is connected to a Xilinx FPGA which not only performs DSP, but also hosts a fractional-N frequency synthesizer. More on this later. I was motivated to design this receiver after reading the work [1] of Matjaž Vidmar, S 53 MV, who developed a GPS receiver from scratch, using mainly discrete components, over years ago. His use of DSP following a hard-limiting IF and 1-bit ADC interested me. The receiver described here works on the same principle. Its 1-bit ADC is the 6-pin IC near the pin headers, an LVDS-output comparator. Hidden under noise but not obliterated in the bi-level quantized mush that emerges are signals from every satellite in view. All GPS satellites transmit on the same frequency, (****************************************************************************************************************************************************************************. ******************************************************************************************************************************************************************************************************************************************************** (MHz, using direct sequence spread spectrum (DSSS ). The L1 carrier is spread over a 2 MHz bandwidth and its strength at the Earth’s surface is – 174 dBm. Thermal noise power in the same bandwidth is – 119 dBm, so a GPS signal at the receiving antenna is ~ dB below the noise floor. That any of the signals present, superimposed one on another and buried in noise, are recoverable after bi-level quantisation seems counter-intuitive! I wrote asimulationto convince myself. GPS relies on the correlation properties of pseudo-random sequences called Gold Codes to separate signals from noise and each other. Every satellite transmits a unique sequence. All uncorrelated signals are noise, including those of other satellites and hard-limiter quantisation errors. Mixing with the same code in the correct phase de-spreads the wanted signal and further spreads everything else. Narrow-band filtering then removes wideband noise without affecting the (once again narrow) wanted signal. Hard-limiting (1-bit ADC) degrades SNR by less than 3 dB, a price worth paying to avoid hardware AGC. (May) **************************************************************************************************************************************************************** (Update) This is now a truly portable, battery-powered, – channel GPS receiver with turnkey software, which acquires and tracks satellites, and continuously recalculates its position, without user-intervention. The complete system (below, left) comprises: (x2 LCD display, Raspberry PiModel “A” computer, two custom printed-circuit boards, commercial patch antenna and Li-Ion battery. Total system current consumption is 0.4A for a battery life of 5 hours. The Raspberry Pi is powered through the ribbon cable linking its GPIO header to the “Frac7” FPGA board and requires no other connections. Currently, the Pi is running Raspbian Linux. A smaller distro would shorten time to first fix. After booting from SD-Card, the GPS application software starts automatically. On exit, it provides a means to properly shutdown the Pi before powering-off. Pi software development was done “head-less” via SSH and FTP over a USB Wi-Fi dongle. Source code and documentation can be found towards the bottom of this page. Both custom PCBs are simple 2-layer PTH boards with continuous ground plans on the bottom. Going clockwise around the Xilinx Spartan 3 on the “Frac7” FPGA board: from o’clock to 3 o’clock are the loop filter, VCO, power splitter and prescaler of the microwave frequency synthesizer; bottom right are the joystick and JTAG connector; and, at 6 o’clock, a pin header for the Raspberry Pi ribbon cable. Far left is the LCD connector. Near left is a temperature-compensated voltage-controlled crystal oscillator (TCVCXO) providing a stable reference frequency, vital for GPS reception. The TCVCXO is good; but not quite up to GPS standard when operating un-boxed in windy locations. Blowing on it displaces the [15:0,31:16] ****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************** 06 MHz crystal oscillator by around 1 part in 011 million or 1 Hz, which is magnified times by the synthesizer PLL. This is enough to momentarily unlock the satellite tracking loops, if done suddenly. The device is also slightly sensitive to infra-red e.g. from halogen bulbs and TV remotes! When first posted in (*********************************************************************************************************************************************************************, this was a four-channel receiver, meaning it could only track four satellites simultaneously. At least four are required to solve for user position and receiver clock bias; but greater accuracy is possible with more. In that original version, four identical instances of the “tracker” module filled the FPGA. But most of the flops were only clocked once per millisecond. Now, a custom “soft-core” CPU inside the FPGA serializes the processing and only 52% of the FPGA fabric is required for an 8-channel receiver or (% for) ********************************************************************************************************************************************************************************************************************************************************************************** – channels. Number of channels is a parameter in the source and could go higher. Positional accuracy is best when the antenna can see ° of sky and receive signals from all directions. Generally, the more satellites in view, the better. Two or more satellites on the same bearing can lead to what is termed “bad geometry.” The best fix so far was ± 1 meters at a very open location using 17 satellites; but accuracy is typically ± 5 meters in poorer locations with fewer satellites. (September) ****************************************************************************************************************************************************************** (Update) Thesource codefor this project has been re-released under the GNU General Public License (GPL). Architecture

Processing is split between FPGA and Pi by complexity and urgency. The Pi handles math-intensive heavy-lifting at its own pace. The FPGA synthesizes the first local oscillator, services high-priority events in real-time and tracks satellites autonomously. The Pi controls the FPGA via an SPI interface. Conveniently, the same SPI is used to load the FPGA configuration bitstream and binary executable code for the embedded CPU. The FPGA can also be controlled via a JTAG cable from a Windows PC and auto-detects which interface is in use. [15:0,31:16] L1 frequencies are down-converted to a 1st IF of .6 MHz by mixing with aMHz local oscillator on the “GPS3” front-end board. All subsequent IF and baseband signal processing is done digitally in the FPGA. Two proportional-integral (PI) controllers per satellite, track carrier and code phase. NAV data transmitted by the satellites is collected in FPGA memory. This is uploaded to the Pi, which checks parity and extracts ephemerides from the bit stream. When all required orbital parameters are collected, a snapshot is taken of certain internal FPGA counters, from which time of transmission is computed to ± 17 ns precision. Much of the (****************************************************************************************************************************************************************************. MHz synthesizer is implemented in the FPGA. One might expect jitter problems, co-hosting a phase detector with other logic, but it works. Synthesizer output spectral-purity is excellent, even though the FPGA core is toggling away furiously and not all on harmonically-related frequencies. This approach was taken because a board similar to “Frac7” already existed from an earlier synthesizer project. Adding a front-end was the shortest route to a prototype receiver. But that first version was not portable: it had inconvenient power requirements and no on-board frequency standard. Front-endSignal processing up to and including the hard-limiter: [15:0,31:16] ********** [15:0,31:16] ************************** The LMH 10000 comparator has a maximum input offset voltage of 9.5mV. Amplified thermal noise must comfortably exceed this to keep it toggling. Weak GPS signals only influence the comparator near zero crossings! They are “sampled” by the noise! To estimate noise level at the comparator input we tabulate gains, insertion losses and noise figures: (**************************************          LNA [31:0] ****************************          SAW [31:0] ****************************          Coax [31:0] ****************************         

RF (*************************************         Mixer [31:0] ****************************         

IF (*************************************          [15:0] ******************************** Overall system noise figure (**************************************      (************************************ (Gain)          27

         – 1.5         – 3.9         19         – 6         [15:0] ****************************      (************************************ (NF)          0.8 [31:0] ****************************         1.5 (*************************************          3.9 [31:0] ****************************          2) **************************************          6 [31:0] ****************************          7 [31:0] ****************************          [15:0] **************************** (0.8 dB) ***************************************

     (**************************************** [15:0] In-band noise at the mixer output is – 0.8 31 – 1.5-3.9 – 6 log (2.5e6)=- (dBm or************************************************************************************************************************************************************************************************************************************ RV RMS. The mixer is resistively terminated in 52 – ohms and the stages thereafter work at higher impedance. The discrete IF strip has an overall voltage gain of so the comparator input level is 52 mV RMS. The LMH 10000 adds 60 dB of gain making a total of dB for the whole IF. Deploying so much gain at one frequency was a risk. To minimise it, balanced circuitry over a solid ground plane was used and screened twisted-pair carries the output to the FPGA. The motivation was simplicity, avoiding a second conversion. In practice, the circuit is stable, so the gamble paid-off. (********************** [1] (************************* Active decoupler Q1 supplies 5V for the remote LNA. MMIC amplifier U2 provides 21 dB gain (not at IF!) and ensures low overall system noise figure, even if long antenna cables are used. L1 and L2 are hand-wound microwave chokes with very high self-resonant frequency, mounted perpendicular to one another and clear of the ground plane. Wind Wind ********************************************************************************************************************************************************************************************************************************** turns, air-cored, 1mm inside diameter from 7cm lengths of 32 swg enameled copper wire. Checked with the tracking generator on a Marconi 3000 SA, these were good to 4 GHz. The Mini-Circuits MBA – L DBM was chosen for its low 6 dB conversion loss at 1.5 GHz and low 4 dBm LO drive requirement. R9 terminates the IF port. Three fully-differential IF amplifier stages follow the mixer. Low-Q parallel tuned circuits strung between collectors set the -3 dB bandwidth around 2.5 MHz and prevent build-up of DC offsets. L4, L5 and L6 are screened Toko 7mm coils. The BFS was chosen for its high (but not too high) 1 GHz f T [15:0,31:16] ********************************. I (e) *********************************** is 2mA for lowest noise and reasonable βr

(********************************************. The (************************************************************************************************************************************************************************************************************************************************************************. 6 MHz 1st IF is digitally down-converted to 2.6 MHz by under-sampling at 11 MHz in the FPGA. 2.6 MHz lies close to the center of the 5 MHz Nyquist bandwidth. It is best to avoid the exact center, for reasons that will be explained later. Several other first IF frequencies are possible: 28 .5 MHz, which produces spectrum inversion at the 2nd IF, has also been tried successfully. There is a trade-off between image problems at lower and available BFS gain at higher frequencies. (SearchSignal detection entails resolving three unknowns: what satellites are in view, their Doppler shifts and code phases. A sequential search of this three-dimensional space from a so-called “cold start” could take many minutes. A “warm start” using almanac data to predict positions and velocities still requires a code search. All code phases must be tested to find the maximum correlation peak. Calculating correlation integrals in the time-domain is very expensive and redundant . This GPS receiver uses an FFT-based algorithm that tests all code phases in parallel. From cold, it takes 2.5 seconds on a 1.7 GHz Pentium to measure signal strength, Doppler shift and code phase of every visible satellite. The Raspberry Pi is somewhat slower.With over-bar denoting conjugation, the cross-correlation function y (Τ) of complex signal s (t) and code c (t) shifted by offset Τ is: (********************************************* (**********************

(The Correlation Theorem) states that the Fourier transforms of a correlation integral is equal to the product of the complex conjugate of the Fourier transform of the first function and the Fourier transform of the second function: FFT (y)=CONJUGATE (FFT (s)) * FFT (c) (************************************************** Correlation is performed at baseband. The 1. (Mbps C / A code is chips or 1ms long. Forward FFT length must be a multiple of this. Sampling at (MHz for 4 ms results in an FFT bin size of 250 Hz. 42 Doppler shifts must be tested by rotating the frequency domain data, one bin at a time, up to ± bins=± 5 KHz. Rotation can be applied to either function. [1] The (************************************************************************************************************************************************************************************************************************************************************************. 6 MHz 1st IF from the 1-bit ADC is under-sampled by a 11 MHz clock in the FPGA, digitally down-converting it to a 2nd IF of 2.6 MHz. In software, the 2nd IF is down-converted to complex baseband (IQ) using quadrature local oscillators. For bi-level signals, the mixers are simple XOR gates. Although not shown above, the samples are temporarily buffered in FPGA memory. The Pi is not able to accept them at Mbps. 1. Mbps and 2.6 MHz are generated by numerically-controlled-oscillator (NCO) phase accumulators. These frequencies are quite large compared to the sampling rate, and are not exact sub-harmonics of it. Consequently, the NCOs have fractional spurs. The number of samples per code chip dithers between 9 and 11. Fortunately, DSSS receivers are tolerant of narrow-band interferers, external or self-generated. Complex baseband is transformed to the frequency domain by a forward FFT which need only be computed once. An FFT of each satellite’s C / A code is pre-computed. Processing time is dominated by the inner-most loop which performs shifting, conjugation, complex multiplication and one inverse-FFT per satellite-Doppler test. The Raspberry Pi’s Videocore GPU could be leveraged to speed things up. At (MHz sampling rate, code phase is resolved to the nearest 103 ns. Typical CCF output is illustrated below: (*********************************************[15] ************************ (********************************************** Calculating peak to average power over this data gives a good estimate of SNR and is used to find the strongest signals. The following were received at (**************************************************************************************************************************************************************************************************************************************************************************: 16 GMT on 4 March in Cambridge, UK with the antenna on an outside North-facing window ledge: (PRN) ************************************** (NAVSTAR) ************************************Doppler (Hz)

(Code Phase) ************************************** (SNR) ****************************************************

9) *******************************************************************************************************************************************************************************************************************************************************************************

(******************************************************************************************************************************************************************************(2.4) ************************************* (****************************************************************************************************************************************************************************************************************************************** (3) (****************************************(************************************ 59

[15:0] ******************************************************************************************************************************************************************************************** (************************************ 5. ********************************4 ******************************************************

22

**************************************** (************************************ (**************************************************************************************************************************************************************************************** [15:0] **************************** (********************************************************************************************************************************************************************************************. (7) ********************************** (****************************************************************************************************************************************************************************************************************************************************[15:0,31:16] ****************************** (************************************** 25 28 (0) **********************************800. 0(******************************************************************************************************************************************************************************************************************************************************. 8 8) ************************** [15:0] ************************ (**************************************** (********************************************************************************************************************************************************************************************************************************************************– (************************************************************************************************************************************************************************************************************************************** 9**************** 1) **************************************** (************************************(************************************************************ From northern latitudes, more GPS satellites will generally be found in the southern sky i.e. towards the equator. Taking longer samples increases SNR, revealing weaker signals; but cancellation occurs when the capture spans NAV data transitions. Forward FFT length is an integral number of milliseconds; however, the inverse FFT can be shortened, simply by throwing away data in higher frequency bins. SNR is preserved; but code phase is not so sharply resolved. Nevertheless, a good estimate of peak position is obtained by weighted averaging the two strongest adjacent bins; and off-air tests suggest this could work even down to quite short inverse FFT lengths.
TrackingHaving detected a signal, the next step is locking on, tracking it and demodulating the bps NAV data. This requires two inter-dependent phase locked loops (PLLs) to track code and carrier phase. These PLLs must operate in real-time and are implemented as DSP functions in the FPGA. Pi software has a supervisory role: deciding which satellites to track, monitoring the lock status and processing the received NAV data.The tracking loops are good at maintaining lock, because they have very narrow bandwidths; However, this same characteristic makes them poor at acquiring lock without help. They cannot “see” beyond loop bandwidth to capture anything further away. Initial phases and frequencies must be preset to the measured code phase and Doppler shift of the target satellite. This is orchestrated under Pi control. The loops should be in-lock from the outset and remain so. Code phase is measured relative to the FFT sample. The code NCO in the FPGA is reset at the start of sampling and accumulates phase at a fixed 1. MHz. It is later aligned with the received code by briefly pausing the phase accumulator. Doppler shift on the (****************************************************************************************************************************************************************************. ******************************************************************************************************************************************************************************************************************************************************** MHz carrier is ± 5 KHz or ± 3 ppm. It also affects the 1. Mbps code rate by ± 3 chips per second. The length of the pause is adjusted for code creep in the time since the sample was taken. Fortunately, code Doppler is proportional to carrier Doppler for which we have a good estimate. Hardware / software split [31:0] ************************************************ In the diagram below, color-coding shows how the implementation of the tracking DSP is now split between hardware and software. Previously, this was all done in hardware, with identical parallel instances repeated for each channel, making inefficient use of FPGA resources. Now, the slower 1 KHz processing is done by software, and twice as many channels can be accommodated in half the FPGA real-estate. The six integrate-and-dump accumulators (Σ) are latched into a shift register on the code epoch. A service request flag signals the CPU, which reads the data bit-serially. With 8 channels active, 8% of CPU time is spent executing the (op_rdBit) ************************************************** instruction! But there is plenty of time, and serial I / O uses FPGA fabric economically. Luxuries like RSSI and IQ logging (e.g. for scatter plots) can now be afforded. The F (z) loop filter transfer functions swallow 2% of CPU bandwidth per active channel. These are standard proportional-integral (PI) controllers: – bit precision is used and gain coefficients KI and KP, although restricted to powers of 2, are dynamically adjustable. Each channel having to wait its turn, NCO rate-updates can be delayed by tens or hundreds of microseconds after a code epoch; but this introduces negligible phase shift at frequencies where phase margin is determined.********************** [15:0,31:16] Thin traces are 1-bit, notionally representing ± 1. The 2.6 MHz carrier is first de-spread by mixing with early, late and punctual codes. I and Q complex baseband products from the second rank of XOR gate mixers are summed over 011100 samples or 1ms. This low-pass filtering dramatically reduces noise bandwidth and consequently raises SNR. Downsampling to 1 KHz necessitates wider onward data paths in the software domain. Code phase is tracked using a conventional delay-locked loop or “early-late” gate. Power in the early and late channels is calculated using P=I (2) Q [15:0] ************************************************ 2which is insensitive to phase. Early and late codes are one chip apart i.e. ½ chip ahead-of and behind punctual. This diagram helps to get the error sense correct: (******************************************************************* [15:0,31:16] A Costas Loop is used for carrier tracking and NAV data recovery in the punctual channel. NAV data, m, is taken from the I-arm sign bit with ° phase uncertainty. k is received signal amplitude and θ is phase difference between received carrier (sans modulation) and the local NCO. k varies from around 364 for the weakest recoverable signals up to over for the strongest. Notice how the error term fed back to the F (z) plant controller in the Costas Loop is proportional to received signal power k². Tracking slope, and therefore loop gain, also vary with signal power in the code loop. Below is a Bode plot of open-loop gain for the Costas Loop at k=(**************************************************************************************************************************************************************************************************** (*********************************** [15:0] // Scilab script // Bode plot: Costas carrier tracking loop rssi=470; // amplitude f1=e6; // MHz f2=1e3; // 1 KHz kPD=rssi ^ 2; kNCO=2 *% pi * (f1 / f2) / (% z-1); kI=2 ^ ( – 73); kP=2 ^ ( – 73); G=kPD * kNCO * (kP kI / (% z-1)); G.dt=1 / f2; scf (0); clf; bode (-G, 1e-3, 500, 0. 06) ; (**************************************** [15:0] Costas Loop bandwidth is around Hz, which is about optimal for carrier tracking. Code loop bandwidth is 1 Hz. Noise power in such bandwidths is small and the loops can track very weak signals. The above kI and kP work for most signals, but need dropping one notch for the very strongest. Scilab predicts, and scatter plots confirm, the onset of instability at k≥ (**************************************************************************************************************************************************************************. Parity errors do not occur unless samples stray into the opposite half of the IQ plane. The amount of Doppler shift is always changing. Tracking a shifting carrier frequency requires a small, constant phase error at the loop filter input to drive the integrator. Insufficient kI integrator gain makes the phase error visible as a rotation of the scatter plot; and true or inverted NAV data appears in the sign-bit of the Q channel.AcquisitionThe code generator is aligned and both loop NCO frequencies are initially set using FFT search data. The initial carrier NCO can be up to Hz (FFT bin size) off-frequency, placing it beyond loop capture range. Initial code rate error cannot exceed 0. 19 Hz and the code loop is insensitive to carrier phase. If the signal is strong enough, the code loop always locks; but the carrier loop sometimes needs help. Fortunately, the exact carrier offset can be calculated from the locked code NCO, since both both ex hibit the same Doppler shift. The carrier loop always locks once its NCO is so updated.Before arriving at the above procedure, which seems to be (******************************************************************************************************************************************************************************************************************************% reliable, I just had to retry acquistion until the carrier loop locked. Fortunately, Doppler shift is constantly changing, and if one attempt failed, the next would often succeed. In stubborn cases, nudging the carrier NCO up or down by half an FFT bin-width proved effective. Carriers close to the original IF center frequency of 2.5 MHz were difficult to acquire, due to fractional spurs on the NCO. A huge improvement was obtained by shifting the IF frequency up KHz. The first local oscillator was changed to (******************************************************************************************************************************************************************************. MHz, moving the first and second IF frequencies to [1] . 6 MHz and 2.6 MHz respectively. These spectra show the carrier NCO set 50 Hz above IF centers of 2.5 and 2.6 MHz. The original center frequency was one quarter of the sampling rate. The spurs are safely further away when the frequencies are not in a simple ratio. NAV data [1] NAV data is taken from the sign-bit of the Costas Loop I-arm. The Q-arm should look like random noise. Below are 512 raw I (p, Q (p) samples @ 1 KHz sampling rate: (********************************************* [15:0,31:16] The following fragment of NAV data was received at (****************************************************************************************************************************************************************************************************************************************************************************: ******************************************************************************************************************************************************************************************************************************************************: **************************************************************************************************************************************************************************************************************************************************** (GMT on Tuesday 1st February (********************************************************************************************************************************************************************:(************************************************************************************************************************************************ [15:0] **************************** (**************************************************************************************************************************************(************************************01575879 (************************************************************************************************************************************************ (************************************ (************************************ [15:0] *********************** (0) ******************************************************************************************************************************************************************************************************************************************************************************************

(************************************************************************************************************************************************************************************************************************************************************************************110100 Payeer(***********************************(********************************************************************************************************************************************** (************************************ 06 (************************************************************************************************************************************************** (************************************Payeer(******************************************************************************************************************************************************************************************************************************************************************************************** (********************* (0) **************************************************************************************************************************************************************************************************************************************************************************************************** () ************************************ [15:0] ************************** (************************************(**************************************** (************************************00001001010101

(**********************************************************************************************************************************************(************************************* (**********************************************************************************************************************************************(************************************** 10 (0) ************************************************************************************************************************************************************************************************************************************************************************************** (************************************110100 (************************************************************************************************************************************************************************ (************************************01010001110010000

06 (************************************* 01010001110010100 (************************************ (****************************************************************************************************************************************************************************************************************************** [14:0] ********************************** 06 (****************************************************************************************************************************************************** (**********************************
(**************************, ****************************************** (************************************ 00001001010101 (************************************************************************************************************************************************ (************************************ (************************************** [15:0] ****************************

() ************************************ [15:0] **************************(************************************************************************************************************************************************************************************************************************************** (************************************ (****************************************************************************************************************************************************** (**********************************************************************************************************************************[15:0] ************************************************************************************************************************************ (************************************ 011111111010100110011001010110101010011010100110011001010000100110101001100110101001110101010101100110011001100110100110100110011011100110011001001111010101100101011011111111001001111111111111111111111111010110000000000000000000000010001100 (**********************************************************************************************************************************************************************************************************************************************************************************************************111100

**************************************** (************************************[15:0] ************************** (0) (**************************, **************************************(******************************************************************************************************************************************************** [15:0] ************************Payeer(************************************ (**********************************************************************************************************************************

(**************************************************************************************************************************************************(************************************** [15:0] ****************************(************************************(**************************************************(************************************************************************************************************************************ (************************************************************************************************************************************************ (************************************ 01010001110001111[15:0] ******************************************************************************************************************************************************************************************************************************************************************************** 01575879

(**************************************************************************************************************************************

(********************************************************************************************************************************************** [15:0] ************************** 19
****************************************************************************************************************************************************************************************************************************************************************************************** (************************************ (0) ********************************************************************************************************************************************************************************************************************************************************************************** (************************************ 11 (************************************************************************************************************************************************************************************

(************************************


(************************************************************************************************************************************************ (************************************(**********************************************************************************************************************************************************************************************************************************************************************************************

111100[15:0] ************************************************************************************************************************** (************************************** (************************************************************************************************************************************************************************************************************************************

************************************** 11 0000 (**************************************** 100101010101000000000000010111100010110011111111110010110001010111111101010011011010011011110001010110110000110111000001011001001101000100010110111101110010001100001001111001011101111111111111111111101101011111111111011010110101101011100000****************************************** [15:0] ************************************ 011111111010100110011001010110101010011010100110011001010000100110101001100110101001110101010101100110011001100110100110100110011011100110011001001111010101100101011011111111001001111111111111111111111111010110000000000000000000000010001100(************************************ 20 (**************************, ************************************** (************************************(**************************************[15:0] **************************************************************************************************************************************************************************************************************************[15:0] ************************** (************************************************************************************************************************************(**************************************

The above are 2 consecutive frames of 5 subframes each. Subframes are 289 – bits long and take 6 seconds to transmit. Column 1 is the preamble 10001011. This appears at the start of every subframe; but can occur anywhere in the data. The – bit counter in column 5 is time-of-week (TOW) and resets to zero at midnight Sunday. The 3-bit counter in column 7 is the subframe ID 1 through 5. Subframes 4 and 5 are subcommutated into 31 pages each and a complete data message comprising full frames takes (************************************************************************************************************************************************************************************************************************************************************************************. 5 minutes to transmit. I am only using data in subframes 1, 2 and 3 at present. Solving for user positionEvery GPS satellite transmits its position and the time. Subtracting time sent from time received and multiplying by the speed of light is how a receiver measures distance between itself and the satellites. Doing so with three satellites would yield three simultaneous equations in three unknowns (user position: x, y, z) if the precise time was available. In practice, receiver clocks are not accurate enough, the exact time is a fourth unknown, four satellites are therefore required and four simultaneous equations must be solved: [1] ******************** (********************** An iterative method is used because the equations are non-linear. Using earth’s center (0, 0, 0) and the approximate time as a starting point, the algorithm converges in only five or six iterations. The solution is found even if user clock error is large. The satellites carry atomic clocks; but these too have errors and correction coefficients in subframe 1 must be applied to the time of transmission. Typical adjustments can be hundreds of microseconds. The uncorrected time of transmission is formed by scaling and adding several counters. Time-of-week (TOW) in seconds since midnight Sunday is sent every subframe. Data edges mark out (ms intervals within******************************************************************************************************************************************************************************************** – bit subframes. The code repeats times per data bit. Code length is (chips and chip rate is 1.) Mbps. Finally, the 6 most significant bits of the code NCO phase are appended, fixing time of transmission to ± ns. Satellite positions at the corrected transmission time are calculated using ephemeris in subframes 2 and 3. Orbital position at a reference time t_oe (time of ephemeris) is provided along with parameters allowing (x, y, z) position to be calculated up to a few hours before or after. Ephemerides are regularly updated and satellites only transmit their own. Long term orbits of the entire constellation can be predicted less accurate using Almanac data in subframes 4 and 5; However, this is not essential if a fast FFT-based search is used. Solutions are computed in earth-centred, earth-fixed (ECEF) coordinates. User location is converted to latitude, longitude and altitude with a correction for eccentricity of the earth, which bulges at the equator. The scatter diagrams below illustrate repeatability, the benefit of averaging and the effect of poor satellite choices. Grid squares are 0.0 ° on each side. Blue dots mark 1048 fixes. Yellow triangles mark the centers of gravity: The tight cluster (ii) was obtained using satellites in four different quarters of the sky. Only the rooftop antenna had a clear view in all directions. But good fixes were obtained by averaging, even when half the sky was obscured. Rooftop fixes also exhibit spreading like (i) and (iii) if the wrong satellites are chosen. The above solutions were generated without compensating for ionospheric propagation delays using parameters in page of subframe 4 which should be applied because this is a single frequency receiver. Ionospheric refraction increases path lengths between users and satellites. In April 2019, I fixed a bug that caused significant errors in user-position solutions. Originally, by not transforming satellite positions from earth-centred-earth-fixed (ECEF) to earth-centred-inertial (ECI) coordinates, I was effectively ignoring Earth’s rotation during the 63 to ms that signals were in flight. I am now seeing positional solution Accuracies of ± 5 meters after averaging, even with limited satellite visibility. I’ve created an (appendix) showing how the iterative solution is developed, starting from a geometric range equation, which is linearized using a Taylor Series expansion, and solved by matrix methods, for the special case of four satellites or the general case of more, With the option of using weighted least-squares to control the influence of particular satellites. You’ll find this and solution “C” source code in the links at the bottom of the page. I’m grateful to Dan Doberstein for sending me an early draft of his GPS book [2] which helped me understand the solution algorithm. The official US government GPS Interface Specification [3] is an essential reference. (Signal monitor) ****************************

(************************* The above circuit arrangement, mostly implemented in FPGA, de-spreads by taking the product of the 1-bit IF and punctual code, leaving 50 bps data modulation. A small notch due to BPSK carrier suppression can just be seen: These spectra show the same de-spread transmission at different spans and resolution bandwidths (RBW). Doppler shift was -1.2 KHz. The noise floor is antenna thermal noise amplified and filtered by the IF strip. -3dB bandwidth looks around 3 MHz, slightly wider than planned. The de-spread carrier is 5 dB above noise at (KHz RBW and************************************************************************************************************************************************************************************************************************************************ (dB above at) Hz RBW. Received signal strength at the antenna can be estimated as – 182 1 log 011 ( (e3) 5=- dBm. It still amazes me how well frequency domain information is preserved through hard-limiting! The LVDS transmitter has a constant output current of ~ 3mA which is ~ 1mW in ohms . Peak power seen at the SA cannot exceed 0 dBm. Here, we see this available power spread across a range of frequencies. Wideband integrated power spectral density must be ~ 1mW.First local oscillatorI’ve been building experimental fractional-N synthesizers using general-purpose programmable logic for several years: [15:0] ************************************ (Project) Date [14:0] ********************************** (Technology) ************************************Frequency (MHz)

(************************************ (******************************************************** (FracN)
Altera M AX 10000 CPLD

4.3 [31:0] ****************************(Frac2) (**************************, ************************************** 2005 (**************************, ************************************** Altera MAX ****************************************************************************************************************************************************** (CPLD) ************************************** 19 – (**************************************** (************************************(Frac3)**************Xilinx Spartan 3 FPGA

[15:0] **************************************************************************************************************************************************************************************************************************************************** – [15:0] **************************(****************************************************** (Frac4) ***********************

Xilinx Spartan 3 FPGA(************************************************************************************************************************************************************************************************************************************************************ [15:0]

****************************************** [15:0] ************************************ (Frac5)Xilinx Spartan 3 FPGA [15:0] **************************** – (************************************(************************, ************************************ (Frac7) ************************************** (****************************************************************************************************************************************************************** (************************** (Xilinx Spartan 3 FPGA) – 2004 (****************************************** Frac7 was built for this purpose; But I had no idea Frac5 would be used in a GPS receiver when I originally designed it. The photo below shows how the ROS – VCO output on Frac5 was resistively split between the output SMA and a Hittite HMC 470 divide-by-8 prescaler. The MHz divider output is routed (differentially) into the FPGA which phase locks it to a master reference using methods documented in my earlier projects. Microwave circuity on Frac7 is similar; but uses a Mini-Circuits 3dB splitter. High stability and low phase noise are achieved, as can be seen in the VCO output spectra shown below. When Frac5 was originally developed, as a dedicated frequency synthesizer, simultaneous toggling on frequencies not harmonically related was avoided to minimise intermodulation spurs. The FPGA was static when clock pulses that toggled phase detector output crossed the fabric. No such luxury is practical when the FPGA is hosting a GPS receiver; However, fortunately, the local oscillator output is good enough: The Marconi (spectrum analyser’s) *********************************************************************************************************************************************************************************************************************************************************** MHz STD OUTPUT was used as the master reference source for Frac5 and all internal GPS receiver clocks. GPS receivers need Accordacies better than 1 ppm (parts per million) to measure ± 5 KHz Doppler shifts on the 42 MHz L1 carrier. Any frequency uncertainty would necessitate a wider search range.Embedded CPUMy original GPS receiver could only track 4 satellites. The available fabric was not used efficiently and the FPGA was full. Identical logic was replicated for each channel and only clock-enabled at the 1 KHz code epoch. GPS update rates are quite un-demanding and most of the “parallel” processing can easily be done sequentially. Embedding a CPU for this task has both increased the number of channels and freed space in the FPGA.This CPU directly executes FORTH primitives as native instructions. Visitors to my (Mark 1 FORTH Computer) ************************* page will already be aware of my interest in the language. FORTH is not mainstream; and its use here might be an esoteric barrier; However, I could not resist doing another FORTH CPU, this time in FPGA, after seeing the excellentJ1project, which was an inspiration. (FORTH) is a stack-based language, which basically means the CPU has stacks instead of general purpose registers. Wikipedia has a good overview. (Features) ******************************************************** (******************************************************************************** (FPGA resources:) ************************************************************************************************************************************************************************************************************ (slices 2 BRAMs) **********************************************************************************      Single-cycle instruction execution      (FORTH-like, dual-stack architecture (************************************************************************************      (********************************************************************************************************************************************************************************************************************************************************** – bit stack and ALU data paths (**********************************************************************************      (************************************************************************************************************************************************************************************************************************************************** – bit double-precision operations

         (Hardware multiplier)      (2k byte) expandable to 4k byte (code and data RAM)      (Macro assembler code development [15:0] ************************************************************************** [15:0] ******************************** Memory and I / O

    Two BRAMs are used: one for main memory, the other for stacks. Xilinx block RAM is dual ported, allowing one instance to host both data and return stacks. Each stack pointer ranges over half of the array. Dual porting of the main memory permits data access concurrent with instruction fetch. One memory port is addressed by the program counter, the other by T, the top of stack. Writes to the PC-addressed port are also used for code download, the program counter providing incrementing addresses. Code and data share the main memory, which is organized as (expandable to 3000) – bit words. Memory accesses can be 17 -, [15] ************************************************************************************************************************************************************************************************************************************************ – or – bits, word-aligned. All instructions are – bit. Total code plus data size of the GPS application is less than 750 words, despite all loops being unrolled. I / O is not memory-mapped, occupying its own (bit-select space) (in ) ********************************************************************************************************************************************************************************************************************************************************************************** out (events). One-hot encoding is used to simplify select decoding. I / O operations are variously 1-bit serial, – or 36 – bit parallel. Serial data shifts 1 bit per clock cycle. Events are used mainly as hardware strobes and differ from writes by not popping the stack. (Instruction format) ********************************************************* [15:0] ****************************************************************************************************************************************[14:0] ************************************************************************************ (**************************************************************************************(****************************************************************************************

(************************************************************************************** (**************************************************************************************

(****************************************************************************************** (****************************************************************************************

(************************************************************************************** (****************************************************************************************() ****************************************************************************************** (********************************************************************************************************************************************************

**************************************

[15:0] ************************************************************************************************************************************************************************************************************************************************************************ [15:0] ************************************************************************************************************************************************************************************************************************************************************************ [15:0] ************************************************************************************************************************************************************************************************************************************************************************** [15:0] ************************************************************************************************************************************************************************************************************************************************************************** [15:0]

[15:0] **************************************************************************************************************************************************************************************************************************************************************************** 9 [31:0] **************************** 8 [31:0] **************************** 7 [31:0] **************************** 6 [31:0] **************************** 5) ************************************* 4 [15:0] **************************** 3 [15:0] **************************** 2) ************************************** 1) ************************************* 0 [15:0] **************************** (******************************************************************************************** [15:0] ************************** (op_push) 0 [15:0] **************************** (literal) (************************************ (op _ **************************************) 1) ************************************* 0 [15:0] **************************** 0 [15:0] **************************** (opcode)
ret (************************************* operand (s) (************************************ (************************************ (op_call) 1) ************************************* 0 [15:0] **************************** 1) ************************************* 0 [15:0] **************************** destination_address [11:1]

0 [15:0] **************************** (************************************ (op_branch) 1) ************************************* 0 [15:0] **************************** 1) ************************************* 0 [15:0] **************************** destination_address [11:1] 1) ************************************* (************************************ (op_branchZ) 1) ************************************* 0 [15:0] **************************** 1) ************************************* 1) ************************************* destination_address [11:1] 0 [15:0] **************************** (************************************ (op_branchNZ) 1) ************************************* 0 [15:0] **************************** 1) ************************************* 1) ************************************* destination_address [11:1] 1) ************************************* (************************************ (op_rdReg) 1) ************************************* 1) ************************************* 0 [15:0] **************************** 0 [15:0] **************************** (input_select [11:0] (************************************ (op_wrReg) 1) ************************************* 1) ************************************* 0 [15:0] **************************** 1) ************************************* (output_select [11:0] (************************************ (op_wrEvt) 1) ************************************* 1) ************************************* 1) ************************************* 0 [15:0] **************************** (event_select [11:0] (**************************************** [15:0] 28 instructions out of a possible 36 are currently allocated in the opcode space h XX – h9FXX. These are mostly zero-operand stack / ALU operations. The “ret” option, which performs return from subroutine, executes in parallel, in the same cycle. Add-immediate is the only one-operand instruction. A carry-in option extends (stack, implied) addition precision. hF (********************************************************************************************************************************************************************************************************************************************************************************************** – hFFFF is spare. (Precision) ******************************************************** Stack and ALU data paths are 38 – bit; However, 17 -, – and – bit operations are supported. – bit values ​​occupy two places on the stack, with least significant bits on top. Top of stack, T, and next on stack, N, are registered outside the BRAM for efficiency. Apart from the – bit left shift (op_shl which is hard-wired for single-cycle execution, all other double precision functions are software subroutines.

Assembly languageThe GPS embedded binary was created using Microsoft’s Macro Assembler MASM. This only supports x mnemonics; but opcodes are declared using equ and code is assembled using “dw” directives. MASM not only provides label resolution, macro expansion and expression evaluation but even data structures! The MASM dup () operator is used extensively to unroll loops e.g.dw N dup (op_call dest)calls a subroutine N times. This fragment gives some flavor of source style. Stack-effect is commented on every line: (************************************************************** op_store [14:0] ************************************************************************************** (equ) ***************************************************************************************************** (op_call $) ; [63:32] [31:0] a [31:0] a**************************************************************************************************************************************************************************************************************************************************** (cycles) ****************************************************************************************************                  dw op_store (****************************************************************************************; [63:32] a                  dw op_addi 4 ; [63:32] a 4 (****************************************************************************************************                  ; drop through op_store (*************************************************************************************************** (equ) ************************************************************************************************** (op_call $; [31:0] a 8 cycles                 dw op_over ; [31:0] a [31:0] [15:0,31:16] [15] **************************************************************************                  dw op_swap (**************************************************************************************************; [15:0] a [15:0] [1] ******************************************************************************                  dw op_over ; [15:0] a [15:0] a [15:0]                  dw op_addi 2 ; [15:0] a [15:0] a 2

********************************************************************************                 

dw op_store (******************************************************************************************************************************************************************************************************************************************************************************, op_drop (****************************************************************************************************; [15:0] a (******************************************************************************************************                  dw op_store opt_ret (****************************************************************************************************; a

(op_fetch) ******************************************************************************************************************************************************************************************************************************************************************************andop_store (************************************************** are primitives.      (************************************************ (op_store) ******************************************************************************************************************************************************************************************************************************************************************and (op_store)are subroutines or “compound instructions” usable as if they were primitives.

         T is actually [15:0,31:16] (after) ************************************************** (op_swap) ****************************************************************************************************************************************************************************************************************************************************************************** [15:0] ********************************, but we don’t care about the upper – bits here. (**********************************************************************************      (************************************************ (op_store) ********************************************************************************************************************************************************************************************************************************************************************************** leaves the address; stack depth can only change ± 1 per cycle. (**********************************************************************************      (Purists might prefer: dw N addi *************************************************** (********************************************************************************** [15:0] ********************************** Host serial interfaces The FPGA can be controlled via SPI by the Raspberry Pi, or by a Windows PC using a JTAG cable. There are two levels of request priority: [15:0] ********************************** (Priority) SPI select (************************************ (JTAG IR) ************************************ (Function) ************************************ (************************************ (Highest) SPI_CS) *************(USER1) ************************************** Halt embedded CPU and load new code image (************************************** (************************************** (Lowest) SPI_CS

(USER2) *************************************Send new command and poll for response to previous (************************************** New code images are copied to main memory via a third BRAM which bridges the CPU and serial clock domains. Thus downloaded, binary images execute automatically. Host commands are captured in the bridge BRAM and the CPU is signalled to action them. Its responses are collected by the host from the bridge on the next scan. The top-level main loop polls for host service requests. The first word of any host message is a command code. Requests are dispatched through the(Commands) ****************************************************************************************************jump table: (**************************************************************                 

dw op_rdReg JTAG_RX ; cmd                  dw op_shl ; offset offset                  dw Commands ****************************************************************************************************, op_add (****************************************************************************************************; & Commands [15]                  dw op_fetch (**************************************************************************************************; vector                  dw op_to_r, op_ret

(op_to_r) ************************************************** (moves) *************************************************** (vector [1] ************************************************************************************ [15:0] to the return stack. (***********************************************************************************

    Some host requests (e.g. CmdGetSamples) elicit lengthy responses. Data ports on the CPU side of the bridge are - bit. The CPU can read and write these via the data stack; However, more direct paths exist for uploading main memory and GPS IF samples. The instructionop_wrEvt GET_MEMORYTransfer a memory word directly to the bridge, using T as an auto-incrementing pointer. GET_MEMORY is the only event which has stack effect. The instructionop_wrEvt GET_SAMPLES (transfers) ****************************************************************************************************************************************************************************************************************************************************************************** bits from the IF sampler: (**************************************************************** UploadSamples:dw

(************************************************************************************************ (dup) ***************************************************************************************************** (op_wrEvt GET_SAMPLES) (***************************************************************************************************; [1] ******************************************************************************************************************************************************************************************************************************************************************************** (=(samples copied) **************************************************************************************************                  dw op_ret CmdGetSamples: dw op_wrEvt JTAG_RST ; addr=0                  dw (************************************************************************************************** (dup) *************************************************************************************************** (op_call UploadSamples) (***************************************************************************************************; [1]=(samples copied)                  dw op_ret

Unrolling loops at assembly time with (dup () trades code size for performance, avoiding a decrement-test-branch hit; and the entire application binary is still tiny; However, long loops must be nested, as illustrated above.

CHANNEL data structure (****************************************************** An array of structures holds state variables and buffered NAV data for the channels. MASM has excellent support for data structures. Field offsets are automatically defined as constants and the (sizeof) operator is useful. (**************************************************************** MAX_BITS equ73 CHANNEL structch_NAV_MS dw? ; Milliseconds 0 ... (**************************************************************************************************** ch_NAV_BITS dw? ; Bit countch_NAV_PREV dw? ; Last data bit=ip [15] (****************************************************************************************** ch_NAV_BUF dw (MAX_BITS /) ****************************************************************************************************************************************************************************************************************************************************************************** (dup [15:0,31:16] **************************************************************************************** (?) ; NAV data buffer ch_CA_FREQ dq? ; Loop integratorch_LO_FREQ dq? ; Loop integratorch_IQ dw (2) *************************************************************************************************** (dup) **************************************************************************************************** (?) ; Last IP, QPch_CA_GAIN dw (2) *************************************************************************************************** (dup) **************************************************************************************************** (?) ; KI, KP ch_LO_GAIN dw (2) *************************************************************************************************** (dup) **************************************************************************************************** (?) ; KI, KP CHANNEL ends Chans: CHANNEL NUM_CHANS dup ()

The epoch service routine (labeled (Method:) is called with a pointer to a CHANNEL structure on the stack. Affecting OO-airs, stack-effect comments refer to it as "this" throughout the routine. A copy is conveniently kept on the return stack for accessing structure members like so: (****************************************************************                 

dw op_r ; ... this                 dw op_addi ch_NAV_MS ; ... & ms                 dw op_fetch (**************************************************************************************************; ... ms

TheChansarray is regularly uploaded to the host. Raspberry Pi application softwareThe Raspberry Pi software is multi-tasked using what are variously known as coroutines, continuations, user-mode or light-weight threads. These co-operatively yield control, in round-robin fashion, using the "C" library (setjmp / longjmp) non-local goto, avoiding the cost of a kernel context-switch: (****************************************************************

void NextTask () {      (static int) id;     if (setjmp (Tasks [cmd]. jb)) (return) **************************************************************************************************;     if ( id==NumTasks) id=0;     longjmp (Tasks [cmd]. jb, 1); }

Up to threads can be active: [15:0] ********************************** (Source) (Instances) ************************************** (Purpose) ************************************

(main.cpp) ************************************* (1) Initialization; polling joystick; exit

(********************************** (user.cpp) 1) ************************************* (User interface) ************************************

(search.cpp [15:0,31:16] ************************** (1) Signal detection ************************************ [15:0] ****************************** (********************************** (channel.cpp) (**************************************************************************************************************************************************************************************************************************************************************************************************Acquisition, tracking and NAV data collectionsolve.cpp 1

User-position solution [15:0,31:16] ************************** (**************************************** [1] Coding as threads, each responsible for one task, produces more readable code. Other source files include: (Source (********************************* (Purpose) ************************************

************************************** (auto.sh [1] ************************ (Auto-start; and shutdown properly on exit (************************************ (cacode.h) (PRBS generator) ************************************ [15:0] ****************************** (********************************** (coroutines.cpp)User-mode threading (****************************************ephemeris. *

(Ephemeris database) **************************************gps .h (*********************************** (Main header file****************(peri.cpp) ************************************* (BCM) ************************************************************************************************************************************************************** (peripherals) ************************************

Print.h (*********************************** (Base class for LCD driver) spi. * [15:0] **************************** SPI interface to FPGA ************************************ There is no Arduino in this project, but its LCD driver files (LiquidCrystal.cpp) ********************** (andLiquidCrystal.hare used. Source code

(Latest, re-released under GNU General Public License)ASM Embedded CPU FORTH (**********************************************************************************      (******************************************************************************************************** (Verilog) *********************** (Spartan 3 FPGA)      (******************************************************************************************** (C ) ********************** (Raspberry Pi) [15:0] **************************************** (Older versions (Win) ******************************************************************************************************************************************************************************************************************************************************************* (C )(******************************************************************************************************************************************************************     (********************************************************************************************************** [15:0,31:16] ************************************************************************************** [15:0] **************** (Schematics) (GPS3) *********************** (front-end) **********************************************************************************      (**************************************************************************************************** (Frac7) ********************** (FPGA) [15:0] **************** (Links and resources) (User position solution [11:0] **************** (derivation)      (************************************************************************************************** N2YOlive tracking of GPS satellites above your horizon (**********************************************************************************      (**************************************************************************************************************** Celestrakdaily GPS ephemeris TLE (two line element) updates