NHD-C12832A1Z Breakout

NHD-C12832A1Z breakout NHD-C12832A1Z breakout - back

If you're in need of a small, low cost graphic LCD, Newhaven Display's NHD-C12832A1Z series is a great choice. It has 128 x 32 pixels in a pretty compact 40mm x 25mm package, 1.5mm spaced through-hole pins so it's easily hand solderable, and it's controlled with SPI so it only requires a few digital pins on an MCU to use it. The two big downsides are that, with it's small-pitch pins plus a couple larger through-hole tabs for the backlight LED contacts it's not at all breadboard compatible, and it has a maximum supply and IO voltage of 3.3V (ideally 3V), so level shifting is required for interfacing with 5V microcontrollers. This breakout board aims to take care of those two issues.

Description:

The NHD-C12832A1Z Breakout includes a TPS79530 fixed 3V 500mA low-dropout linear regulator to generate the supply voltage for the LCD. The TPS79530 has a rated maximum dropout voltage of 170mV and a maximum input voltage of 5.5V, so the board can be powered by either a 3.3V or 5V supply (or really anything in the range of 3.17V-5.5V). The supply should be able to source up to at least 450mA, as this is the rated maximum current draw for the LCD.

Also included on the board is a CD4050 buffer, which is used to shift the SPI signals from the input level of 3.3V or 5V to the LCD's 3V level.

The board includes all external components required by the display, including a 10KΩ pull-up resistor on the reset line, and a 330Ω current limiting resistor in series with the backlight LEDs.

Usage:

The NHD-C12832A1Z series displays use the ST7565R controller, and are fully supported by the awesome u8glib graphics library, which can be used with both Arduinos and the Atmel ATmega series using straight AVR C. To get started check out Oliver's tutorials on the u8glib wiki page, and use the

U8GLIB_NHD_C12832

constructor.

Purchase the NHD-C12832A1Z breakout:

  • Coming soon...

Downloads:

NHD-C12832A1Z Breakout is licensed under CERN OHL v1.1

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:
  http://www.ladyada.net/learn/lcd/st7565.html
*/


#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:
ST7565 glcd(LCD_SID, LCD_SCLK, LCD_A0, LCD_RST, LCD_CS);

// 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() {
  pinMode(BACKLIGHT_LED, OUTPUT);
  glcd.begin(0x18); // Initialise LCD
  delay(10); // Just to be safe
  toggle_backlight();
  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!
  menu.update();
}

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:
  http://www.ladyada.net/learn/lcd/st7565.html
*/


#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:
ST7565 glcd(LCD_SID, LCD_SCLK, LCD_A0, LCD_RST, LCD_CS);

// 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() {
  pinMode(BACKLIGHT_LED, OUTPUT);
  glcd.begin(0x18); // Initialise LCD
  delay(10); // Just to be safe
  brightness_index = 1; // Initial brightness
  set_brightness(0);
  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() {
  menu.clear();

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

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

// Draw brightness menu:
void show_brightness() {
  menu.clear();

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

menu.add_draw_function(draw_brightness);
  menu.set_title("Brightness:");

// 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.clear();
  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;
  set_brightness(0);
  // Hold until button press then reset brightness:
  while (digitalRead(UP_PIN)&digitalRead(DOWN_PIN)&digitalRead(SELECT_PIN));
  brightness_index = brightness; //
  set_brightness(0);
}

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

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 
  called.

 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.

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

 Menu.update()
  This function should be called each time through the main loop to
  use the menu.  

 Menu.clear()
  Completely resets the menu. This should be called before creating 
  new menus.

TinyGA

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() {
  Serial.begin(9600);
  // Must seed random number generator before initializing TinyGA:
  randomSeed(analogRead(A4));
  start();
}

void start() {
  uint8_t i;
  char buffer[10]; // Buffer for serial receiver
  // Initialize with 10 individuals:
  ga.init(10);
  char_num = 0;
  Serial.println("TinyGA TestnEnter a number between 0-255 and TinyGA will try to guess it");
  Serial.flush();
  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] = '\0'; // 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
    Serial.println();
    char_num = 1;
  }
  Serial.print(".");
  // 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.println();
    Serial.print(result, DEC);
    Serial.println(" - Got it!");
    ga.print(); // Have TinyGA print its current population
    Serial.println();
    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:

  ...
  ga.save();
  ...

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.

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

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

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

 -TinyGA.reset(void)
   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.