Category: Random Projects

Recently the battery in my aging laptop (Sony Vaio VGN-NR498E) took a nose dive.  This is to be expected after 4 years or so, so I was not too upset about it.  What I am upset about, is the fact that Sony doesn’t seem to sell a genuine replacement for the battery.  The original is a VGP-BPS9/B and the only “Sony” batteries I found online were from unreputable sources and cost around $150.  I decided to take the battery apart and see if I could replace the cells directly, but in the process I had to break most of the battery connections and it did not seem trivial to replace them.  After whining about it for a week I opted to buy a third party battery off for $59.

Battery Shipment Contents

I received the shipment within 5 days and inside I found the battery, a couple pages of instructions and a mini CD.  There was also a written warning in poorly translated English stating that I needed to update the BIOS in order to use the battery.  It was so poorly translated that I couldn’t even get a loose interpretation of some of the text.  For example, “You’re system may isn’t suitable for this software or has already not renewed at first the bios file of factory”  (side note: is it really that hard to get a fluent English-speaker to proof read your instructions?).  Anyway, the instructions suggested that I may damage the battery and/or system if I didn’t update my BIOS before plugging in the battery, so I popped in the CD which presumably contained the update.  The CD was blank.  I ended up finding the necessary software on a site mentioned in their instructions, but the software gave me a vague warning that my BIOS was not supported and even after I forced the update the software crashed.  At this point I gave up on bricking my laptop via a failed BIOS update and opted to plug it in and hope for the best.  The battery showed about a 40% charge but the laptop said it was not charging it (I don’t haveSony’s anti third-party battery software installed).  After much frustration and trying different combinations of removing and replacing the battery at different times, I decided to take the Steve approach and hack it :).

Original Sony battery (top) and replacement (bottom)

I had already taken my original battery apart and thrown the dead cells away, so I don’t have any pictures of it, but it looked almost exactly the same as the replacement: 6x 3.6V battery cells and a controller card.  Batteries are nothing but a means of storing power, so the controller must be responsible for communicating things like battery capacity and charging status.  I decided to transplant the new battery cells onto the old Sony controller and give it a shot; in short, it worked!  Here’s the process in pictures.

Step 1: Take batteries apart – remove 4 screws and pry top cover off, then gently pry out the batteries and controller card.

Replacement Battery

Step 2: Remove the controller card from the batteries by desoldering the four metal tabs that connect to the different battery junctions.  I used desoldering wick, flux and a hot soldering iron.

A closeup of the new controller (attached), and the original Sony controller next to it.

Step 3: Solder the battery leads to the new controller.

Solder Sony Controller

Finished Controller

Step 4: Reassemble the battery and secure it with some hot glue.

Glue the Batteries and Controller

Finished Battery

Step 5: Once the top cover is replaced, put the battery back in the computer – you’re done!

For best results you will also need to recalibrate the battery by letting it charge completely, then unplugging the power cable and let the battery discharge until it’s completely dead.  I let my new battery charge overnight, then discharged it in the morning.  Incredibly, the new battery kept the laptop alive for over 3 hours – a significant improvement over the 5-10 minutes I was getting before!

If you are going to attempt this, you should know that there is a very real possibility that things could go horribly wrong if, for example, you wired the battery pack in backwards.  You could destroy the charging circuit in your laptop or even melt it down into a heap of plastic and potentially burn down your house in the process.  That having been said, if you know what you’re doing, this is a great way to recover an investment in a low-grade battery!

Having been rather addicted to understanding electronics lately, I’m always looking for something to play with. Last week I was about to throw out a broken wireless Microsoft mouse, but I caught myself and ended up taking it apart.

Rotary Encoder from a Mouse

I dug down to the scroll wheel and found out it was a nice little rotary encoder – there’s an LED pointed at two phototransistors (light detectors) in it, as well as a circle of tiny black posts that pass between the LED and the detectors, as you can see to the left.  When the posts pass in front of the detectors, the Arduino reads them and is able to determine which direction they are going and increments or decrements a variable that I can access.

It took me about 4 hours to figure out how to hook this thing up, so I figured I would share the info in case someone else wants to use a rotary encoder from a Microsoft mouse in their project.

If you are holding the encoder so that the rotating half is facing you and the wires are facing down, the pinout is as follows:

Pin 1: Photo Sensor 1
Pin 2: Vcc
Pin 3: Photo Sensor 2
Pin 4: IR LED +
Pin 5: IR LED –

Unlike most of the examples I found for using a rotary encoder, this one requires +Vcc on Pin 2 – power will not flow the other way.  The LED power is very picky too;  I am powering it from the 5v regulated supply on my Arduino through a 1k resistor to keep the right amount of light in the encoder.  Too much light and both sensors will be high for too long and too little, neither will go high.  The hardest part to figure out was the voltage divider circuit for the sensors.  I could get them working ok on an analog input – swinging between about 80-600, but it wasn’t clean enough to input as digital until I found the right resistor: 10k.  This nicely divides the input between ground and +5v so the encoder can be read.

Here is the Arduino sketch for the project as shown in the video above:

// Arduino Rotary Encoder from Mouse Scroll Wheel
// and SparkFun 4 Digit Serial 7-Segment Display
// by Steve Kamerman 12/18/2010

// These MUST be on interrupt pins!
#define encoderPinA 2
#define encoderPinB 3

#define displayTXPin 10
#define displayRXPin 11

// used only for sprintf()
#include <stdio.h>

// If you don't have NewSoftSerial, grab it from:
#include <NewSoftSerial.h>
NewSoftSerial displaySerial(displayRXPin, displayTXPin);

// the value - this must be volatile because it is modified
// during an interrupt function and used in a normal function
volatile unsigned int encoderPos = 0;

void setup() {
  // setup the encoder
  pinMode(encoderPinA, INPUT);
  pinMode(encoderPinB, INPUT);
  attachInterrupt(0, readEncoderA, CHANGE);
  attachInterrupt(1, readEncoderB, CHANGE);  
  // setup the display
  pinMode(displayTXPin, OUTPUT);
  // reset display
  // Set display brightness
  displaySerial.print(0x7A, BYTE);
  displaySerial.print(0x05, BYTE);
  // set the display to "   0"
void loop(){

// prints the given number, right justified padded with spaces
// sprtinf() is not a great idea if you want to save space
// but I'm really not too worried about it :)
void displayNumber(int num){
  char buf[4];
  sprintf(buf, "%4d", num);

void readEncoderA(){
  if (digitalRead(encoderPinA) == HIGH){
    encoderPos += (digitalRead(encoderPinB) == LOW)? 1: -1;
    encoderPos += (digitalRead(encoderPinB) == HIGH)? 1: -1;
void readEncoderB(){
  if (digitalRead(encoderPinB) == HIGH){
    encoderPos += (digitalRead(encoderPinA) == HIGH)? 1: -1;
    encoderPos += (digitalRead(encoderPinA) == LOW)? 1: -1;

Yes, I’m still on the electronics kick. This is something I’ve been wanting to do as part of a complete home automation project down the road: monitor the temperature of the different rooms / zones in my house. Now that I’ve got a few Arduinos laying around and some thermal probes (thermistors) from some broken Radio Shack temperature displays, I’ve got the hardware necessary to make it happen! I first installed the thermal probes in the ceilings of the master bedroom, my daughter’s bedroom and our living room in locations that I thought were least affected by vents, fans, lights and other sources of heat. Here’s a picture of the probe in my living room:

Thermal Probe in my Living Room

Next, I connected the three probes to my Arduino’s Analog Inputs using the thermistors as voltage dividers between +5VDC and Ground.  In order to detect the temperatures and make them accessible via the Arduino’s serial interface, I used a few examples on the Arduino site as the basis for this program, which waits for a character to be sent to the serial port, then outputs the temperatures:

#include <math.h>
// [Ground] ---- [10k-Resister] -------|------- [Thermistor] ---- [+5v]
//                                     |
//                                Analog Pin 0

double Thermistor(int RawADC) {
 // Inputs ADC Value from Thermistor and outputs Temperature in Celsius
 //  requires: include <math.h>
 // Utilizes the Steinhart-Hart Thermistor Equation:
 //    Temperature in Kelvin = 1 / {A + B[ln(R)] + C[ln(R)]^3}
 //    where A = 0.001129148, B = 0.000234125 and C = 8.76741E-08
 long Resistance;  double Temp;
 Resistance=((10240000/RawADC) - 10000);
 Temp = log(Resistance);
 Temp = 1 / (0.001129148 + (0.000234125 * Temp) + (0.0000000876741 * Temp * Temp * Temp));
 // Convert Kelvin to Celsius
 Temp = Temp - 273.15;
 // Convert to Fahrenheit
 Temp = (Temp * 9.0)/ 5.0 + 32.0;
 return Temp;

void printDouble(double val, byte precision) {
  Serial.print (int(val));  //prints the int part
  if( precision > 0) {
    Serial.print("."); // print the decimal point
    unsigned long frac, mult = 1;
    byte padding = precision -1;
    while(precision--) mult *=10;
    if(val >= 0) frac = (val - int(val)) * mult; else frac = (int(val) - val) * mult;
    unsigned long frac1 = frac;
    while(frac1 /= 10) padding--;
    while(padding--) Serial.print("0");
    Serial.print(frac,DEC) ;

void setup() {

#define ZoneOne 1   // Analog Pin 0
#define ZoneTwo 2   // Analog Pin 1
#define ZoneThree 3   // Analog Pin 2

double temp;
int inByte = 0;
int sensorDelay = 10;

void loop() {
  if (Serial.available() > 0) {
    inByte =;
    Serial.print(" ");
    Serial.print(" ");
    Serial.print(" ");


I had an old laptop with a dead battery that I wasn’t using, so I loaded it with Ubuntu 10.10 x64, Apache, MySQL, PHP and Cacti and put it up in the attic, connected to the Arduino via USB.  I went through the painfully dry Cacti Documentation and wrote a custom Perl script that Cacti uses to poll the Arduino for temperatures:


use Device::SerialPort;
use Time::HiRes qw( usleep );

# Serial Settings
$PORT = "/dev/ttyUSB0";
$ob = Device::SerialPort->new ($PORT) || die "Can't Open $PORT: $!";
$ob->baudrate(115200)   || die "failed setting baudrate";
$ob->parity("none")    || die "failed setting parity";
$ob->databits(8)       || die "failed setting databits";
$ob->handshake("none") || die "failed setting handshake";
$ob->write_settings    || die "no settings";

        if($_ = $ob->read(255)){
                print "$_\n";
                undef $ob;
        usleep(1000 * 10);

undef $ob;

Cacti Graph of my Home's Temperature

Lastly, I put a nice graph together that shows a comparison of the three temperatures over time, with a composite average of all three.  Now I can see that my daughter’s room spikes to nearly 90 deg when the heat comes on – ouch!  Using this data I am better able to adjust the vents in each room to keep the temperature consistent throughout the house.  Next I want to take one of those cheap LCD picture displays and tie it to the Cacti graph and put it near the thermostat so I can think twice about turning on the heat or AC!

Arduino Duemilanove

Arduino Duemilanove

I recently bought  a 2010 Honda Accord Crosstour and was shocked to see how large it really is in my garage!  When it’s parked correctly, I have about 18 inches behind it and 26 in front of it, when it’s not, I can’t shut the garage door, or I can’t walk in front of it.  As a fun project, I decided to make a device that would let me know when I’m exactly in position!

Enter the Arduino.  The Arduino is an open-source microcontroller board that can programmed with a C-like language called Processing via USB.  It’s a great way to leverage your programming skills to interact with the world around you.  In order to help me park my car, I used an ultrasonic range finder from Radio Shack called the PING))) Parallax.  This device has a transmitter, receiver and a few processing chips on it.  It sends out a signal and listens for the echo, then returns the total time duration in microseconds.  Since sound travels one inch in about 74 microseconds, you can take this time and divide it by 74 to get the total distance that the sound traveled, then divide it by 2 since you only care about the distance too the object, not its return trip.  My plan was to put the range finder in the back of garage and use three LEDs to show me if my car was too far, too close or parked just the right distance away.  I wrote the code below to get a distance reading every 1.5 seconds, and if the distance changed since the last time it was polled, my car (or something in the garage) must have moved.  In this case, the Arduino starts polling for changes every 100ms and lights up an orange LED if it is over 26 inches away, a green LED if it is between 26 and 20 inches and a red LED if it is under 20 inches away.  I mounted the LEDs on a piece of aluminum and attached it to the wall so I could see it from my car while I’m parking.  After I’m finished parking and the Arduino sees that nothing has moved in over 10 seconds, it turns all the LEDs off and starts polling at 1.5 seconds again.  Simple and effective!

// PING))) Sensor
const int pingPin = 7;

// Indicator LEDs
const int tooFarPin = 13;     // Orange LED
const int justRightPin = 12;  // Green LED
const int tooClosePin = 11;   // Red LED

// Distance Thresholds
const int outOfRange = 108;
const int tooFar = 26;
const int tooClose = 20;

// Sensor Polling Delay (ms)
const int idleSenseDelay = 1500;
// High-Speed Polling Timeout
const int idleTimeout = 10000;
int senseDelay = 1500;

/*  States
0 = Out of range (no car present)
1 = Too Far
2 = Just Right
3 = Too Close

int currentState = 0;
int lastState = 0;
unsigned long lastDistanceChange;
long distance;

void setup() {
    lastDistanceChange = millis();
    pinMode(tooFarPin, OUTPUT);
    digitalWrite(tooFarPin, LOW);
    pinMode(justRightPin, OUTPUT);
    digitalWrite(justRightPin, LOW);
    pinMode(tooClosePin, OUTPUT);
    digitalWrite(tooClosePin, LOW);

void loop() {
    long duration, newDistance;

    // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
    // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
    pinMode(pingPin, OUTPUT);
    digitalWrite(pingPin, LOW);
    digitalWrite(pingPin, HIGH);
    digitalWrite(pingPin, LOW);

    // The same pin is used to read the signal from the PING))): a HIGH
    // pulse whose duration is the time (in microseconds) from the sending
    // of the ping to the reception of its echo off of an object.
    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);
    newDistance = duration / 74 / 2;
    if (distance != newDistance) {
        // Something is moving, increase polling rate
        lastDistanceChange = millis();
        senseDelay = 100;
    distance = newDistance;
    currentState = getState(distance);
    if (currentState != lastState) {
        // State changed
    } else {
        if (senseDelay != idleSenseDelay && (millis() - lastDistanceChange > idleTimeout)) {
            // Idle Timeout has Passed, turn off LEDs
            digitalWrite(tooFarPin, LOW);
            digitalWrite(justRightPin, LOW);
            digitalWrite(tooClosePin, LOW);
            senseDelay = idleSenseDelay;
    lastState = currentState;

int getState(long distance) {
    if (distance >= outOfRange) { return 0; }
    if (distance >= tooFar) { return 1; }
    if (distance <= tooClose) { return 3; }
    return 2;

void indicateState() {
    // Turn off the LEDs that are on
    switch (lastState) {
        case 1:
            digitalWrite(tooFarPin, LOW);
        case 2:
            digitalWrite(justRightPin, LOW);
        case 3:
            digitalWrite(tooClosePin, LOW);
        case 0:
        case 1:
            digitalWrite(tooFarPin, HIGH);
        case 2:
            digitalWrite(justRightPin, HIGH);
        case 3:
            digitalWrite(tooClosePin, HIGH);

And here it is, the finished product!

Fritzing Sketch

PING))) Parallax

Arduino ParkAssist

LED Indicator

I happen to have an iPhone and an iPod Touch sync’d to my iTunes back in the US, but now I’m in Iraq and don’t have access to my computer with the iTunes library on it. I do have the music, but I don’t want to sync my iPod to my iTunes because all the play counts and ratings will be gone. I had a little free time last night so I wrote a script to update these attributes for me! It is written in JScript/JavaScript and uses the iTunes COM Interface to communicate with your device and the iTunes Library. It is not optimized very well so it will iterate over the entire iTunes Library for each track it encounters on your device, looking for a matching Artist, Album and Track Name to update. It also maintains a log file that lists every track that was updated including it’s old and new values, as well as any tracks on the iPod/iPhone that it could not find a match for in the iTunes Library. I created this script for my own purposes and decided to share it, so I don’t intend to provide much support for it. The zip file contains two files: UpdatePlayCount.bat and UpdatePlayCount.js. Extract the files somewhere, plug in your iPod/iPhone, then open iTunes and click on your device, then check “Manually manage music and movies” and restart iTunes, then double click on UpdatePlayCount.bat to update your library. You can see that progress is being made in iTunes by clicking on your Library’s Music folder then sorting the music by Play Count or Rating. This list is updated in real time.

Download (2KB)

Source Code (JScript/JavaScript)

 * UpdatePlayCount.js
 * Description
 * ---------------------------------------------------------------------------------------------------------
 * This script will update your iTunes library with the play counts and ratings from any iPod or iPhone.
 * It uses the iTunes COM Interface to communicate with your device.  In order to determine which tracks
 * match, the script will search through the iTunes Library looking for a matching Artist, Album and Title;
 * as a result, this process can take a long time.  Updates all the music and movies in the "Music" and
 * "Movies" playlists on your device.  If you need to update more folders you can modify the code.
 * Usage
 * ---------------------------------------------------------------------------------------------------------
 * Double click on UpdatePlayCount.bat
 * @package UpdatePlayCount
 * @author Steve Kamerman, stevekamerman AT
 * @version Alpha 1.0 $Date: 2009/12/22 13:19
 * @license MPL Vesion 1.1
 * @language Microsoft JScript / JavaScript

var logObject, logFile;
var logfileName = "UpdateItunes.log";
logObject = new ActiveXObject("Scripting.FileSystemObject");
logFile = logObject.CreateTextFile(logfileName, true);

var ITTrackKindFile = 1;
var iTunesApp = WScript.CreateObject("iTunes.Application");
var sources = iTunesApp.Sources;
var i;
var updateTracksCount = 0;
var missingTracksCount = 0;
var ipod;
var itunes;
var playlists;
var itunesPlaylists;
var iTunesXML;
iTunesXML = "";

    if(sources.Item(i).Kind == 2){
        ipod = sources.Item(i);
        playlists = ipod.Playlists;
    if(sources.Item(i).Kind == 1){
        itunes = sources.Item(i);
        itunesPlaylists = itunes.Playlists;

if(ipod == undefined){
    WScript.Echo("Error: No iPod or iPhone found.  Please make sure your device is listed in iTunes, then click on it's name and check "Manually manage music and videos".  Restart iTunes and rerun this script.");
WScript.Echo("iPod found, press OK to update iTunes with the play counts and ratings from your iPod.");
WScript.Echo("This process can take a long time to complete.  To monitor the progress,\nopen iTunes and click on your iTunes Music folder\nthen sort by play count or rating and watch them change.\nPress OK to continue");
var currentPlaylist;
var currentTracks;
var currentTrack;
    currentPlaylist = playlists.Item(i);
    if(currentPlaylist.Name != "Music" && currentPlaylist.Name != "Movies")continue;
    currentTracks = currentPlaylist.Tracks;
        currentTrack = currentTracks.Item(a);
        if(currentTrack.PlayedCount > 0){

WScript.Echo("Finished processing "+(updateTracksCount+missingTracksCount)+" tracks.\nUpdated Tracks: "+updateTracksCount+"\nMissing Tracks: "+missingTracksCount+"\nSee the logfile ("+logfileName+") for more details.");

function updateITunesEntry(playlist, artist, album, song, playCount, rating){
    var itunesPlaylist;
    var itunesTracks;
    var itunesTrack;
    var i;
    var a;
        itunesPlaylist = itunesPlaylists.Item(i);
        if(itunesPlaylist.Name != playlist)continue;
        itunesTracks = itunesPlaylist.Tracks;
            itunesTrack = itunesTracks.Item(a);
            if(itunesTrack.Artist == artist && itunesTrack.Album == album && itunesTrack.Name == song){
                logFile.WriteLine(itunesTrack.Name+": count: "+itunesTrack.PlayedCount+"->"+playCount+", rating: "+itunesTrack.Rating+"->"+rating);
                itunesTrack.PlayedCount = playCount;
                itunesTrack.Rating = rating;
    logFile.WriteLine("WARNING: Track not found in iTunes Library: "+artist+" - "+song);

So the other day my 20.1″ Widescreen Viewsonic monitor started acting funny and turning off on me (this is my 2nd one that has died), so I replaced it with a 22″ Widescreen Xbrite and the new monitor rocks! I figured I would send the Viewsonic back again and have it replaced again, but I thought I would give it another shot as-is first. It seems to run fine unless I leave it on for 12-24 hours at a time so I decided to take it to my office.

Since I already have 2x 17″ Flat Panels at my office, I was going to need another video card to support more than 2. After a little researching on the net, I jumped on and found myself a couple dual-head PCI video cards to throw in with my ATI Radeon X1650 PCIe. I got 2 because the only Radeon series for under $100 were either 1xDVI+1xVGA or 2xDVI Low Profile. I got one of each. The first one I received was a VisionTek Radeon 7000 64MB PCI ($34.99). I installed the card and plugged in my 20.1″ Viewsonic and turned on the computer – no joy. I installed the drivers and prayed it wouldn’t mess up my X1650. Drivers installed no problem, but still no display. Restarted – no display. Now I could see the other card and the monitors in the dislpay properties, but when I “attached” them they didn’t do anything. I restarted it again and went into the BIOS and changed Init Display First from PCIe to PCI Card. I saved the changes and booted into windows – whalah! 3 monitors – all playing nicely :). The computer seems like it’s going to die when it starts up because everything slows down to a crawl for a little while, but then it works as expected. This 3-monitor setup seems very efficient to me. I’ll have to report back after I’ve used it for a while.

My Setup
ATI Radeon X1650 PCIe 512MB Dual Head (2x DVI)
ATI Radeon 7000 PCI 64MB Dual Head (1x DVI, 1x VGA)
2x Dell 17″ Flat Panels
1x Viewsonic 20.1″ Widescreen Flat Panel