Drill Battery Pack Rebuild

Hooray for cheap NiCd batteries from China. I just rebuilt a dead battery pack for my cordless drill an awful lot cheaper than buying a replacement one.

 

 

DrillBatteryRebuild

And to help it last longer, I also bought a smart charger. The original charger was really dumb and would overcharge the battery every time – which is why it blew up in the first place. The cells and the charger together still cost less than a replacement battery!

Charger

 

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!

Back in Stock

I was a little stuck for stock over July but I now have dozens of shiny new Bit Rate Converters. The new revision of the board has reverse-polarity protection so you cannot damage anything if the power is plugged in backwards. They are also robot-assembled in China. I was hand-building units for a while to cover the gap while I was waiting for the chinese boards to arrive but no more.

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!

Drilling

Drill Press

When you have to drill a couple of hundred holes, this cheap, handy drill press adapter from Jaycar turns your regular drill into a drill press.

Create random password in a shell script

Here’s a quick one-liner to make up a random password using only shell commands.
MYPASSWORD=`cat /dev/urandom | tr -dc a-z0-9 | head -c 10`
If you want to customize this a bit, there are two parts you can change, first is the filter which specified what range of characters are allowed in the password. a-z0-9 restricts the password to lower-case letters and digits only. You can add extra ranges and characters here, for example, to add a few punctuation characters, try a-z0-9$^&

The other customization is the length of the password which is the number at the end. In my case, the password will be 10 characters long, you can change it to anything you like.

Quick and dirty fix for corrupted mailbox

I run an old mail server using exim4 which stores its files in mbox format.

My inbox isn’t exactly small these days and I get a large volume of mail, mostly spam unfortunately. Sometimes exim4 has a glitch and corrupts the mailbox. The symptoms are always the same, the start of the mbox file is messed up with some random binary garbage. It always occurs at the very start of the file like this example:

LÍfO@+Yðe
~Ó¹ôêÞ:[çknñPùJ꣺U´-ëüµOi;õ¨ÿ-R$!8öµD¨%wÇßC`
(MʱÔ)wiÎ}1Þméõx¤¾GÊ6DFx£MVLZ¦B{TåQ}­ÃÈÍ ©F!¿ã¶Ùìããé!÷EúýD»Ü>W~sÃ.131.81])
        by adamserver with esmtp (Exim 4.69)
        (envelope-from )
        id 1O7eM3-000229-SH
        for adam@siliconsparrow.com; Fri, 30 Apr 2010 10:45:20 +1000
Received: by p14.nnj.simupt.com (Postfix, from userid 33)
        id 41A4CA7E0; Fri, 30 Apr 2010 00:36:38 +0000 (UTC)
To: adam@siliconsparrow.com
Subject: Hello
...

Now trying to edit a 2GB mbox file using vi or nano is akin to torture so here’s my quick and dirty method which simply deletes the first message in the inbox using the commandline tool awk. I have used this technique 5 or 6 times in the last year with success.

NOTE: Make sure you shut down your SMTP server, POP3 and IMAP servers before you run this.

cd /var/spool/mail
mv adam adam-corrupt
tail -c +500 adam-corrupt | awk '/^From /,0' > adam
chown adam adam

How to cycle through the values of an Enum in Java

Here’s a quick little trick. I needed to advance my variable to the next value in an Enum. I found this can be done using the values and ordinal built-in members. This version wraps around to the beginning when you reach the end.

Here’s the code:

private enum Direction { NORTH, EAST, SOUTH, WEST;
public Direction getNext() {
return values()[(ordinal() + 1) % values().length];
}
};

Here’s an example of how to use it:

private Direction currentDirection = Direction.NORTH;

public void turn() {
currentDirection = currentDirection.getNext();
}