Power management with LiPoly batteries

I'm a huge fan of single-cell Lithium Polymer batteries; they're small, relatively cheap, and they come in a wide range of different capacities. However, their output range of 3.0-4.2V from discharged (with protection circuitry) to fully charged can be a bit of a hassle, especially if working with 3.3V devices. Of course there are plenty of power management ICs out there, from very bare-bones to extremely complex, but the majority of them are really not that well suited for the average home PCB fabrication set-up, whether it be due to their exceedingly tiny surface mount packages or there large number of required external components.

The majority of devices I make consist of some combination of 3.3V and 5V components. To power these with a LiPoly I need three things: a consistent 3.3V supply, a consistent 5V supply and a charging circuit. Of course there are many great modules and breakout boards that accomplish these tasks and more, for instance from Adafruit and SparkFun, but I'm not generally a fan of the different-breakout-board-for-every-component look, so I've put a fair bit of time into searching for the simplest to use PMICs, and I've discovered a few good options.


By far the easiest LiPoly charging solution I've found is Maxim's MAX1555, which can be purchased at SparkFun. It comes in a friendly SOT-23 package, and the only external components it requires are a few decoupling capacitors. To quote the MAX1555 datasheet:

The MAX1551/MAX1555 charge a single-cell lithium-ion (Li+) battery from both USB* and AC adapter sources. They operate with no external FETs or diodes, and accept operating input voltages up to 7V... With USB connected, but without DC power, the charge current is set to 100mA (max). This allows charging from both powered and unpowered USB hubs with no port communication required. When DC power is connected, charging current is set at 280mA (typ)...

The datasheet shows the typical configuration, which can be modified to use an LED as a charge indicator like this:


The great thing about this IC is that it is an in-system charger, meaning it will happily power your circuit while charging the battery (unless of course the circuit draws more than the charging current, in which case there will be a net drain on the battery!).

5V Supply:

Getting 5V from a LiPoly battery is not all that tricky either, especially using an IC like the MCP1640 adjustable boost regulator. Available in a SOT-23-6 package, the MCP1640 can supply 5V at up to 300mA from a single-cell LiPoly at a little over 90% efficiency, using only a few external components, like so:

(This circuit is straight from the MCP1640 datasheet)

So in the case of a circuit which only needs a 5V supply, the output of the charging circuit can be routed straight to this boost circuit, and all is well.

3.3V Supply:

This is where it starts to get a bit tricky. As the maximum voltage of the LiPoly is greater than 3.3V, and the minimum voltage is less than 3.3V, neither a regulator nor a boost circuit alone will work. One obvious option is to simply stick a 3.3V linear regulator on the output of the above boost circuit, but this is not generally the best idea. For one, if the boost circuit is 90% efficient, followed by a voltage regulator that might be 80% efficient or less, you're looking at an effective efficiency of 72%. That means that if the circuit draws all its current from this 3.3V supply, 28% of the power into the circuit is wasted!

The cleanest and most efficient way to get a 3.3V supply is straight from the battery using a buck–boost converter. The problem is that the majority of buck-boost ICs come in very small packages. Not only does this make them very hard to solder without stenciling and cooking in a reflow oven, but it means it is extremely difficult to etch your own board if it uses one. After hours of catalog searching, however, I have found a few buck-boost ICs that seem suitable for DIY use.

Most recently I stumbled across the MAX710 and MAX711. I don't know much about them yet, but judging by the datasheet they seem a bit outdated. They both have an input range of 1.8-11V, and the MAX710 has a selectable output of 3.3V or 5V, where as the MAX711 has an adjustable output range of 2.7-5.5V. Both can source a maximum of 700mA. Their efficiency is not all that impressive, and they sell for a whopping $8.61 on DigiKey, but they are the only buck-boost I've seen that come in the lovely SOIC package, which makes them super simple to etch for and solder.

I think the best buck-boost option I've seen is the LTC3440. Like many buck-boosts, the LTC3440 was designed for single-cell Lithium batteries, meaning it is optimized for an input voltage of ~3.7V. It has a maximum continuous output current of 600mA, and has an efficiency of ~95% when supplying 3.3V at 100mA with a 3.7V input. What's great about the LTC3440 is that it comes in a 10-MSOP package. Though the 0.5mm lead pitch doesn't leave much room for error, having exposed pads makes soldering pretty easy using a solder wick (great tutorial on skywired.net), and it shouldn't be too hard to etch.

I'm working on developing breakout boards for a few different combinations of these components, which I'll post write-ups for as I get them done.

Simple GA

I've recently been having a lot of fun with different machine learning algorithms, and one of my favorites has been genetic algorithms.

For the sake of completeness, here is a quick overview of the genetic algorithm:

Some definitions:

  • Individual - Each individual is some sort of recipe of how the problem of interest might be solved. Could be a string of bits, a list of integers, etc.
  • Allele - A single piece of information, of which many make up an individual. Could be a single bit, an integer, etc.
  • Population - A collection of individuals.
  • Fitness Function - A function that tests and scores each individual.

The basic idea is that the algorithm starts with a (usually) randomly generated population. Each individual is passed to the fitness function and its score is saved. Once all individuals have been rated they are passed to some form of selection routine, which, depending on their scores, creates a new population with some combination of the best individuals and their offspring, which are creating using some sort of combining routine.

As the vagueness of my description may imply, I see this as an extremely general-purpose algorithm, and I think that the majority of the task-specific details can be handled through clever fitness functions. I created Simple GA with this in mind.

The idea was to have a straight-forward Python API that could be easily used both in programs and at the interactive prompt. It is quite versatile, allowing for any length individuals of bit-string, integer or floating-point types, any number of random crossovers during combination, and offering a couple different selection routines and the option of random mutation during selection. It is also very simple to directly save and load populations (using RawConfigParser).

Using Simple GA:

from simple_ga import *
ga = Simple_GA(fitness_function, 10, 100, selection=BEST_HALF)
# Creates a population of 100 bit-string individuals of 10 alleles each
ga.evolve(2, verbose=True) # See the verbose output
ga.evolve(100) # evolve 100 times or until correct answer reached

This is still a work in progress; I have plans to add more options for selection and combination routines, and it needs some cleaning up and further testing. It's quite usable as is though.

You can find Simple GA here:

(This was my first time using the Epydoc Python documentation generator; worked great! Check it out if you haven't before: http://epydoc.sourceforge.net/)

RGB Convolution

This was an exercise in convolution filtering I wrote in Python for AI class. Here's a very brief summary of convolution filtering:

Convolution filtering is nothing more than a two dimensional mathematical convolution. For every pixel in the image, a matrix, called a kernel, is applied as follows:

 Given a kernel:
      k0  k1  k2
      k3  k4  k5 
      k6  k7  k8

 And a pixel matrix of equal size:
      p0  p1  p2
      p3  p4  p5
      p6  p7  p8

    \forall p4 \in Image: p4 = \sum_{i=0}^{8}k_i*p_i

There are a number of standard image convolution kernels, such as:

  Edge detection:
       1.0  2.0  1.0
       0.0  0.0  0.0
      -1.0 -2.0 -1.0

       2.0  0.0  0.0
       0.0 -1.0  0.0
       0.0  0.0 -1.0

The kernel can be of any size; I use 3x3 kernels in RGB Convolution. As this is generally the first step in a longer process, the images are often converted to greyscale, which means the convolution needs only be calculated on a single channel. As my goal was more or less to write a nifty program, I opted for the more time consuming process of applying a separately customized kernel to each color channel.

The program consists of a file called rgb_convolution.py, with a single function that takes a Python Imaging Library Image object and an array of the RGB kernels, and it returns a new modified Image object after convolution has been performed. There is also file called convolution_gui.py, which is a rough Tkinter GUI for the program.

I've also included two example images.

You can find RGB Convolution here: Download Documentation

ST7565 Menu

I recently completed an independent school project for which I designed and built a prototype of a hand-held sensor platform. It consisted of an ATmega328, a ST7565 LCD and a couple sensors. I ended up using the Arduino environment with Adufruit Industries' ST7565 Arduino library. Being tired of writing new code every time I wanted some sort of LCD user interaface, I set out to create my own API on top of Adafruit's library.

The basic structure I was after was a menu based UI, involving layers of menus and sub-menus, each consisting of different selectable items, whose functions were all user-defined. This ended up being an easier task than it sounds, and I ended up with a rather cool library which I've dubbed the exceedingly creative name of ST7565 Menu.

The library creates, in my opinion at least, a very easy and intuitive API for menu creation. The idea is that you would create a single menu object, then use a collection of methods to add items to it, with the ability to attach functions to each item that will be called when selected. Here's the code for one of the examples included with the library:

 simple_menu.pde - 11/2011
 Basic example of ST7565_Menu Arduino library.

Remember the ST7565 uses 3.3v, so a level shifter
 is needed if using a standard Arduino board.
 See Adafruit tutorial for more details:

#include <ST7565.h> // Adafruit LCD library
#include <ST7565_Menu.h>

// Menu controls:
#define UP_PIN     3
#define DOWN_PIN   4
#define SELECT_PIN 2

// LCD pins:
#define BACKLIGHT_LED 10
#define LCD_SID  9
#define LCD_SCLK 8
#define LCD_A0   7
#define LCD_RST  6
#define LCD_CS   5

// Must create an ST7565 instance before Menu:

// Create Menu with control pins and address of glcd:
Menu menu(UP_PIN, DOWN_PIN, SELECT_PIN, &glcd);

int backlight_state = 0; // 0-Off, 1-On

void setup() {
  glcd.begin(0x18); // Initialise LCD
  delay(10); // Just to be safe
  show_menu();  // Create menu

void show_menu() {
  // Title always shown on first line:
  menu.set_title("==Simple Menu==");

// Create an item which will call toggle_backlight()
  // when selected:
  menu.add_item("Toggle Backlight", toggle_backlight);

// Add a couple items that do nothing when selected:
  menu.add_item("Menu Item 2");
  menu.add_item("Menu Item 3");

void toggle_backlight() {
  backlight_state = backlight_state^1;
  digitalWrite(BACKLIGHT_LED, backlight_state);

void loop() {
  // Now we just need to update the menu each time
  // through the main loop, it takes care of the
  // rest for us!

If you ignore the comments, the function show_menu() that actually creates the menu is only four lines long, and consists of only two functions: set_title() and add_item(). The order of the menu is simply defined by the order in which items are added.

Here's a video of this sketch running:

And a slightly more complicated demo, which is also an included example sketch:

 menu_test.pde - 11/2011
 A more complicated example of ST7565_Menu Arduino library.

Remember the ST7565 uses 3.3v, so a level shifter
 is needed if using a standard Arduino board.
 See Adafruit tutorial for more details:

#include <ST7565.h> // Adafruit LCD library
#include <ST7565_Menu.h>

// Menu controls:
#define UP_PIN     3
#define DOWN_PIN   4
#define SELECT_PIN 2

// LCD pins:
#define BACKLIGHT_LED 10  // Must be a PWM pin
#define LCD_SID  9
#define LCD_SCLK 8
#define LCD_A0   7
#define LCD_RST  6
#define LCD_CS   5

// Must create an ST7565 instance before Menu:

// Create Menu with control pins and address of glcd:
Menu menu(UP_PIN, DOWN_PIN, SELECT_PIN, &glcd);

//Backlight PWM values:
uint8_t brightness_levels[7] = { 0, 20, 50, 90, 130, 190, 250 };
uint8_t brightness_index; // Index of brightness_levels

void setup() {
  glcd.begin(0x18); // Initialise LCD
  delay(10); // Just to be safe
  brightness_index = 1; // Initial brightness
  show_main(); // Draw main menu

// Draw main menu screen:
void show_main() {
  menu.clear(); // Clear menu and display

// If menu.update() called 70 times, light_of() will be called:
  menu.add_timeout_function(70, light_off);

// Title always shown on first line:
  menu.set_title("Example Menu:");

// Add items with function to be called when selected:
  menu.add_item("Read Analog", show_analog);
  menu.add_item("Set Brightness", show_brightness);
  menu.add_item("Scroll Test", scroll_test);

// Draw analog display menu:
void show_analog() {

// draw_analog() will be called after menu items are
  // drawn and before glcd.display() is called:

menu.set_title("Analog Value:");
  menu.add_item("Back", show_main);

// Draw brightness menu:
void show_brightness() {

// Back to main menu after 40 a inactive loops:
  menu.add_timeout_function(40, show_main);


// These items will pass their integer values
  // (1 and -1) to set_brightness:
  menu.add_item("Up", 1, set_brightness);
  menu.add_item("Down", -1, set_brightness);

menu.add_item("Back", show_main);

// Fill a menu to demonstrate scrolling:
void scroll_test() {
  uint8_t i;
  char value[12]; // To hold counter value
  char label[22]; // To hold item label
  menu.add_timeout_function(40, show_main);
  menu.set_title("Scroll Test:");
  menu.add_item("Back", show_main);
  for (i=1; i<=MAX_ITEMS-2; i++) {
    strcpy(label, "Menu Item "); // First part of label
    itoa(i, value, 10);   // Get counter value
    strcat(label, value); // Append counter string
    menu.add_item(label); // Add it
  menu.add_item("Back", show_main);

// Convert and display ADC values from A0 and A1:
void draw_analog() {
  char buffer[12];
  int value;
  value = analogRead(A0);
  itoa(value, buffer, 10);
  glcd.drawstring(20, 3, "A0:");
  glcd.drawstring(44, 3, buffer);

value = analogRead(A1);
  itoa(value, buffer, 10);
  glcd.drawstring(20, 4, "A1:");
  glcd.drawstring(44, 4, buffer);

// Lower brightness if dir<0, raise if dir>0
void set_brightness(int dir) {
  if (dir < 0) {
    if (brightness_index > 0) brightness_index--;
  if (dir > 0) {
    if (brightness_index < 6) brightness_index++;
  analogWrite(BACKLIGHT_LED, brightness_levels[brightness_index]);

// Draw lower section of brightness screen:
void draw_brightness() {
  char buf[12];
  // Just display brightness_index as brightness level:
  itoa(brightness_index, buf, 10);
  glcd.drawstring(LEFT_MARGIN+10, 5, buf);
  // Visual level display:
  glcd.drawrect(LEFT_MARGIN+17, 40, 60, 8, BLACK);
  glcd.fillrect(LEFT_MARGIN+17, 40, 10*brightness_index, 8, BLACK);

void light_off() {
  uint8_t brightness = brightness_index; // Save current level
  brightness_index = 0;
  // Hold until button press then reset brightness:
  while (digitalRead(UP_PIN)&digitalRead(DOWN_PIN)&digitalRead(SELECT_PIN));
  brightness_index = brightness; //

void loop() {
  // Now we just need to update the menu each time
  // through the main loop, it takes care of the
  // rest for us!

And menu_test.pde running: (I forgot to wait long enough here for the timeout function defined on line 51 to be called.)

Notice in both the analog read and brightness adjust windows I've simply created short menus, then used the Adafruit ST7565 library to draw the rest of the LCD using the add_draw_function() method.

Download library here: ST7565 Menu

And here's the complete API (also found in the README file included with the library):

 Menu(uint8_t up_pin, uint8_t down_pin, uint8_t select_pin, ST7565 *lcd)
  Creates and returns an instance of the Menu object. up_, down_ and 
  select_pins are the IO pins where the control buttons are connected.
  The buttons must be configured active-low with external pullups.
  lcd should be the address of an instance of the Adafruit ST7565 object
  (e.g. &ST7565_instance).

 Menu.set_title(char *title)
  Sets the title string that is displayed on the first line of the LCD.
  The title will remain on the first line during scrolling of the menu.
  Will be blank if not set.

 Menu.add_item(char *label)
  Adds a functionless item to the menu.

 Menu.add_item(char *label, void (*function)(void))
  Adds an item to the menu. When selected the given function will be 

 Menu.add_item(char *label, int value, void (*function)(int))
  Adds an item to the menu. When selected the given function will be 
  passed the given integer value.

 Menu.add_draw_function(void (*function)(void))
  Adds a function that will be just before the menu is drawn. This is
  where other graphics should be drawn to the LCD. Menu can only have
   one draw function.

 Menu.add_timeout_function(int timeout, void (*function)(void))
  Adds a function that will be called after Menu.update() has been 
  called the given number of times without any of the menu controls 
  being pressed. In order to have other controls or events restart the
  timeout count, one should set Menu.timeout_counter to 0.

  Redraws the whole menu; does not update read controls or increment 
  timeout counter. Shouldn't normally need to be called.

  This function should be called each time through the main loop to
  use the menu.  

  Completely resets the menu. This should be called before creating 
  new menus.


From time to time I come up with potentially cool ways I could implement different algorithms on robots, especially the fun ones like genetic algorithms, neural networks and particle filters for localization, but I am lacking the tools to do so quickly and efficiently. Somewhere along the way I started toying with the idea of how I could get a fully functional genetic algorithm to fit comfortably on a microcontroller and have it run quickly. In the spirit of wanting to test ideas as quickly and painlessly as possible, the Arduino seemed like the best platform to try this out on. The idea soon turned into the very ambitious plan of creating a collection of Arduino libraries that covers a number of robotics related algorithms implemented as small as possible; for the time being, though, here's TinyGA, my tiny genetic algorithm for the Arduino.

Before I could begin writing TinyGA, I had to decide where I could shrink the algorithm. I chose to favor population size over diversity, so I decided on using unsigned chars for the individuals. While this limits a population to only 256 possible individuals, it allows for the storage of much larger populations than a larger individual would, both in program space as well as in the EEPROM if a population is to be retained when the Arduino shuts off. Once I had that settled, it was mostly just a matter of plugging in the pieces.

The algorithm requires a user-defined fitness function that returns an unsigned char from 1-255 as a fitness rating, or 0 to signal that the correct answer has been reached and the algorithm should stop running. Selection is done using a simple best-half approach, where the individuals with fitness scores above the population's average survive to reproduce. The surviving individuals are then randomly chosen and combined using a single random crossover point. There is also a probability of random mutations of offspring, which is defined in TinyGA.h, along with some other configuration.

The API is quite simple, requiring only the init() and run() functions to run. Here's an example sketch, showing the basic usage of the API, that prompts the user for a number over the serial port then tries to guess it. This sketch compiles to 4208 bytes. (this example is also included in the library)

TinyGA_Test.pde - Alexander Hiam - 1/2012
Uses the TinyGA genetic algorithm library to guess numbers.

#include <TinyGA.h>

// Create TinyGA instance, giving it a fitness function:
TinyGA ga = TinyGA(fitness);

uint8_t number_to_guess, char_num;

void setup() {
  // Must seed random number generator before initializing TinyGA:

void start() {
  uint8_t i;
  char buffer[10]; // Buffer for serial receiver
  // Initialize with 10 individuals:
  char_num = 0;
  Serial.println("TinyGA TestnEnter a number between 0-255 and TinyGA will try to guess it");
  while (!Serial.available()); // Wait for input
  i = 0;
  while(Serial.available()) {
    buffer[i++] = Serial.read();
    delay(10); // Give plenty of time for next character to arrive
  buffer[i] = ''; // End array
  number_to_guess = atoi(buffer); // Convert to int
  Serial.print("Looking for number: ");
  Serial.println(number_to_guess, DEC);

uint8_t fitness(uint8_t individual) {
  /* The fitenss function; takes a guess and returns a score that is larger
     the closer to the correct number it is, and 255 if correct. */

  return 255 - abs(number_to_guess-individual);

void loop() {
  uint8_t result;
  if (char_num++ >= 60) {
    // Just keep track of where the status character is and move to a new line if >=60
    char_num = 1;
  // Run for 100 generations:
  result = ga.run(100);
  if(result) {
    // Run returns 0 unless it got the correct answer, so we know we have it here
    Serial.print(result, DEC);
    Serial.println(" - Got it!");
    ga.print(); // Have TinyGA print its current population
    start(); // Back to the beginning

Here's an example of it running and converging to the correct answer relatively quickly:

TinyGA Test
Enter a number between 0-255 and TinyGA will try to guess it
Looking for number: 54
54 - Got it!
Generation 82:
Population size: 10
51, 51, 51, 51, 51, 54, 51, 51, 51, 51, 

And here's an example of why genetic algorithms make terrible number guessers:

TinyGA Test
Enter a number between 0-255 and TinyGA will try to guess it
Looking for number: 128
128 - Got it!
Generation 4306:
Population size: 10
127, 127, 127, 127, 127, 127, 127, 128, 127, 127, 

4306 evolutions to guess one of 256 possible numbers!

There is also the option of storing a population in the EEPROM, which I have yet to write an example sketch for. The way it works is that the load() function looks for a 4 byte flag that indicates that there is a saved population, loads it and returns 1 if the flag is found, or returns 0 if there is no population. This way initialisation and saving/loading is trivial to include in the sketch by simply writing:

TinyGA ga = TinyGA(test);

void setup() {
  if (!ga.load()) ga.init(10);

Then at some point:


Then the algorithm may be reset either by calling reset() with no arguments to use the same population size, or reset(new_population_size) may be called to change the size. There's a potential bug here if, for example, a sketch using one population size is loaded onto an Arduino where a previous sketch had saved a different size population. This can be resolved by adding one more line:

TinyGA ga = TinyGA(test);

void setup() {
  if (!ga.load()) ga.init(10);
  if (ga.pop_size != 10) ga.reset(10);

This way the old population would be loaded, then its size would be compared to the desired size, and if not equal the population will be reset with the correct size.

- Get TinyGA - click here

And just to be thorough here's the complete API documentation (copied straight from the README file):

 -TinyGA(uint8_t (*fitness_function)(uint8_t))
   Creates and returns an instance of the TinyGA class. Must be passed
   a user-defined function which takes an unsigned char individual and
   returns an unsigned char fitness rating. Fitnesses should range from
   0-255, where 0 is the worst rating and 255 indicates that the correct
   answer has been found and the algorithm should stop evolving.

 -TinyGA.init(uint8_t population_size)
   Initialize a randomly generated population of the given size.

   Attempts to load a population from the EEPROM. Returns 1 if successful,
   0 if there is no population in memory.

   Attempts to save the current population. Returns 1 if successful,
   0 if the population size + EEPROM_OFFSET is greater than EEPROM_SIZE.

   Prints the population size, current generation and the current
   population to Serial. Serial.begin() must be called before hand.

   Resets to random population with current population size.
   The difference between reset() and init() for resetting the algorithm
   is that reset() will write over TINYGA_KEY in the EEPROM and init()
   won't effect the EEPROM.

 -TinyGA.reset(uint8_t new_population_size)
   Resets to random population with new population size.
   Also resets EEPROM.

 -TinyGA.run(uint8_t n_generations)
   Runs the algorithm the given ammount of generations. Returns 0
   unless the fitness function has returned 255 indicating a correct
   answer, in which case the individual that scored 255 is returned.