Peggy 2 Character display

As mentioned in the Peggy 2 Snake post I wrote a bunch of small utility functions to display a string on the peggy 2.

Each character is stored as a 24-bit number (held in a 32bit uint32) where each 4 bits indicates the on/off status for a row of 4 pixels. This results in allowing for a 4×6 pixel character

For example the character for the number ‘0’ is stored as 0x699996 which when spread out looks like:

0110
1001
1001
1001
1001
0110

By doing this I can store 0-9 and A-Z in only 144bytes.
To save RAM I put this in program memory using: PROGMEM prog_uint32_t chars[37] 

To write a character to the display I use a function “show_char” (note I use a special function ‘setPixel’ to set the individual pixels to a certain brightness level – but if you are not using grayscale then the call can be replaced by standard frame.SetPixel calls)

void show_char(char Character, byte x, byte y)
{
  byte charNum = 36;
  if ((Character >= '0') && (Character <= '9')) {
    charNum=Character-48;
  }
  if ((Character >= 'A') && (Character <= 'Z')) {
    charNum=Character-55;
  }
  unsigned long w;
  w = pgm_read_dword_near(chars + charNum);
  for (byte i=0; i<6; i++) {
    byte offset = 4*(5-i);
    byte b = w >> offset; // get four bits
    b=b & 0xF;
    if (b & B1000) setPixel(x,y+i,7);
    if (b & B0100) setPixel(x+1,y+i,7);
    if (b & B0010) setPixel(x+2,y+i,7);
    if (b & B0001) setPixel(x+3,y+i,7);
  }
}

To make things a bit easier to display a string I also created a quick wrapper function ‘write_string’

void write_string(char string[], byte x, byte y)
{
  byte i=0;
  while (string[i] != '\0') {
    show_char(string[i], x+(5*i), y);
    i++;
  }
}

Full usage/source can be found in the peggy 2 snake code

Peggy 2 Snake

For Christmas my wife gave me a peggy 2 and I finally got around to building it.

Peggy 2 running Snake
Peggy 2 running Snake

It has 24×25 White LEDs with a row of 25 Red LEDs across the bottom.

By having that bottom row a different colour I can use that section for displaying score or other information

The first application I wrote for it the good old game of ‘Snake’.  After writing a quick version of the game I realised it needed a bit more ‘flair’ and so added the ability to display an intro screen and score screen.  To make this easier I wrote a bunch of utility functions to display characters that are stored in an array. I’ll describe how this works in a separate post as Peggy 2 Character display.

The game has multiple levels (where walls are put up in different spots and the speed is increased).  All up the program takes up 5258 bytes so fits on an atmega168 with room to spare.

Source code is available as peggy2_snake.zip

If you don’t have all the leds soldered on you can change gameMinX, gameMaxX, gameMinY, gameMaxY and score* to set the area used to play/display score