NMEA Checksum Calculator

I’ve been doing a lot of GPS work lately. Here’s a little utility I wrote which I’d like to share with you all. It’s an NMEA checksum calculator written in PHP.

Try it out here: http://siliconsparrow.com/demos/nmeachecksum.php

Here’s the source code:


NMEA Checksum Calculator

// Simple NMEA Checksum calculator by Adam Pierce
// Created 12-Jan-2012.
// This code is public domain. Copy & share it all you like for any purpose.

if(array_key_exists('nmea',$_REQUEST))
{
$nmea = $_REQUEST['nmea'];
print "

Calculating checksum for: ".htmlspecialchars($nmea)."

rn";

$checksum = 0;
for($i = 0; $i < strlen($nmea); $i++)
{
$c = substr($nmea,$i,1);
$n = ord($c);
if($c == '$')
$checksum = 0;
else if($c == '*')
break;
else
$checksum ^= $n;
}
print "

Checksum is ".dechex($checksum)."

rn";
}
?>

Enter an NMEA String:


Replicating ASCII Database to UTF-8 in PostgreSQL

Well here’s a curly issue I blundered into today. I was trying to replicate a Postgres database from an old server to a new one using pg_dump/pg_restore and found some errors like this:

invalid byte sequence for encoding "UTF8": 0x92

After some investigation it turns out the older version of Postgres defaults to ASCII encoding of the data wheras the new version of Postgres defaults to UTF-8. Of course I would much prefer to use UTF-8 but shouldn’t those two encodings be compatible anyway? UTF-8 is supposed to be backward-compatible with ASCII.

What happened is a few non-ASCII characters got into the database. 0×92 is not a valid ASCII code. It is a code from Latin-1 encoding. This was in the database thanks to my business partner who was entering some crap into the database using a Macintosh which wasn’t following the ASCII standard so much.

So how to solve it?

First I did a plain-text export of the database on the old server

pg_dump -Fp my_database > mydatabase.sql

Then I converted the encoding to UTF-8

iconv -f 8859_1 -t UTF-8 mydatabase.sql > mydatabase.utf8.sql

Finally I imported the converted data into the database on the new server
createdb my_database
psql my_database -f mydatabase.utf8.sql

And then I wrote a blog post so I’d remember all this next time the issue comes up.

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.

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:
Go to Other Page

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.