Monday, May 8, 2017

Quick Update

Hello everyone,

I know I've only posted twice on this blog, but I've got updates planned for the near future. I recently entered graduate school for Electrical Engineering, and I'm working a full time job at the same time. So I'm a bit busy! But I have a lot of ideas and a lot of projects in process. I'm working on a SNES wireless controller, and updating it to Bluetooth instead of RF for a stronger signal and PC interfacing. Should be neat!

Another big update is I'm going to be migrating this blog to Wordpress. It seems more up-to-date than Blogger, and a bit more flexibility in design. The tutorials might serve better there. I'll keep these two tutorials up, but I'll only be updating them on Wordpress once I'm finished migrating there. Of course, you can continue to comment here and I'll help out any way I can, or you can email me.

Thanks for checking this out! I'm glad I could help so many people with their NES hobby projects. I hope to expand soon to other non-Nintendo projects, too, so check back soon.

Thanks,
Nick

Saturday, October 25, 2014

How to Make an NES Reproduction Cartridge

Nintendo enthusiasts, myself included, know the value of playing a game on the actual hardware, rather than on an emulator. There exist USB adapters to take your NES controller and make it work with emulators on your PC and try to mimic playing the real hardware, but it just doesn’t give you that authentic NES experience. Don’t you wish there was a way to play some of those classic games on a true NES without spending exorbitant amounts of money? Or some Japan-only games without having to learn how to speak Japanese? Or your very own (or someone else’s) ROM hack or homebrew games?

WELL NOW YOU CAN!
 
This tutorial will teach you how to reproduce (almost) any NES game, provided you can find a suitable ROM file. I know there are a handful of these tutorials out there, but I had yet to find one that was as comprehensive as I'd like it to be. Also, since I try to teach a bit of electronics to people who read these tutorials, hopefully you’ll learn some basic electronics principles and more about how EPROMs work.

 Even games like these! If you don't want to spend a few hundred on getting copies of these, you can just make them yourself!


Things you will need (specifics detailed further in tutorial):

1) A donor game. Usually a game that is pretty cheap, or that you don't care about anymore (please don't destroy your copy of Megaman 3). You'll need a specific donor depending on what game you want to reproduce.
2) EPROMs. The heart and soul of the NES game. This is where the game data is stored, on two separate chips. You'll typically need at least two of the same size, as most games use two, which are called a program (PRG) and a character (CHR) ROM. Some games only use the PRG ROM. I buy these chips in groups of 10 on eBay for about $15.
3) EPROM programmer. This is what you use to... program the EPROMs. I got mine on eBay for about $42. It's a TL866CS MiniPro programmer. It's worked flawlessly for me, and it's pretty easy to use.
4) EPROM eraser. This is for prepping your EPROMs, and fixing your inevitable screw-ups. Got it on eBay for $16 (can you tell I like eBay?). You can forgo this one if you're really hurting for $16, but it'll be a lot less hassle if you just get one. Many sellers claim that the EPROMs they sell are empty, but you don't want to take the chance that you get some that have random data stored on them. Plus, if you mess something up during programming, you'll be able to start over.
5) Miscellaneous hardware. At the bare minimum, you'll need wire (I prefer smaller gauge), solder, and a soldering iron. You'll also probably want a screwdriver that can open NES cartridges (called an NES Security Bit), or if you're cheap and really like making things harder for yourself, you can try to use pliers to remove the screws. But for $6 on Amazon or $1 on eBay (you'll have to wait about a month for shipping, though), it's really worth it. Trust me, I've been there. I used to melt the ends of old mechanical pencils to try to make a mold of the screw and use that. Not worth it.
If you do go and buy the security bit, be sure to get the 3.8mm size, and not the 4.5mm


Look at all the nerd cred you gain from this project!

I spent around ~$60 for all the necessary equipment, not including things like my soldering iron (which I already had). Each game you make will cost about $10. Not extremely cheap, but all this equipment gives you the power to make a ton of different games for which you could be spending upwards of $40. As such, I don’t recommend using this method to make games like Super Mario Bros., because you’re apt to find them for a few bucks. Reserve this method for the rare, wallet-emptying gems.

So let’s get cookin’ (or rather, brewin’) some good ol’ NES games.

Introduction to NES Cartridges

Before we start making all these games, there are a few things we need to determine about the game we want to make. NES games were produced spanning nearly a full decade, so it’s natural that the games both made technical leaps throughout its lifetime. For example, games like Balloon Fight don’t take up nearly as much space as a game like Super Mario Bros. 3 does. Also, ROMs can come in many different sizes, which require different PCB layouts with different supporting circuitry (most notably, a chip called a “mapper”). A game like Balloon Fight doesn’t use the same mapper (or even use the same kind of ROM chip) as a more complex game like Super Mario Bros. 3 does, so it follows that you wouldn’t be able to use a Balloon Fight PCB to make SMB3. 

This, of course, means you must choose a compatible donor cartridge for the game you wish to make. This can prove tricky for some games, as a few (such as Mike Tyson’s Punch-Out!!) are either the only game or one of a few that uses a certain PCB class. Or you might get some really weird layouts that are pretty much impossible to replicate without making your own boards from scratch. It's possible for some types of PCBs to be reworked for other games, but they need to already be pretty similar. I'll go into more detail about this later, for now, let's get started prepping your game.

 
Punch-Out is so special, it's the only one to use the PNROM PCB class. Guess you'll just have to buy it, cheapo!

Step 1: Find a suitable donor cartridge.

So how does one find which cartridge is right for them? Personally, I've relied on the amazing website NesCartDB. This website is so extremely detailed and a very powerful tool for all your repro needs.

IMPORTANT NOTE: NesCartDB is hosted on a private server. Sometimes the website goes down from time to time for various reasons. For three months in the summer of 2016, the server was offline due to hard drive issues. In the downtime, the great community at NesDev had been working to provide an alternate, and tech support to try to revive the database. I recommend you use this website if NesCartDB is ever non-functional:

NesCartDB by MiemoNES

All you do is search your game, and it will tell you which are suitable donor cartridges to use! Super easy to use, but it does not provide all the information NesCartDB does.

If you run into issues on this website (I haven't explored everything myself), you can reference this website as well:

Bigass NES Mapper List

It has very basic information about the cartridges. It's mostly accurate, but I've heard of a bit of misinformation on some of the games.

So, on NesCartDB, simply look up the game you want to make on the database. Keep this page open in another tab as a reference. Now, find the “PCB type” of your game and click on it (examples include TLROM, SLROM, CNROM, etc). This type is determined by the kind of mapper it uses, among other things. It’ll bring up a list of suitable donors. Just sort through the games; you'll probably want to look at games that are in your region, since you'll be able to easily get them and use them in your NES without worrying about region locking. Sometimes NesCartDB lists the same PCB types slightly differently, for example TLROM and TL-ROM, so you can try searching those variants as well. There’s a search function on the top menu bar. Depending on the kind of game you choose, you might need to rewire your cartridge a bit, but we'll get into that later.


Click the thing in the red circle, if you didn't know what I was talking about.

You’ll want to be sure the donor cartridge and the game you want to make have nearly identical PCBs. Watch out for how many holes the PCB has for the ROM sockets! NesCartDB provides pictures of the PCBs for nearly every game in the database, so it's easy to compare. I have bought games before that won't work for my donor because they have a weird layout. I could've avoided that if I had just compared the PCB picturs on NesCartDB before buying it.

Also, if you are trying to reproduce a game that has a PCB class listed something like "KONAMI-TLROM" you'll still be able to use the regular PCB class. Sometimes different publishers produced their own boards, but they should still be interchangeable with Nintendo-produced boards.

Note: If you're using a UNROM board, you'll require 32 pins, but only have 28 available. Don't worry, I'll explain later. Just carry on.

Another thing to note is if you're planning on putting a ROM hack onto a cartridge, you'll have to do a bit more work. Some hacks change the kind of mapping that the game uses, so the board of the original game might not simply work with the hack. You'll have to find that information out for yourself. Usually, the game's author will readily have that information available to you. If you need help figuring it out, you can contact me and I'll see if I can give you any advice.

Anyway, most of the cheapest games I’ve found were $5 on eBay or Amazon. Or, you could be a weirdo like me, and print out a list of all the suitable donors and bring it to your local vintage gaming shop and get lots of suspicious stares from the employees as you pore through their collection.

Why hello, I'm looking for "Sesame Street: Big Bird's Hide and Speak" for the NES.
Step 2: Choose your EPROMs

What even is an EPROM?
EPROM stands for Erasable Programmable Read-Only Memory. Basically, it holds information that you can program to read later. You write information onto the EPROM using a programmer, and then that information can then be accessed later, but not rewritten (without an EPROM eraser).

The way data is accessed is through the data pins and address pins. To program the EPROM, the /CE (chip enable) and /PGM (program) or /WE (write enable) pins are tied to logic low (VSS or 0V), and the /OE (output enable) pin is tied to logic high (VCC or 5V). Note the bar above the symbols (which I indicate with a slash) - this means it's inverted logic, where a high voltage means disabled (OFF) and low voltage means enabled (ON). Some EPROMs might use non-inverted logic, but ours do.

An address is called out using high or low voltages on pins A0 to A16 (A17 or A18, for the larger EPROMs). Then, using data pins DQ0 to DQ7, a byte (eight bits of "1" or "0") is loaded parallel onto the data pins. In reality, only the 0's are written to the pins, because by default all the pins start as 1's. A 0 is written to the memory cell (actually a transistor, or a switch) by applying a high voltage onto the pin. Once enough voltage has been delivered to the data pin you desire to be 0, that data will be permanently "programmed" onto that address, until you reset it back to a 1 with UV light. It's similar to gluing a switch in one position so that it can't be moved. Once the byte has been written to the specified address, a new address is called out and new data can be written. This is done for each and every address, until it's filled up.

When you want to recall the data you programmed onto the chip, simply call the address you want to look at on the A pins, tie the /OE and /CE pins to logic low (to enable them), and read the voltages that are now applied to the data pins you programmed earlier. When the NES is playing a game, it's just reading the data on the different address locations. These data pins are what's known as bi-directional, with their function being controlled by the /OE, /CE, and /PGM pins.

Your basic EPROM. So much data shoved into one deceiving tiny little package. It'll have either 28 or 32 pins, and a little window on the top.
See the little window on the top? That's how the EPROM eraser deletes the information on the chip. You can't simply reprogram the memory like modern memory devices by writing over old data with new data (unless you just want to change a few of the 1's to 0's). The only way to erase the information is by blasting the window with a specific wavelength of UV light. "But can't I just stick it on the windowsill and let it get a sun tan?" Well, sure you could, but it might not effectively erase all the data in a timely manner. You should probably just get the eraser.

I swear, I don't work for eBay.

So why don't the EPROMs in my cartridge have those little windows? Well, they're not actually EPROMs, but what's known as a "mask ROM". The "mask" part basically means what it sounds like - it isn't erasable, because that functionality is "masked". Kind of a bummer, really, it'd be really nice to be able to just reprogram the game without having to buy new parts.

EPROMs (the chips) are defined in their sizes by bits instead of bytes (8 bits = 1 byte). ROMs (the game files) are defined in bytes. So, a 2 Megabit (Mbit) EPROM can hold code up to 256 Kilobytes (KB). A 1Mbit EPROM can hold code up to 128KB. This is a bit confusing, but very important! Check your CHR and PRG ROM sizes for the game you want to make on your NesCartDB page, and see how much space each needs.

The maximum size of ROM that you can store on a 28-pin EPROM is 64 Kilobytes. Any CHR or PRG file that is GREATER THAN 64 KILOBYTES NEEDS A 32-pin EPROM.

There are two different types of EPROMs that I use, which I got from eBay - a 4MBit and 512KBit model. I use the M27C512 for smaller games (512KBit, 28 pins), and the AM27C040 for larger games (4MBit, 32 pins). You can buy other models of EPROMs if you'd like, these are just the two specific models I use. If you choose different models, check your pinouts - if they are different than the ones I use in this tutorial, your wiring will be different!

Between these two EPROMs, you should be able to load most any game you want to make. The M27C512 is the largest EPROM size you can get with 28 pins, and the AM27C040 is the largest size you’ll ever need for 32-pin boards, as no NES game uses any ROM larger than this.

NesCartDB really is the bible of NES games.

For example, the game Little Samson's PRG ROM is 256KB, and the CHR ROM is 128KB, so I will need one EPROM that can hold at least 2MBits and another that can hold at least 1Mbits. You can use bigger EPROMs, though, which is why I recommend just getting a lot of the largest sizes since the price difference is usually trivial.

Protip: When searching for them on eBay, it's more economical to get groups of them, rather than single pieces. A lot of sellers use terms like "10pcs" or "x10" when they are selling groups of them. It's usually about $15 for 10 of them if you get them from China. I haven't had any problems with mine yet, so I'd say it's a safe bet. You'll just have to wait a bit longer to get them in the mail.

eBay, proud unofficial sponsor of the Poor Student Hobbyist.

Step 3: Find the ROM file for your game

I’m not going to tell you how to… acquire these files. Use Dr. Google – search “[name of game] ROM”. Be wary of sketchy websites, and whatever you do, don’t install a “downloader” to download your file. This could be malware. You’re looking for zip files of the actual game, not executables. Inside should be a .NES file, and possibly a readme or some other useless text documents.

Again -- don’t run any executables!

Also to note, if you're planning on making a foreign game, you'll want to see if you can find a patch for the ROM that will translate it into English. I'm not going to go into detail on how to patch the ROM, but any patch you find should be accompanied with instructions. It's usually as easy as running a short program.

Once you've readied your ROM, it might be a good idea to download an emulator and try it out a bit, just to make sure it downloaded/patched correctly and isn't corrupted. It'd be a shame to waste all this time and energy putting a corrupted game into a cartridge. I use JNes for all my emulation needs, but there are plenty other emulators out there that will work just fine.

Step 4: Split your ROM file into the CHR and PRG files

Before you do this step, make absolutely sure your EPROM can hold the ROM file. Remember, EPROMs are defined in BITS, where ROMs are defined in BYTES. Eight bits equal one byte. Reread the section above and make sure you picked the right EPROM.

Your .NES file you downloaded in Step 3 contains both the CHR and the PRG files (or just the PRG file, if your game doesn't utilize a CHR ROM). These two files will each go on a separate EPROM. I use ReadNES3 to do split the .NES file (here's the GitHub link).

Once you extract the Zip file, simply drag your ROM file and drop it on ReadNES3.exe that came in the folder. You should get two new .BIN files in your folder now, with the suffixes "Character" and "Program". These are the files we're going to load onto your EPROMs. You'll note that if your game doesn't use a CHR ROM, the file will be 0kB large, so you can ignore it.

Before we load them, though, we should make sure the EPROM is filled up. This is only necessary if your EPROM is larger than the ROM's CHR or PRG file. Don't really need to worry about the specifics, but basically it's to ensure if any of the extra data on the EPROM is accidentally accessed by the NES, it won't be random junk information.

Remember, EPROMs are listed in KBits, so you need to divide by 8 to get the size in KB.

Now, to fill up the EPROM, all we need to do is duplicate the .BIN file until it's large enough. This can be achieved by a simple line of code run in command prompt (press Windows+R, type "cmd" and hit "OK").

First, make sure the command prompt is working in the folder that contains your ROM files. You can use the "cd" command to change the directory. Here's an example of what I would type in:

cd C:\Users\Nick\Documents\

Just fill in the directory where your ROM is located. Your directory should switch to that on the next line.

Now, let's say I have a PRG file that is 128KB, but I have an EPROM that is 2MBit (256KB). So I need to double the PRG file. We do this with the following line of code:

copy /b gameProgram.BIN + gameProgram.BIN gameProgramFill.BIN
The "copy" command, obviously copies the data, and "/b" is to denote that the data is in .BIN format. The line of code essentially doubles "gameProgram.BIN" and stores it into the file "gameProgramFill.BIN".

Let's say I have an EPROM that is 4MBit (512KB). Instead of doubling it, you would quadruple it.

copy /b gameProgram.BIN + gameProgram.BIN + gameProgram.BIN+ gameProgram.BIN gameProgramFill.BIN

Now, compare the sizes of the PRG and CHR files, and the sizes of your EPROMs. They should be the same.

Ready to program them? Hell yeah you are.

I'm a lean, mean, programmin' machine. Slow down, ladies.

Step 6: Program your EPROMs

If you got the MiniPro programmer that I recommended above, you're in luck, because I can totally tell you how to use it. If you have a different EPROM programmer because you found a cheaper one or already had one because you're a nerd, you'll have to find the specifics elsewhere.

The MiniPro comes with a tiny disc that has the programmer. It's pretty self explanatory, but I'll run through the steps real quick-like.

1) Select your IC by using the "Select IC" menu option on the top bar (how cryptic!). The catalog here is pretty extensive, they should have your brand.

They don't have my brand! I have special EPROMs.
2) Do a blank check! Did you remember to erase your EPROMs in your UV eraser? Navigate to "Device > Blank Check" on the menu bar. Hopefully they're blank. If not, try blanking them again your UV eraser. If they still don't work, you might have a defective EPROM, or it's not connected to the programmer properly.

3) Get your PRG or CHR file loaded into the program. This is under "File > Open" (wow, these menu options are so hard to decipher.) The default load options should be correct, make sure the File Format is "Binary" and the Load Mode to be "Normal".

4) Program em! This is under "Device > Program".

5) To be safe, you should verify your program loaded correctly ("Device > Verify"). I've never run into a problem with it programming incorrectly, but if you do just blank your EPROM and try again.

6) Put some tape over the little window, and mark down what ROM is loaded onto it. You want to make sure you know which EPROM has the CHR file and which has the PRG file!

7) Repeat, if necessary, for the other EPROM.

Congratulations! Your game has a brain. Now to give it a body.

No, not that kind of a body! And no, I'm totally not trying to rip off the format of a Cracked article...

Step 7: Begin surgery on your donor cartridge

Open your donor cartridge (hopefully using that special screwdriver I told you to get). See the mask ROM(s)? These need to go.

Note: We do not want to remove any other chips. If your board uses RAM, do not remove it. RAM is non-volatile memory, which means when the RAM loses power, all memory on the chip is lost. Thus, there's no reason to remove the chip, because the ROM takes care of storing all the data.

If you can't tell which chip is which, look on NesCartDB. They do a good job of letting you know which chips are what.

Use the detailed chip info section to decipher what chip is what. Just match the model numbers, you'll be able to figure it out. I believe in you! This is actually the board to The Legend of Zelda. It only uses one mask ROM.
There are a few methods you can go about doing to removing your ROM chips.

1) Use a soldering iron and some copper wick to remove all the solder. This method is the worst one. It stinks. The solder on the games is old, takes a long time to get all of it out, and you'll probably end up burning yourself. 

2) Use a solder sucker to remove the solder. This one is preferable, granted you have access to a solder sucker. You can get a cheapo plastic one for a few bucks, but I've never had any success with using that. My employer, however, happens to have some actual pneumatic solder suckers, so I used one during my lunch break one day. Process goes really fast and clean, only took me a few minutes to get the chips off the board.

3) Cut the pins, remove the chip, and then remove all the remaining bits of metal stuck in the holes. You can cut them using some wire cutters, or better yet, a dremel. You have to be really careful if you decide to use a dremel, though. I have more than once accidentally taken out a few of the traces on the PCB using mine, which I had to go back and manually repair with wire. It's not fun.

See that little scratch right above the bottom row of pins on the right side of the board? That's where I cut one of the traces. I ended up having to painstakingly and very carefully solder an extension wire off of the trace.
Now you’ve hopefully got a nearly blank, undamaged PCB with ONLY the mask ROMs removed. Make sure the sockets are fully empty. If there's any residue solder left in those holes, it'll be a pain putting your new EPROMs in.

Step 8: Wiring up the PCB

This step is only necessary if your EPROMs are larger than 512KBit (if either of your EPROMs have 32 pins). If they are 28-pin EPROMs (except for UNROM boards!!), then go ahead and place them in the sockets and solder the corner pins down. You might have to bend the pins a little bit to get the EPROM to fit in the socket(s). Then you can skip ahead to Step 8. Lucky you!

If you're using a 32-pin EPROM or UNROM PCB type, you'll have to do a bit of work. 

So, Nintendo was clever. As the games got more advanced, and more memory was necessary, the memory management on the board (which was handled by the "mapper" chip) needed to become ever more advanced. Games started becoming larger, which is when you started seeing the 32-pin EPROMs crop up. The extra pins were necessary to make the leap from 64KB to 128KB games.

These new larger ROMs would require a new layout on the PCB. But, some games only required the CHR or the PRG ROM to have more space. They only required the 28-pin package. In order to keep the PCBs generally interchangeable, Nintendo decided to use 32-pin ROMs with a modified pinout so that the board would accept both the 32-pin and the 28-pin chips. Remember how I mentioned that games which don't utilize all 32 pins just let four of them alone? These four pins are the added pins to the larger ROMs. If the game developer didn't need to use all the extra space on the ROM, they could use a smaller one and still be able to place it in the same PCB. Clever girl, Nintendo, clever girl.

So, what does that mean for us? Well, since we're using standard EPROMs, we need to do a bit of rewiring. Again, this is only necessary if you're using the 32-pin EPROMs. The rewiring isn't too complex, but you need to exercise caution when doing this step - I've ruined a few EPROMs because I was hasty. I'd also recommend using thinner gauge wire. Thick wire gets in the way really easily (you'll have to route wire on top of your EPROMs), and can make your cartridge bulge in the middle.

This was my first reproduction. You can see the pins of the EPROM in the middle of the cartridge where it bulges the most, due to the larger gauge wire I used. The cartridge is also a bit harder to fit in the NES.
I'll list the necessary modifications depending on your PCB class. Here's the general steps you should take for rewiring your board. Use these steps with the modifications I list afterwards:

1) Bend up the necessary pins on the EPROMs. Be very careful doing this - go slow and make sure you're not putting the bend stress on the part of the pin closest to the package of the chip. I've broken off pins by not being careful, and let me tell you, it's a major pain in the ass to fix. Also, clip off the thinner part of the lifted pins, and just use the flat parts. They'll get in the way of the cartridge closing correctly otherwise. Note that these lifted pins might just stay lifted, they might not necessarily be wired anywhere.

2) Solder long wires into the necessary holes on the PCB before you put the EPROM in. Be sure to use long enough wire (8 inches or so), at least for the first reproduction you do, so you don't make your life difficult. As you get more experienced, you can cut back on the length of wire and make it look much cleaner.

3) Place your EPROMs in the corresponding sockets. Make sure the CHR and PRG EPROMs go in the correct place! Nintendo was nice and labelled which socket is which. You might have to bend the pins a bit to get the EPROM to fit correctly. Also, I wouldn't solder all the pins in just yet. You might have to reprogram them or change some wiring you missed. Just solder a corner or two in to keep it anchored in place.

4) Route the wires you soldered in step 2 to the correct pins.

5) Solder any extra wires, if listed.

This is how I start off a board. Solder the wires into the holes, and make sure they're long enough.
For reference, here's the pinout of the EPROMs. Find the notch in the EPROM, or the dot on the chip; this denotes the top of the EPROM, and the first pin is the top-most one to the left.


Now that you know the steps to take in your modifications, just what are the modifications you need to make? Here's the most popular PCB types - I will add more if requested. If they're not here, keep reading to learn how to wire it yourself if you want! Keep in mind some games, like the Konami boards I mentioned earlier, may have different wiring, so watch out for that.

Games that use MMC1 mappers (SxROM boards) and MMC3 mappers (TxROM boards), also applies to AxROM boards:

128KB PRG ROM:
Bend up pins 1, 2, 24, 30, and 31.
Connect pin 1 to hole 30
Connect pin 2 to hole 24
Connect pin 24 to pin 16
Leave pin 30 and pin 31 disconnected

256KB PRG ROM:
Bend up pins 1, 2, 24, 30, and 31.
Connect pin 1 to hole 30
Connect pin 2 to hole 24
Connect pin 24 to pin 16
Connect pin 30 to hole 1
Leave pin 31 disconnected

512KB PRG ROM:
Bend up pins 1, 2, 24, 30, and 31.
Connect pin 1 to hole 30
Connect pin 2 to hole 24
Connect pin 24 to pin 16
Connect pin 30 to hole 1
Connect pin 31 to hole 2

128KB CHR ROM:
Bend up pins 2, 22, 24, 30, and 31.
Connect pin 2 to hole 24
Connect pin 22 to hole 31
Connect pin 24 to hole 2
Leave pin 30 and 31 disconnected

256KB CHR ROM:
Bend up pins 1, 2, 22, 24, 30, and 31.
Connect pin 1 to hole 30
Connect pin 2 to hole 24
Connect pin 22 to hole 31
Connect pin 24 to hole 2
Connect pin 30 to hole 1
Leave pin 31 disconnected

Reproducing a UNROM board:
This board is a bit weird. It uses a 128kB ROM, but doesn't have room for a 32-pin EPROM. There aren't any 28-pin 128kB EPROMs available, so that means you still have to use a 32-pin EPROM instead. It's... different. But not hard. Just be very careful when you're modifying the board.
On the PRG ROM:
Bend up pins 1, 2, 24, 31, and 32.
Connect pins 1, 30, 31, and 32 together.
Connect pin 2 to hole 22. (Hole 22 corresponds to the 22nd socket of the 28-pin socket on the PCB. It's the eighth hole from the bottom on the right side.)
Connect pin 16 to pin 24.
When you place the EPROM into the board, make sure that pin 3 is placed in hole 1 on the PCB. Pins 1, 2, 31, and 32 should overhang on the PCB.

Special case - boards that support batteries, but do not have one (like the game Spot):
This board has space for the battery, but does not utilize it. Therefore, some parts were omitted from the final production (some boards may have them in anyway, but if they don't, then you'll have to replace them yourself.) 

In D1 and D2, add regular or Schottky diodes (NOT zener diodes). Make sure they can handle at least 15V or so and at least 40mA just to be safe (this is probably overkill). A great, cheap one to use would be the 1N4148. When you put them in your board, make sure you put it in correctly, because orientation matters. On the 1N4148 the cathode is indicated with a black bar.





The diodes are to isolate the battery from the 5V coming from the NES while it's on. R1 and R2 should work fine with any value resistor between 1k and 10k.

In the spot labelled "CB", place an electrolytic capacitor (at least 10uF). Make sure the polarity is correct on this capacitor as well. This is to keep the RAM chip powered up just in case there's a random spike of voltage from switching the game on or off - if you don't want to put this in, it'll probably still work fine, but your saves might get erased sometimes. On old Zelda games, they used to say on the save screen to hold the reset button in before you turn off the game - this was to reduce spikes from the voltage line. They soon started putting in the capacitor to prevent you from having to do that.

If you're modifying a board I haven't listed (or just want to know why we're bending certain pins and changing the connections) follow these steps:

(Remember, this is only for 32-pin EPROMs!)

I will provide an example for each step, noted in italics - I'll be using Little Samson, which is on a TLROM PCB using the MMC3 mapper

1) Reference the EPROM layout below. If your PRG EPROM is 128KB and still 32 pins, refer to the 256KB size.
Little Samson uses a 32-pin 256KB chip for the PRG, and a 32-pin 128KB chip for the CHR





2) Compare each EPROM's pinout to the ones you are using, making sure to distinguish between the PRG and CHR EPROMs, and bend up any pins that differ from the PCB
Using 27C040 EPROMs:
For the PRG:
- Pin 1 (VPP vs A17)
- Pin 2 (A16 vs /CE)
- Pin 24 (/OE vs A16)
- Pin 30 (A17 vs 5V)
- Pin 31 (A18 vs 5V)
For the CHR:
- Pin 2 (A16 vs /OE)
- Pin 22 (/CE vs GND)
- Pin 24 (/OE vs A16)
- Pin 30 (A17 vs 5V)
- Pin 31 (A18 vs /CE)

3) Connect the pins to the correct holes (VPP is the same as VCC or 5V, and VSS is the same as GND). If you don't have an /OE hole, then connect it to a GND pin. If your EPROM has a /PGM pin (located as pin 31), connect it to GND. Do not connect any unused outputs (A17 or A18), instead leave them floating.
For the PRG:
- Connect pin 1 to hole 30 or hole 31

- Connect pin 2 to hole 24
- Connect pin 24 to pin 16
- Connect pin 30 to hole 1
- Leave pin 31 disconnected
For the CHR:
- Connect pin 2 to hole 24
- Connect pin 22 to hole 31
- Connect pin 24 to hole 2
- Leave pins 30 and 31 disconnected

So, finally, after all that work, here's how my boards usually turn out.

Not pretty, but it works. I used tape to keep the wires in place. I also used thinner wire so that the cartridge didn't bulge this time.
Go ahead and solder the rest of the pins in. If you're not confident, you can test out your game first and then solder the pins in if all is well. But you might not have a good enough connection on the pins. The advantage of keeping your EPROMs unsoldered is that if you made a mistake, it'll be easy to pull the chip back out.

Step 9: Test out your game

The moment of truth! Reassemble your cartridge, and make sure you're not pinching any wires (hence, the tape). Throw it in your NES, turn it on! Hopefully, it'll work. Play it for a few minutes, and make sure everything works fine. Take it back out and fully solder the EPROMs in, if you didn't already.

But, if your game isn't working, don't panic yet!

Some games have what's known as "mirroring". It basically controls how graphics wrap around the screen. Horizontal mirroring is used for games that scroll vertically (like Ice Climbers), and vertical mirroring is used for games that scroll horizontally (like Balloon Fight).

Here's the PCB for Balloon Fight.
See the little solder bead underneath the left mask ROM? It's connecting the wire used for vertical mirroring (denoted by the "V" on the board).

If your game is working fine, but the graphics just scroll the wrong way, then that means you have the wrong mirroring active. Just switch to the other pad on the PCB. An easy fix, but not all games use mirroring techniques.

If your solution isn't that easy, don't lose hope yet.
If you didn't solder the EPROMs in yet, you could try soldering the pins in. You might not have good enough connection from the pins to the board. But first I'd check the wiring to make sure you didn't make any mistakes. If you have a multimeter, do continuity checks on all the necessary pins and wires.

If your wiring is all good, check the board again and make sure you didn't accidentally cut any traces when removing the mask ROMs. If there are any damaged traces, you'll have to repair them with wire.

If your wiring is good and you've soldered in all the pins, try re-soldering them by heating them up with your soldering iron. Don't let the tip sit on the pin for too long, but get the solder "flowing" again. We want a good shiny surface that makes a concave structure onto the pin like this:

Look at that beaut.

If you still can't figure out what the issue is, you might have had a programming error, or your chip got damaged somehow through static electricity or some cosmic particles ruined your EPROM or some other voodoo excuse. You can always try removing your EPROMs and verifying the program again. Just keep analyzing your board, or post your problems to the NesDev or NintendoAge forums. They're usually pretty helpful. You can ask me, too, if you'd like. I try to get back to comments within a few days.

Step 10: Make your cartridge look pretty

So now you've got your game all made up and working, you can add the label to the cartridge. Personally, I haven't made a label yet, but when I finally get around to it I'll update this tutorial with how I did it. I'm usually more preoccupied with playing the game, rather than looking at it. There are plenty of resources online to help you find out how to make the labels.

Here's a quick and dirty tutorial:

1) Remove the old label. Use Goo Gone, or I've heard that baking soda and vegetable oil mixed together does a decent job of removing it.

2) Find the box art, or actual cartridge label, and fit it into a cartridge template. There are plenty of templates for the label size online.

3) Print your design(s) on a full sheet label. I recommend printing more than one cartridge label at a time, because the full sheets get expensive. See if you can mooch off of someone, or buy them in single pieces from your office supply store.

4) Use a full page lamination sheet to cover your full sheet label. That'll give it a nice shine.

5) Cut out your label and place it on your cartridge. Done!

Or you could use this guy's method to really bring out the magic in your NES reproduction.
Conclusion

Congratulations! You have successfully created your own reproduction NES game!
But remember, with this great power comes great responsibility. If you're going to make these reproduction cartridges, please be sure to mark that they are reproduction cartridges so they're not mistaken for genuine ones if you end up trading or giving it to someone else. Don't play it off like it's the original thing. That's called breaking the law, and being a jerk.

I hope this guide helped you out in your quest to play some rare NES gems! I tried to be as clear and comprehensive as possible, but I'm sure I missed something here or there. If you find any errors, let me know and I'll try to fix it. If you find some board instructions I left out, let me know and I'll add them to the tutorial. If you're still having trouble, don't hesitate to comment or email me! I'll try to update this with anything else I find.

Have fun!

I got a lot of information from the great people over at NesDev.com. They have a lot more information than I posted, and if you're itchin' for more technical stuff, head on over there and check it out!

Sunday, July 28, 2013

Wireless NES Controller Using Arduino

I was playing Mega Man 2 in my living room on my NES, sitting just far enough away from the console that the cable for the controller was taut. Nearly pulled the NES off of the table. A problem from a simpler time, I thought. I could get this to be wireless, surely!

So I got to looking online for solutions.

Well... I found this. But I'd rather make my own. It'll be a fun little electronics project!

Not counting the 3D printed case and smaller parts like resistors and capacitors, I spent overall about $40 on this project. Here's what we'll need:

1) One NES controller
2) Two ATMega328 processors (and an accompanying Arduino board to program them)
3) One wireless transmitter and receiver pair (about $10)
4) A shift register (such as the CD4021, which just so happens to be used by the controller)
5) Battery charging circuit
6) Lithium ion battery (I used a 330mAh battery, but even something as small as 100mAh will still get you ample play time - make sure it can fit in the controller!)
7) Protoboard
8) A switch - I used these, but you can use your own and drill a hole in the model for it
9) Miscellaneous components (resistors, capacitors, 16MHz crystal oscillators, and LEDs)

You'll also need access to a 3D printer. If you're still in school, check to see if you can get 3D printing services. If they don't, you can send it out to get it made on some website, or you can order one from meJust email me (thepoorstudenthobbyist@gmail.com) with the model you want, and I'll get back to you on a price and time frame. I might even do some custom orders, if you ask nicely, and don't have outlandish requests. Currently I can only print in white, though. But you can paint it if you wanna. Here's the Thingiverse entry for the controller and the receiver.

I bought most of my supplies on eBay from China. It takes a few weeks to get here, but the savings can be great for the simpler things. As a quick comparison, you can buy a single ATMega328 on Amazon, Adafruit, or Sparkfun for upwards of $5, or you could buy a five pack from China for little more than $10.

The transmitter and receiver seem to be best available at Sparkfun, so you might want to consider buying the battery and battery charger from there as well to cut down on shipping costs. The only part of this tutorial that would be slightly different is for the battery charging circuit.

A note on the batteries - make sure your battery will fit inside the controller. A 2000mAh is awesome, but complete overkill. And definitely won't fit in the controller I've designed. Keep it under 500mAh and you should be good. The space provided in the controller is about 1" x 1.5".

Enough boring exposition - let's kick off this journey by learning how the controller actually works. If you're so inclined to skip the prototyping steps and just build the controller, skip to the "Expanding the Transmitter Test Unit" section.

How the NES Controller Works


The NES controller is surprisingly and satisfyingly simple, actually. It uses a single IC - the CD4021. Just a simple shift register. The schematic for the controller is below.

Note: When figuring out which wires correspond to which pins on the controller port, do NOT trust any color diagrams you find online. Mine did not match the one I found, and it turns out Nintendo changed the convention a few times. The easiest thing to do is use a multimeter and figure out which wires go where.

If you are wondering, I use TinyCAD for schematic drawing.
So each button on the controller corresponds to a different digital input into the shift register. The NES sends a pulse through the latch wire (on the P/S pin) at a rate of 60 Hz, or once per 16 ms. When the shift register receives this pulse, it takes the states of the buttons and sends it through pin 3 (Q8, labelled as "Data" above) as serial data. The rate at which this data is sent is determined by the clock speed, on pin 10 (approximately 83 kHz, sent from the NES). The NES will take this serial data from the data wire. The data is analyzed from the pulse train, the state of each button is determined, and the game takes care of the rest from there.

A timing diagram for the NES and the controller. The NES sends the latch and clock pulse trains, the controller sends the data pulse train. In this example, the B and Left buttons are pressed. Note that a pressed button is represented by a low signal.

If this explanation isn't sufficient enough, here's a more in-depth explanation of shift registers. If you know how they work, you can skip ahead.

Each button is either on or off. This is classically defined as a 1 or a 0, however in the case of the controller, they decided it was easier to set on as a 0 and off as a 1 (a "1" state is 5V, a "0" state is 0V). This achieved using the resistors R1 through R8 (which are known as "pull-up" resistors, because they pull the signal up to 5V) which are paired with the buttons. When the button is not pressed, the circuit is not completed, forcing the pin on the shift register to 5V from the supply. When the button is pressed, the pin is grounded, forcing it to 0V.

The states of these 8 buttons, reading either 5V or 0V, are collected by the shift register. When the P/S pin is activated by the NES using a small pulse, a snapshot of the button states is taken, and is fed through the serial output as a string of 8 bits (or a byte). This string of 8 bits would be represented by an oscillating square wave, if you were to look at the signal on an oscilloscope. Once the 8 bits have been fed through and read, the NES sends the pulse again to take the next snapshot. So, if you were playing Super Mario and you were running to the left (so holding the B button and the left D-pad), the byte would read 10111101.

Make sense? It's not complicated once you get the hang of it. It's worth mentioning that the data going into the shift register (8 separate pins) is known as "parallel" data, and the data coming out (one single pin) is known as "serial" data. This is a good idea, because otherwise there would be 7 more pins coming out of the controller port if they decided to go only the parallel route.

So here's how our overall system will work. The NES controller will send its button presses to the digital pins of the transmitting ATMega328. This transmitter will send the button presses wirelessly, as a byte, to the receiving ATMega328. This receiver will analyze the byte, determine which buttons were pressed, and mimic those button presses to the shift register through eight digital output pins. The NES will then read the parallel data on the shift register and receive it as serial data as it would a normal NES controller.

Simple, right?

If this picture doesn't make it look simple, nothing will.

The Beginnings of the Receiver


Now that we know how the controller works, we can begin to make the receiver end of the wireless controller. You'll need a CD4021 shift register. They're widely available today, even though they're 30-something years old. I found a bunch at my local electronics hobby shop, or you can buy them online for about $0.50 (I recommend eBay if you don't mind waiting for things from China - I got about 10 for a buck). The Arduino IS capable of sending serial data to the NES, which would eliminate the need for this external shift register, but this way to me is easier to program and troubleshoot without more expensive equipment (like an oscilloscope).

The CD4021 chip makes this baby hum. It's not humming a very complicated tune, either.
Now that we have the shift register, find ten resistors to use as pull-ups (shown as R1 through R10 below). I used a few 10kΩ resistors myself, since I had a lot lying around, but most sizes between 1kΩ and 50kΩ should work fine, since we're not using current to control our ATMega. You'll want to keep the resistor size above 1kΩ, as lower resistances might pull too much current from the NES. The wiring schematic I used is shown below.


R11 is connected to a pushbutton, used to start the program used for debugging. In the final product, this button will not be used. I used pins 2 through 9 to correspond with the buttons shown in the previous post. Use the table below for reference.

Arduino Digital Pin4021 Pin4021 Pin NameNES Button
D27P1Right
D36P2Left
D45P3Down
D54P4Up
D613P5Start
D714P6Select
D815P7B
D91P8 A

The NES reads the button states in this order: A, B, Select, Start, Up, Down, Left, Right. It's important that we use this order of buttons in our program and keep the pins consecutive. This will become apparent later in the tutorial.

I've cut off a controller port from our controller, and soldered new wires to the small ones to put in a breadboard.
What the board will look like after wiring up the controller port. The three LEDs are from another project, and it is not necessary to use them.

After connecting everything shown in the schematic above, you can run a test program. For my program, I simply flashed the start button on and off every two seconds. The code I loaded into the Arduino to test this is below.

NOTE: Be sure to disconnect the USB cable from the Arduino when plugging it in to the NES - otherwise power will backfeed into the NES from the controller connector. When you turn the NES on, the Arduino will turn on from power coming through the 5V pin on the connector.

//Presses start button on and off every two seconds
int right=2;
int left=3;
int down=4;
int up=5;
int start=6;
int select=7;
int b=8;
int a=9;
int button=11;
int ledpin=13;

void setup() {               
pinMode(right,  OUTPUT);
pinMode(left,  OUTPUT);
pinMode(down,  OUTPUT);
pinMode(up,  OUTPUT);
pinMode(start,  OUTPUT);
pinMode(select,  OUTPUT);
pinMode(b,  OUTPUT);
pinMode(a,  OUTPUT);
pinMode(button, INPUT);
pinMode(ledpin, OUTPUT);
digitalWrite(right, HIGH);
digitalWrite(left, HIGH);
digitalWrite(down, HIGH);
digitalWrite(up, HIGH);
digitalWrite(start, HIGH);
digitalWrite(select, HIGH);
digitalWrite(b, HIGH);
digitalWrite(a, HIGH);
}

void loop() {
  //Wait til button is pressed
  while(digitalRead(button)==LOW){
    digitalWrite(ledpin, LOW);
    delay(100);
  }
  while(1){
    digitalWrite(start, HIGH);
    digitalWrite(ledpin, LOW);
    delay(1000);
    //Flash led connected to pin 13, and emulate start button press
    digitalWrite(start, LOW);
    digitalWrite(ledpin, HIGH);
    delay(1000);
  }
}


Pop in your favorite game, and see the game respond to your start button presses! Now if you want, you can program in other button presses. You can even, oh I don't know, program it to run the first level of Super Mario Bros.




While waiting for my wireless dongles to come in the mail, I made this neat little program. The LEDs on the breadboard were used for debugging. Red LED indicates pushing the A button to jump, yellow LED indicates program is running in the main loop, and green LED was just to signify the end of the program.

This receiver will be modified before the final product, but it's a good start for now. Let's delve into the wonderful world of wireless wonders.

Preparing to Test the Wireless Communications


Now it's time to try out your dongles (heh). The two devices I bought are very easy to interface with, especially with the VirtualWire.h library for Arduino that exists for many such devices. You'll need to download and install this library to the Arduino IDE.

For this step, you'll either need two Arduinos, or you could use an ATMega328 processor on a breadboard. I chose this path, since I only have an Uno at my disposal. But how do you use an ATMega on a breadboard, I hear you ask. Luckily, I have an answer for you in the form of a schematic.

No way it's that easy!
That's all you need. Just connect your 5V and GND wires to a power source (I use the power pins on the Arduino board while prototyping). R1 holds the RESET pin high to 5V - this will keep the program running. X1 is a crystal oscillator, which drives the clock signal to the processor - I used a 16MHz crystal, which is standard for the 328. The crystal also needs two 22pF (or whatever you can get closest) capacitors for stabilization. The LED is just a power indicator.

AREF is the reference voltage used for scaling the analog inputs, and AVCC is used for the analog pin power. Since we won't be using these pins, just tie them to VCC.

Note that the pin numbers don't correspond to the pin names - for example, D0 (digital pin 0, or the RX pin) is pin 2. D7 is pin 13. In the future, be sure to connect to the correct pins.

But how do you put this code onto your ATMega without an Arduino? Simple. Just put the ATMega into the Arduino Uno and upload your program. Then, remove the chip and place it on your breadboard. You'll want to be sure that you can easily insert and remove the processor at will, should you need to reprogram anything. You'll also need to ensure you put the chip in with the correct orientation.

Most ATMega328s are preloaded with the Blink test code. Hook up an LED to D13 (pin 19) to check. If you get nothing, then program the Blink code into your ATMega and try again.

If the Blink code still isn't working, try removing the two 22pF capacitors - your breadboard might have enough internal capacitance to keep the timing accurate, and the added capacitance might screw up the oscillator. You'll need to add them back in if you plan on moving to a printed circuit board or a more permanent soldered protoboard.

Setting up the Transmitter Test Unit


I'm going to use this separated ATMega to drive the transmitter module. This is because we'll want to read what the receiver is.... receiving... by using the Serial Monitor. So here's how you'll want to wire the transmitter side.

Again, pretty simple. Make sure you don't flip the pins on the transmitter.
I've re-purposed some sample code I found online to test our setup. The code below will simply send an arbitrary number to the receiver. The receiver will be connected to our COM port to read through the serial monitor. It'll only print the number if it receives it, because the VirtualWire.h library sends a check to the receiver, so you'll know if it's actually transmitting or not. Here's the code that you'll load into the ATMega of the transmitter.

// Transmitter Test Unit Code
#include <VirtualWire.h>
byte number=170; //Arbitrary binary number (10101010)

void setup()
{
    // Initialise the IO and ISR
    vw_set_ptt_inverted(true); // Required for specific model, you probably don't need this
    vw_setup(4800); // Maximum bits per second recommended by manufacturer
}

void loop()
{   
    // Sends the binary number once every second
    digitalWrite(13, true); // Flash a light to show transmitting 
    vw_send(&number, 1);
    vw_wait_tx(); // Wait until the whole message is gone
    delay(100);
    digitalWrite(13, false);
    delay(1000);
}

So you've got your breadboard transmitter. For testing purposes, as I mentioned before, I ran the power pins off of the 5V and GND pins from the Arduino Uno board. The data will still be transmitted wirelessly, they'll just be pretty close to each other.

Setting up the Receiver Test Unit


The receiver is a bit more complicated than the transmitter. But at least we can still use the Arduino Uno, making it a bit easier to wire up. I'd suggest using the same Arduino from earlier, and keep your shift register wiring, because you'll need it later. Here's the schematic.

Not too bad. The shapes and relative positions of the pins on the receiver that you see are accurate to the actual model. The LEDs on the shift registers were added for troubleshooting later.

And here's the code you should upload.

// Receiver Test Unit Code
#include <VirtualWire.h>
byte number;

void setup()
{
    Serial.begin(9600);    
    vw_setup(4800);     // Maximum bits per second recommended by manufacturer
    vw_rx_start();       // Start the receiver PLL
    pinMode(13, OUTPUT);
}
void loop()
{
    digitalWrite(13,false);
    byte buf[VW_MAX_MESSAGE_LEN];  // sets variable for received message
    // VW_MAX_MESSAGE_LEN is equal to 80, it is a constant in VirtualWire.h
    byte buflen = VW_MAX_MESSAGE_LEN;  // sets maximum message length
    if (vw_get_message(buf, &buflen)){ // Checks to see if the message was received
    // and if it was within than the maximum length        
      digitalWrite(13, true);
      number=buf[0];
      Serial.println(number, BIN);
    }
}

Load it up, make sure power is being delivered to your transmitter. Pull open the Serial Monitor, you should be getting a steady signal of  "10101010". If you’re not receiving this byte, make sure you have the baud rate set to 9600 in the Serial Monitor, make sure everything is wired up correctly and all the appropriate LEDs are on or flashing, and that you have the transmitting ATMega on the breadboard and the receiving ATMega on the Arduino.

Here's my setup at this point. The transmitter is using the standalone breadboard with ATMega, seen on the back left. The receiver dongle is on the breadboard on the right, and the Arduino with receiver code is on the front left. It is connected via USB to my computer so that I can read the received data through the Serial Monitor.

Expanding the Transmitter Test Unit


Once you've verified that the receiver is getting the test number 10101010, it's time to expand it to transmit the NES button presses. To do this, we're going to emulate an NES with our microcontroller. As I discussed earlier, the NES sends out a signal through the latch wire, which is received by the shift register. The shift register then sends back the states of the buttons in the form of serial data at the rate sent through the clock wire.

You'll need to take your controller cable that you cut up earlier, and extract the five wires coming out of it. I soldered on new wires and taped the bare wire, and then put them into the receiver breadboard. The power line should go to the 5V rail, the ground wire should go to ground, and I put the clock on pin 8, the latch on pin 7, and the data on pin 6.

The only real addition is the NES controller wires on the left.
Here's the code you'll need to load into your ATMega (it's actually the final version of the code you'll need).

// Final Transmit Unit Code
#include <VirtualWire.h>

int clock = 8;
int latch = 7;
int data = 6;
int x;
byte nespad = 0;

void setup()
{
    // Initialise the IO and ISR
    vw_setup(4800);     // Maximum bits per second recommended by manufacturer
    pinMode(clock, OUTPUT);
    pinMode(latch, OUTPUT);
    pinMode(data, INPUT);
  
    digitalWrite(clock, LOW);
    digitalWrite(latch, LOW);

    Serial.begin(9600);
}
void loop()
{   
    digitalWrite(latch, HIGH);
    delayMicroseconds(12);
    digitalWrite(latch, LOW);
    // The Latch has now been sent, so send clock signal and read the button states
    for(x=0;x<8;x++){
      digitalWrite(clock,LOW);
      delayMicroseconds(4);
      nespad = nespad << 1; // Shift the bits of nespad to the left
      nespad = nespad + digitalRead(data); // Add the new pin state, either a 1 or 0
      digitalWrite(clock,HIGH); // Next button state is output to the data line
      delayMicroseconds(4);
    }
    digitalWrite(clock,LOW);
  
    digitalWrite(13, true); // Flash a light to show transmitting 
    vw_send(&nespad, 1);
    vw_wait_tx(); // Wait until the whole message is gone
    delay(1);
    Serial.println(nespad, BIN);
    digitalWrite(13, false);
}

Load it up, be sure your USB cable is plugged in, and open the Serial Monitor. You should be seeing a string of 1's when no buttons on the gamepad are pressed. Try pressing some buttons, and you should see some 0's start to show up. It's pretty fast, faster than the NES actually samples. This is important, as you'll want to send the data to the receiver faster than the NES would sample it so that you don't experience any missed button pushes or lag.

Expanding the Receiver Test Unit


Let's add the same level of functionality to the receiver as we did the transmitter. Now, we'll have a receiver that can extract data from the received number, and mimic the output of the controller onto the shift register of its own that will then be read by the NES. Remember those LEDs we added? This new code will allow you to see your button presses in real time, and will actually be the final version of the code to use in your receiver, just like the transmitter! Load this code up onto your receiver ATMega.

// Final Receiver Unit Code
#include <VirtualWire.h>

byte number;

int A = 9;
int B = 8;
int Select = 7;
int Start = 6;
int Up = 5;
int Down = 4;
int Left = 3;
int Right = 2;

int x;

void setup()
{
    Serial.begin(9600);    
    vw_setup(4800);     // Maximum bits per second recommended by manufacturer
    vw_rx_start();       // Start the receiver PLL running
    pinMode(13, OUTPUT);
    
    pinMode(A, OUTPUT);
    pinMode(B, OUTPUT);
    pinMode(Up, OUTPUT);
    pinMode(Down, OUTPUT);
    pinMode(Left, OUTPUT);
    pinMode(Right, OUTPUT);
    pinMode(Start, OUTPUT);
    pinMode(Select, OUTPUT);
}
void loop()
{
    digitalWrite(13,false);
byte buf[VW_MAX_MESSAGE_LEN];  // sets variable for received message
    // VW_MAX_MESSAGE_LEN is equal to 80, it is a constant in VirtualWire.h
    byte buflen = VW_MAX_MESSAGE_LEN;  // sets maximum message length
    if (vw_get_message(buf, &buflen)){ // Checks to see if the message was received
    // and if it was within than the maximum length 
    {        
      digitalWrite(13, true);
      number=buf[0];
      Serial.println(number, BIN);
      for(x=0;x<8;x++){
      // This code reads each bit in the received byte
      // Depending on the bit, the corresponding pin, which is two places
      // ahead of the number in the loop, is toggled high or low
        if (bitRead(number,x)==1){
          digitalWrite(x+2, HIGH);
        }else{
          digitalWrite(x+2, LOW);
        }
      }
    }
}

Plug 'er in to your NES through the severed controller port, and turn your NES on. It should turn your receiver on. Try turning on your transmitter as well, and push some buttons. Your LEDs on the receiver should start lighting up, and your NES should also respond. If not, double check to see if your transmit and receive LEDs are flashing on the transmitter and receiver. Also be sure to double check your wiring as well - it's a decent expansion from before.

If you want to, after you've verified that all is working properly, you can pull your circuit off of the Arduino and onto its own standalone breadboard, like the transmitter. Here's the circuit to follow.


Your final schematic for the receiver. If you'd like, you can remove the LEDs, if you are sure it works.

This is what mine looks like. For the final product, the LEDs will be removed and it'll be a lot smaller than it looks like here.

Congratulations! You have a working wireless NES controller. You can stop now if you want. You'll have ugly wire-laden breadboards lying around, but it'll work. You could at least take your circuits off of the solderless breadboards and onto more permanent fixtures.

But if you want to make something a bit nicer and more portable, as an actual wireless controller would be, let's add a rechargeable battery in the mix.

Making the Transmitter Battery Powered


For this part, I originally planned on buying a battery management IC and making circuitry around that. But as I looked further, it seems that Adafruit sells a nice little charging circuit for about the same as you would've spent on parts anyway. It also comes mounted with a USB port, and a standard connector to many rechargeable lithium ion or lithium polymer batteries (called the JST connector). I recommend the micro-USB version if you have an Android phone, as you'll likely already have a ton of those chargers lying around. If not, you can also get the mini-USB version. Both are the same price, and have the same circuitry anyway. You'll also need a battery, of course. I bought a 3.7V, 330mAh battery, since I figured that should hold a charge well long enough for many hours and the ATMega can work reliably on 3.7V. Also, it's small enough to fit comfortably in the controller. This ran for a continuous 24 hours, meaning the circuit uses about 14mA. Adafruit has many different batteries to choose from.

An important note about these rechargeable batteries - make sure the battery you buy has protection circuitry built in to it. All the ones on Adafruit's website has this. This will prevent the battery from becoming damaged from draining too quickly (such as from a short circuit) or from overcharging. Also, when picking your battery, make sure your charging circuit is correctly suited for the type of battery. The one I used, to which I provided links above, can charge 3.7V and 4.2V lithium ion/polymer batteries. Adafruit also has a great tutorial with more in depth information about batteries, if you're interested. I'd recommend it, because lithium ion batteries have been known to explode and catch on fire without a protection circuit (seriously).

The wiring is extremely simple. Solder the battery leads onto the provided JST connector wires (make sure to get the polarity correct). Then connect the BAT pin on the breakout board to the power rail on your receiver, and the GND pin to the ground of the receiver. And that's it! If your battery is already charged a bit, you should see your circuit working. If not, plug in your USB charging cable, and it should turn on.

This little baby will provide you with hours of NES gameplay. Note that's a 900mAh battery, not a 300mAh. I was impatient and just took the picture with a battery I had lying around.
What's next but to package it all up and put it in nice little cases? Nothing. That's exactly what's next. And last!

Finalizing the Packaging


What a journey, huh? We're finally at the climax of this project - making it look oh-so-sexy. For this part, I first thought about just shoving everything into the controller by itself, but it was way too much stuff to just shove into that little thing. What I decided to do was make a 3D model of the back of the controller, and simply make it a bit deeper to put all the circuitry underneath the main PCB. This way, it would still feel like a normal NES controller but just a bit thicker, which is a welcome addition for me honestly (I have huge hands).

An isometric view of the front and back.

Here's the Thingiverse entry for the controller and the receiver.

So I measured the locations of everything in the actual bottom of the controller. All those cylindrical things are for support for when you press the buttons on the gamepad. There is one that I think is used for keeping the cable in place, but since we won't be using the cable anymore, I took out that support. That's where the battery will go instead. On the bottom of the controller, I put a hole for the USB charging port. On the top near the middle, I put a square hole for the switch I bought, and two holes next to it for the charge LED and the power LED. And that's all I changed!

Annotated elegantly, just for you, in MSPaint.

After I printed it out, I took an X-Acto blade and cut off all the support material and carved out the holes so that everything fit snugly (I purposely made it so that the holes would be smaller so I could finely tune how everything fit). You'll have to drill your own hole for the switch, since there's so many different ones you could use. Keep in mind that the controller back that I have is about 1/2 inches thick, so make sure your switch can fit.

Then I made a protoboard version of the transmitter, and cut it to fit between the support pillars. I put receptacles for the ATMega chip, just in case I needed to reprogram something. You also need to desolder the wires on the existing PCB, since you won't be needing that cable. I pulled those wires down to the protoboard. Here's the final circuit you'll need to make for the controller, including the switch, the charging circuit, and the LEDs.

Not included is the NES PCB. I also added an antenna on the transmitter.
If you didn't include the capacitors on the crystal oscillator on your solderless breadboard model, make sure to include them here! Another addition you'll need to make is an antenna for the transmitter. It'll need to be about 6 inches long for the 434 MHz transmitter. Make it into a coil shape to minimize real estate (I took a wire and wrapped it around a screwdriver). This shaped antenna also seems to transmit more effectively than a straight wire. I won't get into antenna theory here, just trust me, it works better! Experiment with different shapes if you want to - that's how you learn.

Beautiful, isn't it?
After I ensured everything was working correctly, I glued down the charge board, the LEDs, and the switch. I didn't glue anything else down, just in case I needed to remove it or modify it later. I don't recommend gluing the battery, either. I used Loctite superglue that I got on Amazon.

Put the controller back together, and great! You've got a nice looking and comfortable wireless NES controller! Now we'll have to package up the receiver, and we'll finally be done. Here's what the model looks like.

Time to go out with a very boring rectangular prism.

Again, here's the Thingiverse entry for the controller and the receiver.

That's my receiver. Deal with it. I had a bunch of 5cm x 7cm protoboard lying around, so I made a nice little 5cm x 7cm box to house it. It fits fine, juts out a bit though. I figured it be easier to make with more space. Once again, here's the circuit to follow for the receiver. It's almost exactly the same. Just remove the LEDs, and add a 6 inch antenna. Unlike the previous antenna, this one should not be coiled up. You can just stuff it into the box. Keep it as straight as possible, but don't worry if you have to curve it a few times.

I'm running out of things to say on these pictures.

For the points of connection to the plug, I just soldered five wires sticking out of the top of the board. Then I stripped the wires coming out of the plug. I put the board in the box, then put the plug into the case on top of the board (you might have to cut out the hole a bit for it to fit nice and snug). These wires coming out of the plug are pretty thin, so I also soldered extra wires onto them and covered them up with electric tape. Or you could be hardcore and use heat shrink.

It's a tight fit. And it's ugly. But it works! Note the antenna shape - it's not coiled tightly.

I glued the LED to the hole, and plugged in the receiver to test it out. Verify all works well, then put the top on. I opted to glue mine together, because I like taking risks. I'd recommend maybe gluing only a few points on the receiver initially to keep the top on, but make it easy enough to open it up to fix anything you might need to fix.

When you're done, you should have a nice looking, functional, homemade wireless NES controller!

What a beautiful isometric view of such a lovely product!

Final Words


Well, it's been a long time coming, but we've finally finished our wireless controller! We learned how the controller works with shift registers, learned how to use the ATMega328 processor off the Arduino board, and learned how to interface wirelessly between processors.

Note that this controller works best when you have a clear line-of-sight from the controller to the receiver. I've had a few situations where if I sit just right with enough obstructions, communications could drop momentarily. But these were very few in number, and only when I tried really hard to screw it up. What do you expect from such inexpensive wireless modules? For the price and simplicity, this system works very nicely.

If you have any questions about this project, or you want to order these 3D prints directly from me, feel free to email me at thepoorstudenthobbyist@gmail.com. Stay tuned for more electronics tutorials!