Category Archives: Arduino

Arduino programming, tips and research.

Arduino-based Adafruit EZ-Key Remapper

Previously, I discussed the Adafruit Bluefruit EZ-Key module. This device comes factory-programmed to send specific key sequences via Bluetooth when one of the 12 inputs is selected. Software is available to change these key sequences, but this software runs on a host computer and requires installing an older version of a development environment called Processing.

Since it appears that the remapping is done simply by sending a text HEX sequence with a checksum to the EZ-Key, I thought it might be easier to just do this on an Arduino with a simple text user interface – no special installs needed.

I did a bit of work on this, and wanted to share my work-in-progress and maybe get some feedback on the interface.

Basically, for each of the 12 inputs you can specify a modifier (SHIFT, CTRL, ALT, etc.) plus up to 6 keycodes which will be sent out (with a Keys-Down) via Bluetooth. When the input is released, a matching Keys-Up message is sent.

To customize, you simply need to specify an input (0-11) and then a modifier (8 available choices) and then up to 6 keycodes (about 112 options available, such as ARROW UP or “k” or numeric keypad minus). I put together a very quick user interface, and here is a sample session, with comments on what is going on:

Adafruit Bluefruit EZ-Key Remapper 0.00 by Allen C. Huffman (alsplace@pobox.com)

Enter input to configure (0-11), [L)ist, [U)pdate or [Q)uit: L

* Here, I select "L" to list the current input config.
Input Key Codes:
----- ----------
 0.   ARROW_UP
 1.   ARROW_DOWN
 2.   ARROW_LEFT
 3.   ARROW_RIGHT
 4.   RETURN
 5.   SPACE
 6.   1
 7.   2
 8.   W
 9.   A
10.   S
11.   D

Enter input to configure (0-11), [L)ist, [U)pdate or [Q)uit: 6

* I select "6" to change input 7 (currently sends "1").
Editing Input 6 Configuration:

Modifier: NONE - Enter new modifier # (0-8), [L)ist, [ENTER)Skip or [Q)uit: L

* To see a list of available modifiers, I select "L".
  0. NONE             3. ALT_LEFT         6. SHIFT_RIGHT  
  1. CTRL_LEFT        4. GUI_LEFT         7. ALT_RIGHT    
  2. SHIFT_LEFT       5. CTRL_RIGHT       8. GUI_RIGHT      
Modifier: NONE - Enter new modifier # (0-8), [L)ist, [ENTER)Skip or [Q)uit: 1
Setting new modifier value to: CTRL_LEFT

* By selecting "1", I am choosing the modifier to be "CTRL_LEFT".
Modifier: CTRL_LEFT - Enter new modifier # (0-8), [L)ist, [ENTER)Skip or [Q)uit: 

* It shows the Modifier line again, and by pressing ENTER, it skips and moves to the next item - Keycodes 0-5:
Keycode0: 1 - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 0

* By entering "0", I am selecting "KEY_NONW" - no key. In this example, I am making this input simply send the left CTRL key.
Setting new keycode value to: NONE

Keycode0: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

* By pressing ENTER five more times, it skips over key codes 1, 2, 3, 4 and 5, leaving them to their current values of "NONE".
Keycode1: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

Keycode2: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

Keycode3: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

Keycode4: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

Keycode5: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

Enter input to configure (0-11), [L)ist, [U)pdate or [Q)uit: L

* Now I use "L" to list the input config again, and can see that input 6 is now set to send the left CTRL key:
Input Key Codes:
----- ----------
 0.   ARROW_UP
 1.   ARROW_DOWN
 2.   ARROW_LEFT
 3.   ARROW_RIGHT
 4.   RETURN
 5.   SPACE
 6.   CTRL_LEFT
 7.   2
 8.   W
 9.   A
10.   S
11.   D

Enter input to configure (0-11), [L)ist, [U)pdate or [Q)uit: 7

* I then change input 7:
Editing Input 7 Configuration:

Modifier: NONE - Enter new modifier # (0-8), [L)ist, [ENTER)Skip or [Q)uit: L

* I want to make this input send ALT-Q, but I forgot what modifiers are available so I "L" to list them again.
  0. NONE             3. ALT_LEFT         6. SHIFT_RIGHT  
  1. CTRL_LEFT        4. GUI_LEFT         7. ALT_RIGHT    
  2. SHIFT_LEFT       5. CTRL_RIGHT       8. GUI_RIGHT      
Modifier: NONE - Enter new modifier # (0-8), [L)ist, [ENTER)Skip or [Q)uit: 3

* "3" is the left ALT key.
Setting new modifier value to: ALT_LEFT

Modifier: ALT_LEFT - Enter new modifier # (0-8), [L)ist, [ENTER)Skip or [Q)uit: 

* Then I press ENTER, and it goes to key code 0, which is currently the "2" key. I want to change that.
Keycode0: 2 - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: L

* But since I don't know what key codes are available, I choose "L" to get a huge list of all of them.
  0. NONE            28. 2               56. F2              84. KEYPAD_PLUS    
  1. A               29. 3               57. F3              85. KEYPAD_ENTER   
  2. B               30. 4               58. F4              86. KEYPAD_1       
  3. C               31. 5               59. F5              87. KEYPAD_2       
  4. D               32. 6               60. F6              88. KEYPAD_3       
  5. E               33. 7               61. F7              89. KEYPAD_4       
  6. F               34. 8               62. F8              90. KEYPAD_5       
  7. G               35. 9               63. F9              91. KEYPAD_6       
  8. H               36. 0               64. F10             92. KEYPAD_7       
  9. I               37. RETURN          65. F11             93. KEYPAD_8       
 10. J               38. ESCAPE          66. F12             94. KEYPAD_9       
 11. K               39. BACKSPACE       67. PRINT_SCREEN    95. KEYPAD_0       
 12. L               40. TAB             68. SCROLL_LOCK     96. KEYPAD_PERIOD  
 13. M               41. SPACE           69. PAUSE           97. EUROPE_2       
 14. N               42. MINUS           70. INSERT          98. APPLICATION    
 15. O               43. EQUAL           71. HOME            99. POWER          
 16. P               44. BRACKET_LEFT    72. PAGE_UP        100. KEYPAD_EQUAL   
 17. Q               45. BRACKET_RIGHT   73. DELETE         101. F13            
 18. R               46. BACKSLASH       74. END            102. F14            
 19. S               47. EUROPE_1        75. PAGE_DOWN      103. F15            
 20. T               48. SEMICOLON       76. ARROW_RIGHT    104. CONTROL_LEFT   
 21. U               49. APOSTROPHE      77. ARROW_LEFT     105. SHIFT_LEFT     
 22. V               50. GRAVE           78. ARROW_DOWN     106. ALT_LEFT       
 23. W               51. COMMA           79. ARROW_UP       107. GUI_LEFT       
 24. X               52. PERIOD          80. NUM_LOCK       108. CONTROL_RIGHT  
 25. Y               53. SLASH           81. KEYPAD_SLASH   109. SHIFT_RIGHT    
 26. Z               54. CAPS_LOCK       82. KEYPAD_*       110. ALT_RIGHT      
 27. 1               55. F1              83. KEYPAD_MINUS   111. GUI_RIGHT      

Keycode0: 2 - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 17

* Since I want to send a "q" key, that is 17.
Setting new keycode value to: Q

Keycode0: Q - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

* Above, it confirms that key code 0 is now "Q". I can then press ENTER to skip the next five optional key codes for this input.
Keycode1: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

Keycode2: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

Keycode3: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

Keycode4: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 

Keycode5: NONE - Enter new key code # (0-111), [L)ist, [ENTER)Skip or [Q)uit: 
Enter input to configure (0-11), [L)ist, [U)pdate or [Q)uit: L

* Back to the main menu, I do an "L" to list the current input config.
Input Key Codes:
----- ----------
 0.   ARROW_UP
 1.   ARROW_DOWN
 2.   ARROW_LEFT
 3.   ARROW_RIGHT
 4.   RETURN
 5.   SPACE
 6.   CTRL_LEFT
 7.   ALT_LEFT + Q
 8.   W
 9.   A
10.   S
11.   D

Enter input to configure (0-11), [L)ist, [U)pdate or [Q)uit: U

* And they look good. Input 6 is now left CTRL, and input 7 is now left ALT + the Q key. Cool. Selecting "U" will update the EZ-Key to use this new config.

...update device here...

…and there you have it. A very simple and easy-to-use “BIOS-like” interface to remap the Adafruit EZ-Key directly from an Arduino, without touching a line of source code or installing anything special.

Does this seem useful? Should I polish it up and post it? I just created it because I was too lazy to download stuff and writing my own seemed more fun.

Let me know what you think in the comments…

Adafruit Bluefruit EZ-Key

Last year, my friend Mike tipped me off to a new Bluetooth product that had been released by Adafruit. The tiny EZ-Key device…

http://www.adafruit.com/products/1535

…was a $19.95 “ready to go” switches-to-Bluetooth board. All you had to do was feed it power (3V-16V) and then hook switches (say, joysticks or arcade buttons) to the 12 input pins and ground and you were set. Power it up, hold down the pair button for a few moments, and let it connect to your computer. After that, any press of those switches would send a preprogrammed character. By default, they were:

  • #0 – Up Arrow
  • #1 – Down Arrow
  • #2 – Left Arrow
  • #3 – Right Arrow
  • #4 – Return
  • #5 – Space
  • #6 – the number ‘1’
  • #7 – the number ‘2’
  • #8 – lowercase ‘w’
  • #9 – lowercase ‘a’
  • #10 – lowercase ‘s’
  • #11 – lowercase ‘d’

You can find a full tutorial here:

http://learn.adafruit.com/introducing-bluefruit-ez-key-diy-bluetooth-hid-keyboard/overview

And the online user manual (with pinouts, wiring examples, etc.) here:

http://learn.adafruit.com/introducing-bluefruit-ez-key-diy-bluetooth-hid-keyboard/user-manual

If the default keys are not good for you, the device can be reprogrammed to send a different single character when a switch is pressed. This seems to involve using an adapter to hook the EZ-Key’s TX/RX pins to the PC, then running a special program that sends sequences to the EZ-Key to remap it.

The device can also be remapped over Bluetooth, which sounds like an easier option since you probably have Bluetooth (if you are using a Bluetooth adapter like this) and probably don’t have a TTL-to-Serial USB adapter. (Okay, some of you reading this probably do, but I don’t…) ((Actually, maybe I do. That may be the thing I use to program BASIC Stamps, though I didn’t know that at the time I bought it.)) (((But I digress…)))

For simple projects, the EZ-Key and a power supply is all you would need, provided whatever you are hooking to (like the MAME emulator) uses simple key presses. One emulator I have on my Mac uses the CTRL key for the FIRE button, so I would at the very least have to remap the EZ-Key to send a CTRL press.

For things like the iCade, which uses dual keypresses (one key for “press button down” and another for “release button”), this will not work. The EZ-Key only does single key presses.

Fortunately, the EZ-Key can also act as a Bluetooth gateway. You can hook it up to a serial port on an Arduino (or Teensy, or anything else with a UART) and write data to it at 9600 baud. This data is either sent out as a simple key down/key up press, or you can do more advanced things like send modifier keys (CTR+ALT+DEL) or even mouse movement and button clicks.

Using four wires, I connected an Arduino up to the EZ-Key:

Arduino hooked to EZ-Key
Arduino hooked to EZ-Key

I was using the Software Serial Arduino library to turn pins 10 and 11 in to TX and RX:

http://arduino.cc/en/Reference/SoftwareSerial

This let me open the EZ-Key just like I would open the console and read/write data to it:


#define RX_PIN         10
#define TX_PIN         11

// Initialize the Software Serial port.
SoftwareSerial EZKey(RX_PIN, TX_PIN); // RX, TX

// We talk to the EZ-Key at 9600 baud.
EZKey.begin(9600);

EZKey.write('x'); // send 'x'

It would be very easy to make a sketch that read data through the Arduino serial console port, and sent that out via Bluetooth:


#include <SoftwareSerial.h>

#define RX_PIN         10
#define TX_PIN         11

// Initialize the Software Serial port.
SoftwareSerial EZKey(RX_PIN, TX_PIN); // RX, TX

void setup()
{
Serial.begin(9600);

// We talk to the EZ-Key at 9600 baud.
EZKey.begin(9600);
}

void loop()
{
char ch;

// If data is available from the USB serial console...
while(Serial.available()>0)
{
// Read a character from the Serial console.
ch = Serial.read();

// If nothing was read, it returns -1...
if (ch>=0)
{
// Write that character out to the EZKey via UART.
EZKey.write(ch);
// Echo back to the serial console.
Serial.write(ch);
}
}
}

I paired the EZ-Key to my iPad, then opened the Serial Monitor on the Arduino IDE and was able to type things there and see them show up on the iPad (inside of Notepad, or anything else that accepted keyboard input).

The next step, for me, will be to integrate EZ-Key support in my iCade interface. Right now, I support reading digital inputs and writing out iCade commands as USB keyboard presses. With just a few lines of code, I should be able to expand this to use the EZ-Key and support Bluetooth as well.

Eventually, I will roll this in to my experimental USB Host Shield version, so it can also read USB joysticks (rather than just digital input switches) and output them as iCade USB keyboard or Bluetooth messages.

My EZ-Key sample program is now on GitHub:

https://github.com/allenhuffman/EZKeyTest

Stay tuned…

Simple scrolling LED Sign for NeoPixel (WS2811) or LPN8806

  • 2014/03/16 Update: The source code to this is now on GitHub. Check the Arduino link at the top of each page of this site.

Yesterday evening, I coded up a simple scrolling message sign that uses addressable LED strips like the Adafruit NeoPixels (WS2811) or LPN8806. The code I created is built for NeoPixels, since those were the ones I had access to, but it would be trivial to make it work with the Adafruit LPN8806 library. Future versions will make this simpler.

First, let’s talk about LED signs.

The BetaBrite is a commercially available scrolling message sign that’s been around for ages. I bought one at SAM’S CLUB back in the late 1990s. The BetaBrite that I have uses an 80×7 array of LEDs. This is what I will be trying to replicate.

If you shop around (ahem, e-Bay), you can find 1 meter long WS2811 LED strips with 60 RGB LEDs for around $8-$9. If you had seven of those, you could make a 60×7 LED sign. It wouldn’t be able to show as many characters at the same time as a BetaBrite does, but it would be good enough to experiment with. (There are strips with 144 pixels per meter, but they are very expensive. And, when you get past 500 or so LEDs, you start running out of memory on the Arduino. I plan to fix this with some updates to the LED library, eventually.)

Consider this wonderful drawing as I discuss a few possible ways to present a sign made out of LED strips:

LED Sign ideas

A. At the top is an example of one of these LED strips with LED number 0 to “n”. One end hooks to the Arduino and power, and the other end can be used to daisy chain multiple strips together. The first LED will be 0, and they count up to the end of the last strip. If you have three 60 LED strips, you have LEDs 0 to 179. The green arrow shows the direction of the data (the LEDs count up in that direction).

B. Next is an example of how you might arrange multiple strips so they could make up an LED sign. Each strip is shown running left-to-right, so at the end of the first strip the cables go all the way back to the left to connect to the start of the next strip. Wiring them like this makes it real easy to do things with. Notice that the green arrow runs left-to-right on each row.

C. However, it would be much much easier to just connect them like this, without all the extra wires running around. But, this causes every other row to run in the opposite direction (again, see the green arrows). This means the software has to be smart enough to know how to reverse drawing the pixels for every other row.

ALSO, based on where you decide to make LED 0, that changes everything. In these drawings, we are hooking the Arduino up at the top left. But, if it was easier to hook up at the bottom right, the entire numbering system would be backwards.

I decided to write a simple LED message program that could handle all of this. It’s not pretty, but it (maybe) works. I configure it with the number of LEDs in use, and how many are in each row, then I set where the start pixel is (TOPLEFT, TOPRIGHT, BOTTOMLEFT or BOTTOMRIGHT). I support running the rows STRAIGHT (A) or ZIGZAG (B). It can even do something fun…

D. This is the only thing I have actually done. I had two 1 meter strips, so I decided to spiral them with 20 LEDs in each spiral before the next row starts. These 120 LEDs can be split up in my program as six rows of 20 LEDs each, and then (with a small enough font), a message can rotate around it.

If you’d like to try out my code, I have posted it to GitHub:

https://github.com/allenhuffman/LEDSign

I have only tested it in the D configuration, but I have done some debug prints that make me think it should be handling all the other variations. Until I have access to more LED strips, I won’t know for sure.

Anyone want to try it out and let me know how it works for you?

Poor documentation, and the code could be cleaned up and optimized quite a bit. Perhaps I will have that done when I reach version 1.0.

Here’s a video of my first working version:

Cheap Arduino Wiznet 5100 ethernet shield

e-Bay seller kbellenterprises has a Wiznet 5100 ethernet shield for the Arduino for just $11.49 with free shipping. And, it ships from Missouri (fast). I have not used this shield, but it’s a great price if it works:

http://www.ebay.com/itm/Wiznet-W5100-Ethernet-Shield-for-Arduino-MicroSD-UNO-MEGA2560-FAST-US-SHIP-/171264625782?pt=LH_DefaultDomain_0&hash=item27e02acc76

This seller also has various Arduino clones (a Leonardo clone for $12.75 and a Leonardo mini for $9.99) with free shipping as well.

Arduino WS2811 scrolling message sign

I have two 1m 60 LED WS2811 strips, and expect to receive several more in coming weeks from Chinese suppliers. Once I have seven of them, I plan to use them as a scrolling message sign.

However, with two 1m strips (120 LEDs total), you can spiral them loosely (not tight enough to break the strip) and end up with six rows… Sorta. And, with a quick Arduino sketch (making use of some TVout fonts)… You can create a mini-circular scrolling message sign.

Here is “HELLO WORLD”:

Just for fun…

2014 Halloween project update

I have been sent a few things I will be using to make a prototype for the Halloween project. The main features will be playing audio on demand, and switching lights (or other 120V items) on and off in time to the audio. Here are the items I will be evaluating:

  • MP3 Shield ($19.99) from CutiDigi.com. This shield has its own flash storage and lets you load MP3 files over from SD memory cards or USB thumb drives. In addition to control buttons on the shield itself (vol+/-, pref, next, play), it also has buttons to start up the copy operation and put the unit to sleep. There is a 1/8″ headphone style jack for getting audio out. It is controlled via serial (tx/rx) and can be made to play a specific track number off the memory.
  • Relay Shield ($7.59) from e-Bay seller happyvalley009. This shield has four relays that can handle 120V up to 3amps, which is a small amount but enough for our needs. It is dangerous to run 120V in to a shield like this, as a short could really cause some problems. A better solution might be to use a separate relay board ($8.49 with Amazon Prime shipping) that is controlled without being attached to the Arduino itself. That would let it be physically separate and still be controlled the same way (and, this one can handle more amperage).

As soon as my funding source returns from vacation, we will order more items and begin working on a prototype.

Pac-Man source code now on GitHub

For those who wish to follow along with my Pac-Man project without having to copy/paste source code from these articles, I have posted my current work-in-progress source (which includes many changes I have not discussed, yet).

https://github.com/allenhuffman/PacMan

I have broken the program up in to multiple files, but since this makes quite a mess in the IDE, I am probably going to combine all the bitmaps in to one file instead of separate ones.

If you want to play with it, you can modify the Joystick code to read whatever you have for input (buttons, analog joystick, whatever) and at least move the Pac-Man around the screen. There is no ghost collision detection, no scoring, and no dot handling yet… But it’s a fun demo.

Arduino ethernet for $10

Here is a heck of a deal. This Arduino Ethernet Shield uses the WizPro 5100 like the official Arduino shield:

http://www.icstation.com/product_info.php?products_id=1494#.UxXX3TK9KSM

If this $10 shield works the same, it is a very cheap way to get internet connectivity out of an Arduino. If you get one, let me know how it works for you.

The shield I used for my Ethernet experiments was made by Sainsmart and it runs about $20:

http://www.sainsmart.com/sainsmart-ethernet-shield-w5100-for-arduino.html

And for those who don’t want to wait for mail order (from China?), you can get a $20 Seeed ethernet shield at your local Radio Shack:

http://www.radioshack.com/product/index.jsp?productId=13356964

Pretty cool.

Arduino Pac-Man part 10 – the story so far

See also: part 1, part 2, part 3, part 4, part 5, part 6, part 7, part 8, part 9 and part 10.

So far, there have been nine installments to this rambling series on creating a Pac-Man style game for an Arduino using the TVout video library. During the course of this discussion, many small things have changed so I thought it might be a good time to reboot the series. Here is a brief updated overview of the process so far.

0. Inspiration and Evolution

One night, two weekends ago, I decided to try the TVout video library for Arduino. I cut up an old A/V RCA cable and used two resistors to connect it to my UNO and soon was running the TVout demo. I next created a small program to draw a line, square, and circle. Then I decided to make the circle bounce around the screen like a ball, followed by bouncing multiple balls. I soon replaced the circle with a bitmap graphic so I could bounce a different shape, and ended up making that shape a Pac-Man which I could steer around the screen, avoiding the balls. Somehow this led me to decide to create a full-on Pac-Man style game.

1. Creating the Maze

Pac-Man arcade screen
Pac-Man

I would be using the default TVout video resolution of 120×96. The original Pac-Man resolution is 224×288 and uses a monitor that is turned sideways (portrait mode) so it is taller than it is wide. If I just scaled that screen size down proportionally, it would become 75×96 and make for a very small maze.

I decided to take the approach used by most home versions that would be played on traditional monitors (landscape) and crop off the top and bottom area (score, lives left, level) so only the maze would be left. The maze alone was 224×248.

I began the process of drawing out the maze, pixel by pixel, on top of this scaled down graphic. As I did this, I had to adjust my maze size a bit so everything would line up. Some later research revealed that the original Pac-Man screen was divided up in to 8×8 tiles of 28 across and 36 down. (Or, when the top and bottom where cropped, 28×31.) In order to get 31 tiles vertically out of the TVout’s 96 pixel tall resolution, I did some simple math and divided the height of the TVout screen (96 pixels) by the number of tiles I wanted to display (31). 96/31=3.096. It seemed I would need to round to 3×3 tiles.

pacman-arduino-270x297
Pac-Man Arduino screen.

Going across the screen (28 tiles) at three pixels each was 84 (3*28=84). Going down the screen (31 tiles) at three pixels each was 93 (3*31=93). My scaled down Arduino maze would be 84×93, and that would allow it to be the same number of tiles as the original, just using smaller tiles.

I used a 3×3 grid to draw out the full maze, and took the liberty of making the side walls a bit wider than they really should be to make them look better. (If you look at the thick walls around the ghost house in the center, that is how the entire outer wall should be for the scaled down lines to be the same dimensions. That is the only thing about this maze recreation that isn’t dimensionally accurate.)

I used a website to convert my graphic file in to C data statements that could be displayed by the TVout bitmap library function.

2. Sprites

Pac-Man sprites
Pac-Man Arduino sprites.

I next created the ghost and Pac-Man character sprites to use in the game. The original arcade sprites were just under two 8×8 tiles wide and tall (less than 16×16 pixels) and would fit in the maze corridors. Since my corridors were now 5 pixels tall or wide (just under two 3×3 tiles) it seemed to work out perfectly to make my game characters 5×5. I designed Pac-Man with three frames (mouth closed, partially open and fully open) just like the arcade, and created versions for all four directions. For the ghosts, they had two frames of animation, and a version for all four directions (with the eyes facing that way). I drew these in a graphics program first, then hand entered them as data in the C source code.

2. Moving – some new stuff here!

Moving through the maze was a challenge. Originally I tried to detect walls by looking for set pixels, but I kept running in to places where the characters would get stuck at the rounded corners. After I learned about how Pac-Man used the tile system, that provided a nice and simple solution: I created a binary map that represented all of the tiles on the screen (28×31) and put a 1 where a wall would be and a 0 where a hall/path would be.

Once I had this, I worked out a system which would track which tile a sprite was in, and check for tiles around it to see if it could go in that direction. This is the part of the project that has evolved the most over the past week as I learned that tiles were also used for how the ghosts knew where to move (they head towards a specific tile), and how collisions between ghosts and Pac-Man were done.

Ghost sprite moving right.
Ghost sprite moving right.

Pac-Man considered a sprite to be in whatever tile the center of the sprite was in. Because of this, I would be tracking the X/Y coordinate of each object based on its center. In a 5×5 sprite, the center would be at (3,3) if we used base-1 and started with the top left pixel at (1,1) and the bottom right pixel at (5,5). In order to allow sprites to move smoothly, I would also track an X/Y offset within  pixel. In the diagram to the right, the top ghost appears at the center of, for example, tile (10,10) with an X offset of 0. As it moves to the right (second ghost), it would still be in tile (10,10) but would have an X offset of 1. As it moves to the right again (third ghost), its center would now have it be in tile (11,10) with an X offset of -1 from that tile. Lastly (four ghost), it would be in tile (11,10) with an offset of 0.

I would need, at the very least, for each sprite to contain something like:

uint8_t x,y;
int8_t  xOffset, yOffset;

To figure out where on the screen to draw the sprite, I would take the tile coordinate, and multiple it by the size (3 pixels tall or wide), and then add the offset. In the above example, tile (10,10) with an X offset of 0 (in the center) would correspond to screen pixel (30,30). As the ghost moved to the right, it would be at (31,30) and (32,30). I also needed to add a few pixels to X and Y to compensate for the maze bitmap being a bit wider than the tiles under it. (NOTE: This is simplified. In the actual code, I also add half the width of the tile to keep the X/Y positions representing the center.)

To keep from having to do this kind of math (MAZEX+x*3+xOffset) every time an object was displayed, I thought I might also track the screen position separately:

uint8_t xScreen, yScreen;

I would need to do some testing and see if the overhead of the formula to calculate screen position every time was better than tracking two separate X/Y coordinates (one for tile, one for screen). Therefore, this approach is still something that could change. It would make the code seem simpler, but perhaps at a cost of extra CPU cycles needed (versus just having a variable around).

Objects also need to know what direction they were headed in. Initially, since I had started with a bouncing ball demo, I gave each object a directional offset variable that could either be +1, -1 or 0 depending on if the object was moving right/up, left/down or stopped. I was calling them “mx” and “my” (movement X, movement Y) and to move, I would just do something like:

x = x + mx;
y = y + my;

As I got further in to development, I decided that since no object ever moved diagonally (thus, no mx=1 at the same time my=1), using two variables was not needed. Instead, I could just track the current direction with one, that would be set to UP, LEFT, DOWN or RIGHT:

uint8_t direction;

And, because ghosts look one tile ahead to decide where they will turn when they get there, and because Pac-Man allows the player to push the joystick in a different direction as he is moving and instantly be ready to turn there, I added:

uint8_t nextDirection;

When I share the updated code, this will make more sense, and the new code should also be much simpler.

3. Ghost A.I.

With the basics of a maze and ability to move around it figured out, I then moved on to the logic of the ghosts. Pac-Man ghosts basically just try to move towards a target tile. That tile either causes them to scatter to a corner, or to try to track down Pac-Man, based on the mode the game is in.

To achieve this, I created some functions that let the ghost determine what it’s next direction should be at every intersection. It does this by comparing the tiles it could turn to and seeing which one is the closest to the target tile. Once I had targeting working, the only thing left to do would be add code to change the tiles as the game modes changed (from scattering to the corner, to chasing Pac-Man, to running away frightened after an energizer pellet was eaten).

There are also some special rules that needed to be taken care of, like the four passageways that ghosts are never allowed to turn up, and handling the side tunnels.

4. Dealing with Dots

A big portion of the project, currently left untouched, is figuring out how to handle all the dots on the screen. I have previously shared my idea on how this will be done, but I have yet to write any code to test this idea (this will be next). Once this is done, there will be very little left to do for the “engine” of this game to function.

5. Miscellaneous TO DO

The final part of this project will include coding some specific routines to handle things like:

  1. Scoring as Pac-Man eats dots.
  2. Collision detection between Pac-Man and Ghosts.
  3. Changing mode to FRIGHTENED when Pac-Man eats an energizer pellet.
  4. Displaying bonus fruit at appropriate times and scoring if eaten.
  5. Altering speed of Ghosts and Pac-Man based on levels and mode. Also, ghosts slow down in the tunnels, Pac-Man is slower while eating dots, and Pac-Man can slightly cut corners when turning.
  6. Intro screen, intermissions and high scores.
  7. Sound.
  8. …and probably many other things I haven’t even thought about yet. For instance, just yesterday, I saw a “cut scene” between levels that I had never seen before. I will have to find videos of all of them to try to recreate them.

And with that out of the way, it’s time to resume this project reboot, and share the current state of the code.

To be continued…