## Running TDA18219HN from external clock

06.03.2014 16:38

I'm finishing up the new design for VESNA's UHF receiver and one feature that sunk the most time was the ability to run two receivers synchronously from the same clock source.

Some of the silicon tuners from NXP, like the TDA18271HD, have a dual-tuner feature. The tuner runs a 16 MHz crystal oscillator that is used in a PLL to generate the local oscillator signal. If the chip is programmed as a master, it outputs a buffered differential sine signal on two XTOUT pins. Another tuner can be programmed as a slave and attached to that clock in place of the crystal resonator:

Image by NXP

Unfortunately the TDA18219HN that I'm using doesn't have that feature. You cannot disable the oscillator and set the pins XTALP and XTALN as passive clock buffer inputs. On the other hand, it still has the clock output, because that is useful to run the demodulator. This made me think it should still be possible to run two tuners synchronously, albeit with some additional circuitry.

Datasheet reveals very little about what is behind the XTAL pins:

Image by NXP

Note that the capacitors are wired in series with the quartz and not to ground. So one thing is immediately obvious: this chip does not use the common Pierce oscillator topology. That makes sense, since the chip mostly uses balanced signals. The single-ended digital clock signal generated by the common oscillator variant would be of little use. It also means that running this chip from an external clock is not a simple matter of finding which crystal pin is the input to the integrated CMOS inverter.

After some browsing of the literature I didn't find any quartz oscillator topologies that would require capacitors wired like that. In a number of experiments with a signal generator, oscilloscope and a pile of test circuits I came up with the following model:

XTAL pins are inputs to a differential buffer B. You can produce the correct differential clock even by driving just one pin, although analog performance is reduced because twice the required input level causes saturation.

Pins are also connected to circuits C and D that provide power to a ringing quartz crystal. Circuits on both pins are independent: driving one pin does not cause any change on the other one. The circuit is very prone to oscillations even without a quartz attached and I wasn't able to measure its input impedance directly. From some indirect measurements and calculations it seems that it must lay on this circular path in the complex plane:

Since the circuit compensates for the losses in the oscillator, the real part of the impedance must be negative. The imaginary part is positive, so it exhibits an inductive reactance (at 16 MHz it's equivalent to around 6.6 μH). This is a bit weird, since quartz resonators typically also behave like inductors in a circuit and the inputs should compensate for that.

The final verdict is that it should be possible to drive XTAL inputs from respective XTOUT outputs, provided there's an AC-coupled voltage follower between them. The follower must be powerful enough to drive the relative low impedance of the XTAL inputs. The power required is non-negligible - my worst case estimate from the impedance plot is 10 mW, which seems a bit high considering this is far above the microwatt levels quartz crystals typically endure.

In the end, I can't really test this until I have a prototype circuit on my desk because any stray capacitance from cables ruins the result. I also don't know how much of a problem phase shift between the receivers will be. If it turns out that it won't work at all, scraping this feature won't be too big a loss anyway.

Posted by | Categories: Analog | Comments »

## Universe in a cup

01.03.2014 16:42

This topic came up in an IRC channel the other day. How does the universe compare to a cup of tea? How long after the big bang did it take the universe to cool through the temperatures, characteristic of the popular hot beverage?

Fortunately both tea and the early universe are fairly well understood these days.

In the case of tea, the cup cools down approximately exponentially. Time constant depends on the thermal resistance between the drink and the ambient, its mass and specific heat. Fortunately, a dedicated research unit provides empirical data on the subject.

As far as the universe is concerned, that part of its cooling is described by the Friedmann equation for the matter-dominated era.

As you can see from the graph above, the universe took slightly longer than your five o'clock tea to cool down.

However, unlike the cup of tea, the universe at that age wasn't terribly interesting. All the fun sub-atomic business had finished long ago and darkness was filled more or less evenly with neutral hydrogen and helium.

It will take more than 100 million years for the first stars to light up and another 10-something billion years before an odd biped gets the idea of throwing a fistful of leaves into boiling water.

Posted by | Categories: Ideas | Comments »

## Elektro Ljubljana power outages

22.02.2014 17:50

Today is Open Data Day. Unfortunately our little local group didn't have an organized event this year, so I thought I would contribute by releasing a little project of my own.

During the glaze ice disaster this month I've been collecting data from Elektro Ljubljana to share with family and friends living on the affected areas and keep them up-to-date with the situation.

Elektro Ljubljana is one of the larger distributors of electrical energy in Slovenia. It maintains the distribution infrastructure in the central and southern regions of the country, including our capital city Ljubljana. They cover 36% of the population according to their website. From the beginning of the crisis they have been publishing reports on the state of their infrastructure several times per day. They continue to do so, since emergency crews still haven't been able to reach some damaged parts of their network.

Image by Elektro Ljubljana d.d.

I've downloaded these hand-written reports and converted them into machine-readable JSON format through a hastily written Python scraper (not proud of parsing HTML with regular expressions, but I've been in a hurry). The data starts at the first report on January 31 and continues to the latest report published today.

You can get the extracted data on GitHub as well as scripts that have been used to extract it:

$git clone https://github.com/avian2/elektro-ljubljana-outages.git  The following graph shows the number of clients without electrical power (red), affected transformer stations in the whole network (green) and affected transformer stations in the Logatec region (where, in addition to my family, also the Log-a-tec network resides): The animation below shows the development of the outages over time. The color of each region shows the number of transformer stations without power. It would be better if the percentage of affected stations would be shown, but unfortunately I do not have data on the total number of stations in each region. Posted by | Categories: Life | Comments » ## Story of ice and more ice 20.02.2014 21:36 As you might have heard, the beginning of February has been kind of crazy regarding weather. I spent the last week of January with my parents in Austrian alps, enjoying a vacation away from the grid. During the days when we were planning to travel back home more than 2 meters of snow fell in the south of the country. This record snow-fall was too much even for the industrious Austrian road services and all connections with Slovenia were closed. We were lucky to be able to wait it out a warm place. When the Austrian roads cleared on Saturday we headed home. Unfortunately, the worst was still waiting for us on the other side of the border. When we arrived at my parents', the country was covered in perhaps half-meter snow and encased in an inch or so of ice. Trees were already falling due to heavy glaze ice and we narrowly escaped a trunk falling on the road. It took picks and dirt shovels and heavy work until nightfall to dig ourselves through the snow and ice on the driveway to the house. That evening first the cable TV went dark and soon after that the power grid. The night was something straight out of a nightmare. It wasn't a storm. Just a persistent slow drizzle freezing on everything it touched. There were constant flashes of incredibly bright blue-green light reflected from the overcast sky. Some close, some far away, from shorted transmission lines. The neighbor's house alarm was triggered by the loss of power and then died down. After that the only thing that could be heard from the dark were loud cracks from trees splintering under the weight of ice. The next morning there was hardly a tree still standing on my parents' yard. The ice was still thickening and wouldn't clear for a week. Most of the country was in state of emergency due to closed roads and destroyed electrical transmission lines. Logatec, city my parents live in, was among the ones that were hit the hardest by ice. It's a scary feeling to be in a situation like that. The local supermarket opened running on an emergency generator. We were let in through the staff entrance in the back. It was dark, with only the cash registers powered up. The refrigerators with frozen goods were locked. A customer was yelling loudly at a lady behind the counter how outraged he was that he couldn't get fresh bread. I kept thinking whether I should buy more food than usual in case this situation will last more than a few days and whether that would look weird. It's amazing to what degree we take electric power for granted today. Water and heat run out surprisingly fast without it. Checking for announcements on local government web site becomes highly nontrivial when the battery in your mobile phone runs down and later when the generator at the GSM base station runs out of fuel. Surprisingly, the only service that was working almost without interruptions, at least at my parents' house, was the telephone land-line. In the age of electric stoves and kilowatt hair dryers mere 2 kW from a generator is preciously little. Even when you think you have everything prepared for an emergency there are still surprises. My father bought a generator exactly for a contingency like this. He serviced it yearly and kept it in good order, but it still took a few overhauls until it was running smoothly under the load of the central heating system. Many people found out that their generators were out of oil or fuel after a few years of gathering dust. The server handling this website, my mail and a few other services was also knocked off-line. I had an automated duplicity backup, which I regularly used to restore an odd file or two. I was confident that I could rely on it. When I tried restoring the full backup however I hit two bugs that made moving my things to other servers far less than trivial. According to reports at the height of the crisis one-fifth of the country was without power and the distribution infrastructure in the Notranjska region was almost completely destroyed. While a temporary line was established to my parents' neighborhood after a week and a half, there are still frequent day-long outages. Even though my place in Ljubljana never lost power, I now keep a few spare batteries and a battery powered FM radio in the top drawer. And I have even more respect for people I know that volunteered in local emergency services and did long shifts to help people in need. Posted by | Categories: Life | Comments » ## CubieTruck Perl performance 23.01.2014 22:57 Two months ago I bought a CubieTruck, one of the many cheap, bare-bone ARM-based computers that keep popping-up everywhere these days. My idea was to replace the aging x86 server that is running this website with something more power-efficient. So I was looking for a reasonably powerful board with a proper SATA interface and a decent amount of RAM. Raspberry Pi was out of the question, but the latest incarnation of CubieBoard with a dual-core 1 GHz ARM Cortex-A7, 2 GB of RAM, SATA 2.0 and Gigabit Ethernet seemed to fit the bill. Unfortunately I could not find any reliable benchmarks I could use to estimate how ARM SoCs perform in comparison with my existing setup. So before I decided to migrate I took a while to do some performance tests and get to know this hardware. The software setup I'm interested in benchmarking is somewhat archaic in these days of Node.js and NoSQL. I'm using Perl 5 with HTML::Template doing most of the heavy lifting (at least according to Devel::NYTProf profiler). Most parts are statically generated and some are dynamic using a handful of Speedy CGI Perl 5 scripts. These are combined into a consistent website you see here with a somewhat convoluted Apache configuration using the threaded worker. In the following benchmarks I'm comparing: • An AMD Duron at 700 MHz, 1.2 GB RAM running stock x86 Debian Squeeze. Root filesystem is mounted from an IDE hard drive. • A CubieTruck A20 running armhf Debian Wheezy and the kernel supplied for the CubieTruck Ubuntu Server installation. Root filesystem is mounted from an SD card. Both machines were connected through a 100 Mb/s Ethernet switch to a laptop which was running the remote end of the benchmarks. First, to see how fast the static part of the web site is generated, I ran the full (single threaded) HTML rebuild. I measured the required user space CPU time with the time utility. This is the fastest run of three on each machine: AMD DuronCubieTruck CPU time to rebuild static pages45.3 s61.8 s Then, to check if network was operating at the bit rate I thought it was, I ran iperf to measure TCP throughput between the server and the laptop: AMD DuronCubieTruck iperf throughput test94.0 Mb/s94.5 Mb/s Finally, I ran a suite of tests using the Apache benchmarking tool. I measured how many requests per minute a server can handle for different types of content and different number of concurrent requests. Numbers in parentheses show size of HTTP body (without headers). The site rebuild is somewhat disappointingly almost one-third slower than on a 10 year old PC. However the single threaded Apache performance is on par with it. In the case of more concurrent users the CubieTruck of course has an advantage because of an additional CPU core. Actually in both cases with static content CubieTruck managed to saturate the line when there was more than one concurrent request. I tried to make these tests in a way that the slow SD card in the CubieTruck would minimally affect their outcome. All of data should fit into the buffer cache, which is why in the first test I only took into account the fastest run and only user space CPU time. However I now suspect that the SD card still affected the numbers somehow (the rebuild operation is the heaviest of the tests regarding filesystem I/O). I don't know for sure how kernel computes the time returned by the time utility. These results are good enough that I can't dismiss CubieTruck based on performance. If a proper SATA drive wouldn't speed it up, I could probably parallelize the build process with not much work. That should cut down on time if it's really Perl performance on ARM that is slowing it down. On the other hand I'm having some other concerns about using CubieTruck as a personal server so I'm not completely decided yet about putting it on my rack. Posted by | Categories: Digital | Comments » ## Moving a SSL certificate to a hardware token 05.01.2014 21:35 This is how you move a client side SSL certificate from Firefox to a hardware cryptographic token. It's something I do just rarely enough so that I have to look it up every time. And due to the chaotic nature of OpenSC documentation it's not easy to find all the steps. Here is a quick guide for future reference: This assumes that OpenSC is already installed on the system and working correctly. I'm using a Schlumberger Cryptoflex USB token. Cryptoflex works with 2048 bit RSA keys. I haven't tried larger ones. First export the private key and certificate to a PKCS #12 file: Edit → Preferences → Advanced → Certificates → View Certificates → Your Certificates → Backup. You can verify that it worked by: $ openssl pkcs12 -in file.p12


Now insert the USB token or a smart card into the reader. You can inspect existing contents by:

$pkcs15-tool -D  The Cryptoflex 32K doesn't seem to have enough memory for two key pairs, so you have to delete any existing content before uploading a new certificate. It might be possible to just delete individual files from the token, but I couldn't figure it out, so I just erase the whole device and setup everything from scratch. First erase the token and setup the PKCS #15 structure on it. The default transport key offered by OpenSC works. $ pkcs15-init --erase-card
$pkcs15-init --create-pkcs15  Create a PIN and PUK entries on the token: $ pkcs15-init --store-pin --auth-id 1 --label "My PIN"


Now upload the key you exported from Firefox to the token and protect it with the PIN you entered previously:

\$ pkcs15-init -S file.p12 -f PKCS12 --auth-id 1


Verify that it has been written to the token correctly using pkcs15-tool -D. You can now remove the certificate from Firefox' software storage. You can do that from the certificate manager. You have to remove the token from the system first, because the Firefox' UI hides certificates in software storage if a hardware token is present.

Make sure you keep a safe backup of the file.p12 (and remember the passphrase). It should be impossible to retrieve the private key back from the hardware token so this is now your only way to recover it in case you want to move it to a new device in the future.

Some more background info is available on the old OpenSC wiki. It's not linked from anywhere right now because supposedly they have a new wiki, but a lot of documentation didn't make it there yet.

Posted by | Categories: Code | Comments »

## On forgetting passphrases

01.01.2014 19:57

If you're using encryption to protect your mail and personal files you might find this lesson useful. This goes double if you are (like me) trying religiously to avoid any holes or bit rot in your personal project archive. The gist of it is that you will sooner or later forget a password or a passphrase that you are not actively using.

Consider the case of changing your expired GPG key. If you forget the passphrase for the expired GPG key, you will lose access to your old encrypted mail. It seems obvious in hindsight, but I only realized that after finding out that after a few months of disuse I am unable to recall the old passphrase. I had to say goodbye to an (admittedly small) part of my mail archive.

On a similar note, an encrypted home directory on an old computer will soon be a bag of random bits after you switch to a new machine and change your user password. If forgetting old passwords used to be easy to circumvent (with init=/bin/bash and other venerable tricks), it's impossible now unless you can recall the keyboard sequence from muscle memory. I thoroughly clean out old hardware that leaves my hands. However if a laptop just ends up sitting in a drawer somewhere I'm usually sloppy enough that I often need to lift some old project files from a disused disk drive.

It's easy to avoid this problem once you know it exists. You can write the old GPG passphrase down somewhere or even remove it from the old secret key, depending how concerned you are about the content of old mail. Or you can keep the passphrases for old keys in sync with the new key. And move files you want to retain from old hardware. That saves it from stuck disk bearings as well.

Posted by | Categories: Life | Comments »

## Jahresrückblick

21.12.2013 18:31

It is that season again that makes power-hungry notebooks double as lap warmers and is conductive to large hacker Congresses in the north. Before I go catch this year's last few deadlines, attend festivities with my family and then lose myself among the blinkenlights in Hamburg, I thought I might join the custom of writing a personal year review.

Well, it's been an unusual year.

If anything has marked it for me it has been travel around Europe. I am pretty sure that I did more kilometers by plane, car or train than in any other single year in my life. If I count only longer trips, I've been to Athens, Brussels, Cologne, Ghent, Ilmenau, Ludwigsburg, Munich, Paris and more places in northern Great Britain than I can remember. I visited most of these places because of my job at the Institute, others for less formal meetups or simply running away from it all for a while.

The list would even be one city longer if I weren't rushed to surgery at one point which left me grounded and limited to the neighborhood of my doctor's office for a month or so.

Maybe because of travel or other things, I found it hard to concentrate on any really important thing this year. I've noticed that my context switches are getting longer. I can hardly work on two serious projects on two consecutive days. Since this is hardly compatible with looming deadlines and overflowing lists of tasks it has led to a lot of frustration and burn out on my part. If it's an effect of trying to focus on harder problems now, it sure feels often like I'm just wasting time on unimportant details.

The Slovenian Open Data group has been a most welcome source of motivation when all other things seemed to move in a wrong way. It's incredibly inspiring to talk with people honestly doing their best to improve the world.

It's been the year when Kiberpipa was shut down and when I more or less lost contact with the Computer Museum.

A new Debian was released which in one way or another broke many work flows I have been using for years. It left a strong impression that desktop software is slowly going the way of the dodo. Together with the continuing confirmations of surveillance on the Internet it has contributed significantly to the feeling of impending doom and doubts regarding where technology is headed today.

Perhaps because of that I also spent more time than I want to admit on pastel colored cartoon ponies. Even though I occasionally fear that this subculture is all a massive viral marketing campaign it's been at times weirdly fascinating to explore. It was a fun way to forget more serious things for a while. It got me to experiment with drawing and writing fiction which was an interesting new experience, even if most of what I made is laughably unoriginal or has been described as too depressing.

"You're discussing cartoons while your country is falling apart" was a comment I once heard that probably contains more truth than I would wish and maybe sums it all up pretty well. 2013 for me has been mostly about vastly more ideas than time and energy to properly implement them and no good way to select that one idea out of nine that would be worth focusing on.

Posted by | Categories: Life | Comments »

## TDA18219HN signal distortion

10.12.2013 19:34

I've been writing previously about some AGC problems I noticed with the NXP TDA18219HN tuner chip. Here is how they look like in practice.

Below is the TDA18219HN intermediate frequency output signal captured with an oscilloscope. There is a -60 dBm, 783.1 MHz constant wave on the tuner's antenna input. Channel filter is set to 8.0 MHz bandwidth. Tuner has a balanced IF output, so yellow trace shows non-inverted pin IFP, blue trace shows inverted pin IFN and orange trace shows IFP - IFN. The signal is as expected at this point, with no visible non-linear distortions. The integrated automatic gain control keeps the signal peak-to-peak amplitude at around 400 mV regardless of the input level.

The following capture is from the same setup, except channel filter is set to 1.7 MHz. The input frequency was also lowered to 780 MHz to keep the frequency at the IF stage approximately the same. There's a severe signal distortion at this point. Note that the signal level is also higher now (this screenshot was made at 500 mV/div compared to 200 mV/div in the other two pictures). The triangular shapes make me think that the slew rate limit of some amplifier stage has been reached.

When input level is lowered to -75 dBm the distortion dissappears:

The new TV band receiver for VESNA will have an external channel filter anyway, so this isn't such a problem. I'll simply run the tuner using the 8 MHz setting and rely on the external filter to reduce the IF bandwidth further.

If it's really a bug in the hardware and not some artifact of my own circuit, I'm guessing that this setting wasn't well tested in production since it's not commonly used for DVB-T transmissions. A note in the datasheet about it would be nice though.

Posted by | Categories: Analog | Comments »

07.12.2013 18:00

Working on the new UHF receiver, I wanted to quantify the amount of noise that VESNA's A/D converter will contribute to the total noise of the receiver. This is one of two noise sources I cannot influence (the other being the TDA18219 RF front-end). Knowing the approximate performance of the ADC helped me when choosing other components in the signal chain, since I wanted them not to significantly affect the total amount of noise in the system.

VESNA's STM32F103 microcontroller has 12-bit A/D converters with a 3.3 V reference voltage. In theory they should be accurate to the least-significant bit. Amplitude of the quantization noise is therefore:

\hat u_Q = \frac{3.3V}{2^{12} - 1} = 0.80 \mathrm{mV}

Here's a practical measurement at 2 Msamples/s. The setup was the same as with my high-frequency test, except that the input was grounded with a 50Ω terminator instead of connected to a signal generator:

The histogram of the samples looks nicely like a Gaussian distribution. Calculating the standard deviation gives directly the RMS value of the noise:

\sigma = 0.74
u_{noise} = \sigma \frac{3.3 V}{2^{12}-1} = 0.60 \mathrm{mV}

Comparing to the largest possible signal RMS value:

u_{signal} = \frac{ 3.3 \mathrm{V} }{2\sqrt{2}} = 1200 \mathrm{mV}

So given these values the best signal to noise ratio achievable is:

SNR = 66 \mathrm{dB}

Resulting in effective resolution of 10.9 bits (SNR for an ideal 12 bit converter is 72 dB). A metric like SINAD would more accurately describe the capability of VESNA's ADC for capturing modulated signals, but I think this estimate was good enough to give me an idea of how much freedom I had in choosing a channel filter implementation.

Having done this measurement, another metric can also be calculated, which might be interesting to know. VESNA'S ADCs are mostly used for reading analog sensors. Those are basically DC signals and there the peak-to-peak resolution is a better indicator of ADC performance (as this application note explains).

N_{pp} = \log_2 \frac{2^{12}-1}{6.6 \sigma} = 9.7 \mathrm{bits}

So out of 12 bits you only get 9 most-significant bits without flicker. However, for reading slow-moving sensors you might probably want to use some slower ADC mode with longer sampling time. That might integrate away some of the noise and provide a better resolution.

Posted by | Categories: Analog | Comments »