Category Archives: Technology

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

Building a Remote Control From Scratch – part 2

In Part 1 I described the design and building of the circuit. Now it’s time to get onto the software.

This is the tricky part. I’ll have to digress into how infra-red controls work.

An infra-red controller pulses it’s LED at 38kHz. This ‘carrier’ is then switched on and off to produce a sequence of carrier bursts. The length of the bursts are usually the same and the data is encoded in the gaps between the bursts. A short gap represents a binary ’0′ and a long gap represents a ’1′. Here’s what a typical signal looks like:

A typical infra-red code has bursts of carrier frequency

A typical infra-red code has bursts of carrier frequency

So the software needs to:

  1. Produce the 38kHz carrier frequency

  2. Output bursts of carrier in the correct sequence

  3. Replay different sequences in response to button presses

  4. Shut down everything when the code is finished so as not to drain the battery

The PIC10F206 has 0.5k of ROM and 24 bytes of RAM which should be more than enough. It has an internal oscillator and runs a fixed instruction-cycle time of 1µs. It has a timer/counter peripheral but I’m not going to use that. 38kHz equates to about 26 clock cycles so if I make a loop which takes exactly 26 cycles to run, that will be simple and deterministic. I won’t have to worry about interrupt latency.

Now I need to know the length of the digital pulses that make up the code. How do I find out that timing, especially since I no longer have the original remote? Well, it so happens that I used to be the lead programmer at a company that does a lot of infra-red control and automation. During my time there, I amassed quite a collection of codes from various equipment.

My amplifier is a 1990s vintage Matsushita SUX911 (what an awful name!). These were sold under the brand name “Technics” in Australia. Most Matsushita gear use the same set of codes. You can take a Technics, or a Panasonic controller and use it on just about any other piece of equipment made by them.

The burst timing for the Matsushita code is:

Start pulse length 4.0ms 154 cycles
Start gap length 3.5ms 135 cycles
Data pulse length 1.2ms 46 cycles
’0′ gap 0.7ms 27 cycles
’1′ gap 2.5ms 96 cycles

Since our carrier frequency loop is 26 CPU cycles, I now need to count the loops to get the pulse length. As you can see in the table above, I have expressed each timing value in the number of carrier cycles.

I wrote a bunch of lookup tables to direct the sequence of pulses and gaps using the pre-calculated cycle counts. After a code is completed, the chip is placed into SLEEP mode which draws only 100nA of current and will wake up from sleep when a button is pressed which is a nice feature of the PIC10.

 Here is a flow chart of the software. As you can see, it is dead simple:

The flowchart for the software is pretty straightforward

The flowchart for the software is pretty straightforward

The software came together without too many problems, it turned out to be about 300 lines of assembler, about 1/3 of which was the code lookup tables. It uses 0.1k of ROM and 3 bytes of RAM fitting easily into the PIC10F.

There are usually a few gotchas with the various PIC chips and the PIC10F was no exception. I wasted a couple of hours trying to get the internal pullups to work only to find that pins GP0 and GP1 would default to being a comparator unless you specifically disable that function.

After whacking a couple of software bugs, I got the signal looking good on the oscilloscope. Now to test on the real equipment.

Final testing was a bit of a disappointment though. It kind of worked but you had to hold it within an inch of the receiver. Seems the output power of the Infra Red LED was nowhere near strong enough.

First I tried changing the resistor value from 39Ω down to 20Ω and then 10Ω but it made no difference. What I eventually discovered was that the maximum output power of the PIC was closer to 10mA than the 25mA advertised.

I had to add a transistor to amplify the signal.

I had to add a transistor to amplify the signal.

No matter. I patched on a quick little transistor amplifier using a PNP surface-mount transistor from my junk box and now it’s blasting at about 100mA which is enough power for it to work from across the room.

Unfortunately I don’t have any key caps for the buttons so it looks a bit raw and ugly in its box but it works. It ended taking a day and a half to design and build this thing. Definitely a complete waste of time. I could have just bought a replacement controller but where’s the fun in that?

Here’s the finished product.

Looks a bit ugly but it works!

Looks ugly but it works!

Building a Remote Control From Scratch – part 1

Tragedy has struck! I lost the remote control for my amplifier. If I want to turn the music up, I have to get out of my chair and walk across the room. This is unacceptable!

So I need a new remote. I could have bought a replacement controller, or one of those universal ones that are pretty cheap these days but being an electronics guy, I decided to build one. From scratch. Using parts from my junk box.

Tiny Computer

The very tiny PIC10F206 computer

So what I found was this:

  • A PIC10F206 low-power micro computer (don’t we all have these lying around?)

  • Some ugly blue fob cases left over from an old project that was never finished

  • Various surface-mount resistors and capacitors

  • Some small surface-mount pushbuttons

  • LEDs of various colours (but not infra-red)

  • CR2032 coin cell batteries and holders

Well the show stopper is the lack of infra-red LEDs so I guess I’m going to have to buy one of those. Still it should only cost a few cents and other than that I’ve got enough parts to do the job.

The PIC micro is seriously small but it can output 25 milliamps from it’s I/O pins so I should be able to drive the IR LED directly from that. Here is the circuit I designed:

Remote Control Circuit Design

Remote Control Circuit Design

It’s a pretty simple design. The PIC has an internal oscillator so there’s no need for a crystal. P1 is the PICKit in-circuit programming connector. The PIC also has built-in pull-ups which means there is no need for pull-up resistors on the pushbuttons.

I calculated the resistor values to achieve the 25mA maximum current through the IR LED and added a plain red LED so you can see it working.

Now I could build this on some prototyping board or just hand-wire it but it so happens that being a freelance electronics designer, I’m always getting printed circuit boards made for various clients. So I slipped a board design in with a batch of 30 other boards that were going to a Chinese board factory – I got my PCB almost for free.

Assembling the PCB was dead easy, it’s got to be the simplest PCB I have ever designed. Only 10 parts on the whole thing and a single layer board. In fact, I got my 11-year old son to do most of the soldering.

Printed Circuit Board

Of course, the PIC is just a computer so it won’t do anything until I program it. In Part 2 I’ll get onto the software…

Fixing corrupted character encoding in TAR format Postgres backup

So I’m restoring a backup of a Postgres database when this old familiar error occurs:

pg_restore: [archiver (db)] COPY failed: ERROR: invalid byte sequence for encoding "UTF8": 0x96

This is a common issue with Postgres which I’ve written about before but this time I can’t edit the data manually because it is in pg_dump -Ft “tar” format.

There are a few guides around the internet offering solutions to the problem but they mostly suggest fixing the encoding in the original database and backing it up again, preferably in SQL format.

However what do you do when the original server is destroyed. I mean that is what backups are for right? I’m kinda panicking at this point because I don’t have access to the original database anymore. But I’ve got backups, I’m good right? – Wrong.

So after some nail-biting, I have found a way to fix this. The procedure is a little complex but not too bad and certainly better than the alternative of losing all your data.

 

Step 1 – Create a working directory

Create a directory inside /tmp. It must be done in /tmp or some other globally-writable directory.

mkdir /tmp/pg
cd /tmp/pg

 

Step 2 – Untar the backup

tar xf ~/mybackup.tar
chmod 644 *

You’ll get a zero-block warning from tar. Don’t worry about it, a bug in pg_dump writes out an incorrect tar format. You also have to set the permissions to make the files globally readable or Postgres won’t see them.

 

Step 3 – Fix up the paths

In the file restore.sql, replace all occurrences of $$PATH$$ with /tmp/pg

sed -i 's/\$\$PATH\$\$/\/tmp\/pg/g' restore.sql

 

Step 4 – Fix all the badly encoded files

Your data is now in plain-text format so you could fix it by hand but here’s a little bash script to do it automatically:

for i in *.dat; do mv $i tmp.dat; iconv -f 8859_1 -t UTF-8 tmp.dat > $i; done

 

Step 5 - Restore the database

The backup is now in a state where it can be restored. I don’t trust pg_restore anymore so I’ll use the client to do it:

psql mydatabase -f restore.sql

 …and there you have it. It worked for me, hopefully it will work for you too!

Crispy fried chips

130801105805870978994I got an RS232 bit rate converter in for repair today. Tests indicated that it boots up fine but converts data in one direction only. Also the indicator lights do not light.
I opened up the case and ho-lee-cow! Looks like some hell of a voltage surge happened here. Maybe it got hit by lightning.

I’ve seen some charred messes before but I cannot believe this board still mostly works. It boots up and can send and receive data even though the CPU and RS232 chip are charred husks. Unbelievable!

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.