Category Archives: Technology

Posts about technology, interesting things I find out as I develop technical products.

Smallest Computer Ever!

 

OK, so it’s not the smallest computer ever, but at only 3mm long it is the smallest computer I’ve ever programmed. This is the PIC10F206 and yes, that’s the tip of my finger it is sitting on.

This little beastie has less than 1k of memory and only runs about as fast as an Atari ST but hey, it’s a real honest-to-god computer and if you only want something simple done, it can be real useful. Oh, and it only costs 70 cents, way cheaper than the Atari.

So what did I use it for I hear you ask? well, I just needed a 40kHz oscillator with some low frequency modulation to make an ultrasonic insect repeller. You could probably do that with a couple of CMOS chips and a ceramic resonator but this solution is cheaper, smaller, uses no external components and I even have a couple of spare I/Os left over to, I don’t know, flash a light or something.

Class D Amplifier

I have been building audio amplifiers for one of my clients for a while now but we’ve been having some overheating issues so I decided to go high-tech, ditch the old-school linear amp and use a class-D amp.

A class-D amp works a little differently from a traditional analogue amp in that it generates a high-frequency square wave which is pulse-width-modulated. This square wave is then put through a low-pass filter to knock the corners off it and you end up with a wave the same shape as the input wave. This is very clever because a transistor is most efficient when it is either fully off or fully on. By avoiding the linear analogue section of the transistor’s range, the power efficiency is very much improved.

After some research I decided to use the TPA3113 from Texas Instruments. I wired this thing up according to the recommended application circuit and it works pretty well. TI claim this device has a power efficiency of 87% and no heatsink is required. I have yet to properly load-test it but my initial tests are very promising.

The only drawback with this part is it’s sensitivity to power supply noise. A little ripple in the input voltage can make for some very nasty buzzing noises so I’m going to have to add some DC filtering.

This picture is of the whole board. The chip on the right is the class-D amp, the other chips are… well, I haven’t got it all working yet so I’ll leave that for a future blog post.

Count the words in a string using Postgres

I just wanted to post this little bit of code. I needed to produce a list of phrases from a database but only show phrases with more than four words. Here’s the SQL:

select phrasetext from phrases
where array_upper(regexp_split_to_array(phrasetext,E'\s+'),1) > 4;

How this works is a regular expression is used to split the string by spaces. This spits out a text array. The array_upper function retrieves the largest index in the array which, being 1-based is the same as the number of items in the array – which of course is the same as the number of words in the phrase.

UPDATE: I found a simpler way to do this, just use the spaces & wildcards:

select phrasetext from phrases
where phrasetext like '% % % %';

First adventures with iPhone programming

The last month or so I have been learning how to write apps for iPhone because I have a business opportunity for an iPhone app (which I can’t tell you about yet – stay tuned).

But this article is not about the app, it is about my first impressions of programming for iPhone after 20+ years of programming for Windows and UNIX. I have never even written anything for a Mac in all that time.

Coming from the world of C++, Java and C#, I am finding the Objective-C language rather alien. It’s like a bunch of LISP programmers took a look at C and tried to make it more like the One Pure Language. The result is like a bastard offspring of C and Smalltalk.

And it’s so wordy! To show what I mean, here’s an example of some code written in C++. This just manages the storage of a person’s name and can concatenate the first and last names.

using namespace std;
class Person
{
public:
// Storage.
 string _first;
 string _last;

// Constructor
 Person(const char *firstname, const char *lastname)
  : _first(firstname)
  , _last(lastname)
 { }

// Concatenate the first and last names into a full name.
 string toString() const
 { 
   ostringstream oss;
   oss << _first << " " << _last;
   return oss.str();
 }
};

Now I would have thought that C++ code has a lot of lines to do a fairly simple task but look at the Objective-C equivalent:

@interface Person : NSObject
{
// Storage.
  NSString *first;
  NSString *last;
}

@property (retain) NSString *first;
@property (retain) NSString *last;

- (Person *)initWithName:(NSString *)ifirst withLastName:(NSString *)ilast;
- (NSString *)toString;

@end

@implementation Person

@synthesize first;
@synthesize last;

// Constructor.
- (Person *)initWithName:(NSString *)ifirst withLastName:(NSString *)ilast
{
  [super init];
  if(self)
  {
    self.first = ifirst;
    self.last = ilast;
  }
  return self;
}

// Destructor.
- (void) dealloc
{
   [first release];
   [last release];
   [super dealloc];
}

// Concatenate the first and last names into a full name.
- (NSString *)toString
{
  return [NSString stringWithFormat:@"%@ %@",self.first,self.last];
}

@end

The Objective-C requires many more lines of code to do the same job. You may say "so what?" but more lines means more time taken to write it and more places for errors to occur.

Also note that the C++ constructor is much simpler and I did not need to write a destructor at all for such a simple class. C++ is a very old language now, modern languages such as Python and C# do not require you to even think about destructors, they just manage the memory completely automatically. Having to care about allocating and freeing memory is kind of like stepping back into the 1990s.

The only place where the Objective-C was more elegant than C++ was the toString function where it could be implemented in just one line in Objective-C vs. 3 lines in C++.

But all grizzling aside, I would now call myself reasonably proficient at iPhone programming and am finding the API fairly easy to work with. My app is almost finished and I hope to have it in the App Store soon.

Solved – CDHtmlDialog and bitmap resources

Today I am working on some old code and am being frustrated by the CDHtmlDialog class in MFC7. All I want to do is display some hyperlinks and a BMP image embedded in the EXE as a resource – is that so very hard? Well it can be done but it’s not well documented. Here is my solution which I worked out from hours of reading MSDN, forums and some guesswork.

<img src="res://MyApp.exe/#2/#101" />

So now to explain. First use the res:// protocol so that it knows you want to load from a resource. The 2nd item is MyApp.exe and is simply the name of your executable, you don’t have to give a full path.

Now the bit that isn’t obvious. The #2 is the resource type. #2 is for bitmap resources. If you have another type of resource, you’d need a different number. I have no idea how to find out the number for other types, it doesn’t seem to be explained anywhere in MSDN.

Finally the #101 is the resource ID for the bitmap. To find this in MFC you need to look at the file Resources.h, find the bitmap you are looking for and note down it’s resource ID number.

Dead Easy Pure CSS Button Class

Here’s a really simple way to make a styled button using only CSS. I wrote this because a lot of the “Pure CSS Button” scripts I found on the interwebs use a PNG image for the button which is not pure enough for me dammit!

This one does not use any image at all which is good for saving space if you are, say, working on an embedded web server with only a few kB of storage. It is also quick to set up. Simply cut & paste the following lines into your CSS file and add class=”button” to your tag in the HTML.

.button {
	font-size: smaller;
	background: #CCCCCC;
	padding: 3px;
	border-top: 1px solid #EEEEEE;
	border-left: 1px solid #EEEEEE;
	border-right: 1px solid #666666;
	border-bottom: 1px solid #666666;
	text-decoration: none;
}

.button:active {
	border-top: 1px solid #666666;
	border-left: 1px solid #666666;
	border-right: 1px solid #EEEEEE;
	border-bottom: 1px solid #EEEEEE;
}

And here is an example of a link using this style:

<a class="button" href="otherpage.html">Go to Other Page</a>

Here is what it looks like: Test Button – how easy was that!

 

Fastest Board Ever

I’ve just got to have a little boast about my latest PCB. I managed to draw up the schematic and lay out the PCB in just 3 hours start to finish. And anyone who knows me will tell you that I’m quite thorough when designing boards, double-checking measurements and footprints and so on.

Admittedly, I was doing a lot of recycling, about 75% of it was cut & pasted from other boards I have designed in the past but hey, if it gets the board out the door quicker…

In case you’re wondering what it does, it’s a custom RS422 to RS232 Bit Rate Converter I did for a client and of course, the board works perfectly with no design errors.

How to FFT with NXP’s DSP library

What a mouthful of acronyms in that title! This is going to be a very nerdy post.

Today I have been having fun processing audio with the NXP1758 Arm Cortex-M3 microprocessor. It’s really quite easy with the DSP library from NXP. Above is a screen shot of it showing the spectrum of a single note from a synthesizer.

The DSP Library

To get the library, download AN10913 from NXP’s website. There is no source code for the FFT, you need to link the static library NXP_M3_DSPLibFft.a into your project. The documentation doesn’t say much about the FFT function which is why I’m writing this blog post. Here’s some things they don’t mention:

  1. The FFT functions use complex numbers for both the input and output data
  2. It won’t do an in-place FFT – you need two separate data buffers
  3. The number of output data points is always equal to the number of input data points

Processing the data

I’m doing a 1024 point FFT so I’ll need a 4096 byte input buffer and a 4096 byte output buffer for a total RAM usage of 8k. The buffers are twice as large as you’d think because they need to store complex numbers. Each complex number consists of two 16-bit signed values, the first one being the real component and the second one the imaginary component which can be safely set to zero for audio data.

Interpreting the result

The result data contains a bunch of complex numbers which represent the amplitude and phase of each “frequency bin” in the spectrum. A frequency bin is a slice out of the total spectrum; being a digital process, FFT cannot deliver a continuous spectrum.

The bandwidth of each frequency bin is the sampling frequency divided by the number of FFT points. So for example if you are sampling at 22050Hz and using 1024 FFT points, each bin will cover a 21.53Hz slice of the total spectrum. Each bin has a centre frequency of (N*SAMPLERATE)/FFTSIZE where N is the bin number. So in my example above, bin 1 will be centred at 21.53Hz, bin 2 will be centred at 43.06Hz and so on. Bin 0 is centred at 0Hz and represents the DC component of the signal.

The results are complex numbers so you can work out not only the amplitude of each bin but also the phase. I am not interested in the phase so my example code below only computes the amplitude.

The Code

#include "dsp/cr_dsplib.h"
#include <stdint.h>
#include <math.h>

uint16_t fft_in[2048];
uint16_t fft_out[2048];
int16_t spectrum[512];

// Returns an array of 512 values containing the amplitude of each frequency
// bin from DC up to the sampling frequency / 2.
int16_t *processaudio(uint16_t audiobuffer)
{
  int i;

  // First copy the audio data to the real component of the FFT input buffer.
  // Set the imaginary component to zero for all samples.
  memset(fft_in, 0, sizeof(fft_in));
  for(i = 0; i < 1024; i++)
    fft_in[i*2] = audiobuffer[i];

  // Now I can run the FFT.
  vF_dspl_fftR4b16N1024(fft_out, fft_in);

  // Convert the output data back into real numbers because I am not interested
  // in the phase component.
  // Also note that the second half of the FFT output mirrors the first half so it is
  // only necessary to process 512 data points.
  for(i = 0; i < 512; i++)
  {
    a = fft_out[i*2];
    b = fft_out[i*2+1];
    spectrum[i] = sqrt((a*a)+(b*b));
  }

  return spectrum;
}

First Board from OurPCB

A few people in my circle of acquaintances have been recommending OurPCB for prototype printed circuit boards so I thought I’d give them a try with my latest board. This board is a work-for-hire job so I’m sorry I can’t tell you what it’s for but I can tell you it’s a 4-layer board.

With 4 layer boards, you can’t see everything from visual inspection. The proof will be whether the board works after I populate it. But apart from the solder mask registration being slightly out, the board looks pretty nice. They even threw in gold coating for free!

OurPCB are a little slower than other board fabs I have used – it was almost three weeks before I got my boards – but they are cheaper. They seem pretty good.