Here is the answer. Copper_Ground_Pours_AN2010_4
There are already several articles and code examples about bootloader for AVR. And we also have some amazing bootloaders out there that can be used. But I haven’t found any article which explains how to build a bootloader step by step. And this would be the aim of this article. It would be as simple, readable and understandable as possible to teach you how to build a custom bootloader for AVR chip from scratch using codes. Please do familiarize yourself with C, a little bit inline assembler and AVR programming of course before continue reading.
This tutorial would be divided to four parts(0, 1, 2, 3). All the code examples have been compiled with Atmel Studio 6.1 on Windows 7 and tested on Atmega1284p. But they should be very easily transferred to other AVR chips.
Some tools we will use in this tutorial:
1. Atmel Studio
3. Putty as a serial console
The hardware we will use:
What is a boot loader ? A boot loader is basically a program that you put in a special part of a microcontrollers memory that allows you to program the microcontroller without external hardware.
For this How To I’ll be using the ATmega32 as the microcontroller, but by the end of this article you should know enough to easily adapt it to other AVRs.
The question you are probably asking now is “where do I get a boot loader?” The answer is you can either program your own or use someone else’s. For this example we’ll be using the excellent “Fast Tiny & Mega Uart Bootloader” from Danni at AVRFreaks. Depending on the microcontroller you are using you may need to change the TX and RX pins and ports in BOOTLOAD.asm to match those of your microcontroller. BOOTLOAD.asm is located in the BOOTLOAD folder. After you have made any necessary changes, you need to assemble it using the assembler that comes with AVR Studio. This will create a file called BOOTLOAD.hex, you will be using this file later. You also need to decide what communication protocol you want to use with your microcontroller (usb, rs232, etc.) so that you can get the appropriate IC to interface between the UART of the microcontroller and your computer. I used a ft232RL USB to UART bridge. The schematic for hooking up the ft232RL is right in the datasheet:
You don’t need the ferrite bead that is in the schematic unless you are worried about noise. In this configuration the FT232RL will be powered through USB. However, your microcontroller should have a separate power supply so that it can be turned on separately.
Programming the Boot loader in the Right Place:
To use your boot loader you have to split up the microcontroller’s flash memory into two parts: the boot loader section and the application section. The boot loader section is obviously where the boot loader is stored. The application section is where your main code is stored. By “main code” I mean whatever you have programmed your microcontroller to do Ex. Blink an L.E.D.. You have to have a separate section for the boot loader, otherwise it will get overwritten every time you upload a new “main code”.
AVRs have what are called “fuses”. Unlike mechanical fuses, these do not protect from over current, rather they are like configuration files that tell the microcontroller what clock frequency it’s supposed to run at, what voltage to shutdown at, etc.. Turns out we can use a special kind of fuse called a “Lock Bit” to lock part of the AVRs memory so that the boot loader cannot be overwritten. Besides lock bits, fuses are separated into two different categories: low fuse byte and high fuse byte, we will learn more about these later.
Understanding the Datasheet:
To find out what fuses to program, we have to look at the datasheet of our microcontroller and find information about the different fuses and lock bits. First, let’s look at all the different lock bits of an ATmega32:
As you can see, bits 7, 6, 1, and 0 should always equal 1. However, bits 5, 4, 3, and 2 are changeable. To figure out what these lock bits do, you have to find a different table in your microcontroller’s datasheet:
These tables tell you about the different bits you have to program/unprogram to get different modes. The default mode for the ATmega32 is to leave them all unprogrammed. Now lets move on to high fuse bits and low fuse bits. Here are all the fuses for the high byte:
The only fuses that are relative to boot loaders in this byte are the BOOTSZ1, BOOTSZ0 and BOOTRST fuses. Let’s take a look at table 99 and see if we can decode the meanings of these fuses:
This is pretty straight forward, all that the BOOTSZ1 and BOOTSZ0 fuses do is specify how much of the memory should be “set aside” for the boot loader. Usually if you are using someone else’s boot loader, they will specify how many words of space it needs. For the Fast Tiny & Mega Uart Bootloader we only need 256 words of space. The BOOTRST fuse is not explained very well, but you need to have this fuse programmed. It is the fuse that tells the microcontroller to boot up at the beginning of your boot loader code. Now that we have the high fuse byte figured out, let’s move on to the low fuse byte. Here is the table in the ATmega32 datasheet for that:
Obviously, these fuses have to do with selecting the correct clock frequency, start-up time, and brown-out trigger. You can pretty much leave these alone, unless you are using an external crystal, or want to select a different internal oscillator frequency.
Putting All This New Knowledge to Use:
Now that you now all about the different fuses of the ATmega32, let’s go through this information and formulate a few lines of binary that will define the different fuse settings. Before we get to that I’ll outline the process of getting the boot loader into the ATmega32:
Step1: Erase chip
Step2: Set low fuse byte
Step3: Set high fuse byte
Step4: Unlock boot loader section
Step5: Program boot loader into micro-controller
Step6: Lock the boot loader section so that it cannot be erased
Now that we know this, we can start figuring out which fuses should be programmed, and which shouldn’t. Let’s start out with the low fuse byte, this is pretty simple because, as I said before, unless you are using a different clock frequency you can leave all of these fuses as default. For purposes of thoroughness, here are those values:
CKDIV8 = 0 (default)
CKOUT = 1 (default)
SUT1 = 1 (default)
SUT0 = 0 (default)
CKSEL3 = 0 (default)
CKSEL2 = 0 (default)
CKSEL1 = 1 (default)
CKSEL0 = 0 (default)
Here are the high fuse bits:
RSTDISBL= 1 (default)
DWN = 1 (default)
SPIEN = 0 (default)
WDTON = 1 (default)
EESAVE = 1 (default)
BOOTSZ1 = 1 (changed)
BOOTSZ0 = 1 (changed)
BOOTRST = 0 (changed)
Here we see that everything is left default except for BOOTSZ1, BOOTSZ0, and BOOTRST. Having BOOTSZ1 and BOOTSZ0, unprogrammed, in accordance to table 99 selects a boot size of 256 words. Programming BOOTRST tells the microcontroller to start from the beginning of the boot loader code. Finally, let’s see how we should handle the lock bits. To unlock the boot loader section we need to program these lock bits, as per tables 95 and 96:
Bit7 = 1 (default)
Bit6 = 1 (default)
BLB12 = 1 (default)
BLB11 = 1 (default)
BLB02 = 1 (default)
BLB01 = 1 (default)
LB2 = 1 (default)
LB1 = 1 (default)
After that we need to program the boot loader into the boot loader section, more about this later. To lock the boot loader section we need to program these lock bits, again according to tables 95 and 96:
Bit7 = 1 (default)
Bit6 = 1 (default)
BLB12 = 1 (default)
BLB11 = 0 (changed)
BLB02 = 1 (default)
BLB01 = 1 (default)
LB2 = 1 (default)
LB1 = 1 (default)
This selects Application Section mode 1 which says “No restrictions for SPM or LPM accessing the Application section”. It also selects Boot Loader Section mode 2, which says “SPM in not allowed to write to the Boot Loader section”. This means that you will be able to program the application section (the part where your main code is). But you will not be able to program the boot loader section.
(Finally!) Programming the Boot Loader using AVRDUDE:
For this step you need a hardware programmer to program the bootloader into the chip, I used this one. To use the binary code we just figured out, we need to convert it to hexadecimal. These are the hexadecimal values for the previous binary:
Low Fuse Byte (01100010) = 62
High Fuse Byte (11011110) = DE
Lock bits for unlocking boot loader section (11111111) = FF
Lock bits for locking boot loader section (11101111) = EF
And finally, here are the lines for avrdude that you can use in Terminal or Command Prompt to program your microcontroller. To use this you need to be in the directory of the BOOTLOAD.hex file you created earlier.
avrdude -c ponyser -p m32 -P /dev/ttyS0 –e avrdude -c ponyser -p m32 -P /dev/ttyS0 -U lfuse:w:0xE1:m -U hfuse:w:0x9E:m avrdude -c ponyser -p m32 -P /dev/ttyS0 -U lock:w:0xFF:m avrdude -c ponyser -p m32 -P /dev/ttyS0 -D -U flash:w:BOOTLOAD.hex:i avrdude -c ponyser -p m32 -P /dev/ttyS0 -U lock:w:0xEF:m
The –P and -c options needs to be changed depending on what hardware programmer you are using, as well as –p depending on what microcontroller you are using.
Now that you know the hard way to figure out fuse values, I’ll tell you that you can also use this AVR fuse calculator, which is much easier.
How to Use the Boot Loader:
Now That you have the boot loader in the microcontroller, you can use it! First you need to change directory (cd) in command prompt or terminal to the FBOOT folder of the bootloader folders you downloaded earlier. The .hex file of your main code should also be in the FBOOT folder. Now plug in your ft232rl chip that you should have hooked up to your microcontroller. Then you need to type this in command prompt:
fboot.exe -b1200 -c1 -pfile.hex -vfile.hex
file.hex should be changed to the name of the hex file you want to program into your microcontroller. You may want to use a higher baud rate (the -b option) if you are using an external crystal of a higher frequency. Also, you may need to change c1 to something different like c2 or c3, depending on what com port you have your ft232rl plugged in to. After you have done this you should see a spinning ”/” symbol. Now turn on your microcontroller and it should start programming!
The end! I hope you enjoyed this How To.
Each general-purpose I/O port has four 32-bit configuration registers
two 32-bit data registers
a 32-bit set/reset register
a 32-bit locking register
two 32-bit alternate function selection register
Where to get stuff
I get a lot of questions about where I buy things. So I decided to post some hints.
Note that since I am located in the US, the list is biased towards US suppliers. Apologies to the rest of the world…
By no means is this intended to be an exhaustive links page – I hate those. What I list here are the places that I do business with, and have had positive experiences with. I list mainly sources other than places that specialize in DIY audio, mostly because if you’re reading this, you probably already know about them. That said, I list a few of these that I do business with.
Commercial parts distis
Hardware, wire, mechanical parts
Specialty tube audio vendors
There was a time, not that long ago, that you couldn’t go online and order parts from main-line electronics component distributors. They didn’t take credit cards, either. So you had to be a “wholesale” customer, and set up a credit account. That made it very difficult for hobbyists to get parts. Thankfully that is no longer true. So this list includes distributors that, although they make their money selling hundreds or thousands of parts to commercial enterprises, will also sell you one or two ICs (for a price, of course). These places are the ones to go to for resistors, capacitors, semiconductors, connectors… basically anything except designer audiophile parts and tube-specific parts.
Here are the ones I use:
Allied Electronics – www.alliedelec.com
You have to admire a distributor that pre-dates the invention of the transistor. Allied has been selling parts since the early days of radio. Now, they are a full-line disti that sells a broad variety of passive, active, electromechanical, and test products. They even have a few tube-specific power transformers, as well as Hammond and Triad transformers and chokes. They ship fast, usually from Fort Worth, Texas. I often buy Triad chokes and things like switches from Allied.
Mouser Electronics – www.mouser.com
Most DIY folks know Mouser. They issue a big thick catalog, and carry a wide variety of parts. I use Mouser more often than all the others, partly because they are nearby (in Texas), and I can place an order after dinner and get it the next day, and only pay for UPS ground shipping (there are some good things about living in Texas). I tend to specify Mouser (and Digi-Key, below) in BOMs because they are the most familiar and hobbyist-friendly distis – they will ship you a single resistor if you want, and don’t charge an outrageous fee for small orders. Note that Mouser carries lots of parts that may not be in the online or print catalog – for example, they have Alps RK27 audio pots for less money than the specialty places! If in doubt, search for a partial part number. Mouser also runs some sample services for semi manufactures, including Fairchild, so they stock their lines pretty well. I tend to specify Fairchild diodes and transistors because of this (and they also tend to be inexpensive).
Digi-Key – www.digikey.com
Almost everybody knows Digi-Key as well. I remember when they started, in the early 70′s, selling a ham radio keyer kit (hence the name). I guess they figured out that they can make more money selling parts. A model of efficiency, I’ve gotten ship notices 10 minutes after placing an order! DK, like Mouser, carries a broad variety of parts. They also run several semiconductor companies sample services, so they keep a pretty broad inventory of parts from companies like TI. Between Digi-Key and Mouser you can find almost everything you need…
Newark – www.newark.com
Like Allied above, Newark is an old company. They also carry similar items to Allied. One benefit is that Newark is part of Farnell, a worldwide distributor, and has arrangements for bulk shipping of order items from Europe to the US for a reasonable fee. I’ve gotten parts that are of European origin shipped in for less than I could have purchased directly from Europe.
Master Distributors – www.masterdistributors.com
I just started using this company, primarily because they carry an in-depth stock of electromechanical parts (relays, switches, and connectors). They sell online and don’t seem to have issues with small orders.
Arrow Electronics – www.arrownac.com
Arrow is one of the large commercial active and passive distributors. They’re not cheap, and charge a lot to ship parts. Why would I list them? Because they will sell small quantities of parts online, especially semiconductors, that you cannot find anywhere else. Definitely not my fist choice – try Mouser and Digi-Key first – but you can get some pretty obscure parts from Arrow. Their line card reads like a “who’s who” of electronic component suppliers.
I like to design PC boards. As much as the audiophile purists insist that point-to-point wiring (using some exotic silk-covered monocrystaline silver wire produced by Tibetan monks) is the only path to sonic nirvana, I think a PCB works just fine, has more repeatable results, and much easier to assemble (especially for the less experienced builder). The down side of PCB’s include the fact you have to design them (so need some software – see my CAD page) and that they are expensive to make in small quantity.
Since I’ve done board-level design for twenty-some years, I really prefer that my PCBs are professional quality – meaning plated holes, silkscreen and soldermask. So I only use “real” commercial board houses. Yes, I have to pay about $100 minimum for a lot of boards.
Here is where I go:
Advanced circuits is a domestic supplier (Denver) of both proto and production PCBs, though they tend towards prototype quantities. www.33each.com is also advanced circuits – they started a “$33 each” program for double-sided PCBs a while back (but there is a minimum 4 piece quantity). Advanced circuits is fast and reasonably priced for 2-layer PCBs. If I only need a couple of boards I will either use them or PCB Fab Express (below). Also check out their free DFM (Design For Manufacturability) service – you can submit your Gerber files online and they will run a free design rules check. You can do this even of you don’t buy your PCBs from them - www.freedfm.com.
PCB Fab Express – www.pcbfabexpress.com
Similar to Advanced Circuits, another choice when you want just a few PCBs. Expect around $100 for a handful of boards. PCB Fab Express charges are based on PCB size, so I usually order small boards here, and bigger ones at Advanced Circuits. Both have free online quote systems so you can compare them.
Sierra Proto Express – www.protoexpress.com
In the past I’ve found Sierra to be the least expensive supplier of small quantities of multilayer boards. See their “no-touch” service. Note that they don’t do any design checking, they just run your job, so use the free DFM (above) first!
PCB Cart – www.pcbcart.com
PCB Cart is a direct-from-China PCB prototype PCB manufacturer. By far the cheapest option if you need more than a couple of PCBs. Fast considering they are in China – 8 day turn plus two days shipping, for a total of 10 days (they include weekends too). You do pay a small tooling fee and of course shipping, but the total for ~5 pcs. 2-layer PCBs usually comes out to just over $100, and you can get 20 pcs. for not much more. I highly recommend them, as I’ve built many boards with them and they have never missed a delivery or screwed up a job.
Good hardware stores are becoming hard to find, thanks to Home Depot and the likes. There are still a few good local ones around… McGuckin in Boulder (www.mcguckin.com), and Winks (www.winkshardware.com) in Portland come to mind. If you’re lucky you have one near you. If not, thankfully there are companies that have turned to the Internet that can supply everything you need.
McMaster-Carr – www.mcmaster.com
My favorite “hardware store”. This is where I buy almost all of my fasteners (screws and nuts and the likes), as well as specialty materials (like Teflon stock), adhesives, shaft couplers, etc. They also carry lots of maintenance items, from janitorial supply to replacement motors for your conveyor belt system, as well as tools. McMaster has a good website that’s pretty easy to search, everything seems to be in stock, they don’t mind small orders, and they ship the same day (though parts may arrive from multiple warehouses in multiple packages).
Weico Wire – www.weicowire.com
One of the few places you can get mil-spec solid-conductor, silver-plated, Teflon-insulated hookup wire. They sell it in 100 foot (or 1000 foot) spools, direct from their web site. Unless you feel the need for that exotic silk-covered monocrystaline silver wire produced by Tibetan monks, this is your best bet to do point-to-point wiring. Weico also sells magnet wire and other wire and cable.
Online Metals – www.onlinemetals.com
Online Metals has made a business out of selling small quantity and cut-to-size metal materials online. I use them to get things like chassis plates (they cut them to size, usually much more accurately than they would lead you to believe) and aluminum angle or “T” stock. Reasonable prices, broad selection including copper, brass, aluminum, stainless, steel, and some plastics.
Front Panel Express – www.frontpanelexpress.com
If you don’t want to fabricate your own chassis parts and don’t mind spending a little money, FPE rocks! They produce absolutely beautiful custom parts from Aluminum sheet, with any holes, cutouts, and engraving you want (as long as it’s possible to do on their CNC cutter/engraver machines). They provide software to do the design. I usually design in AutoCAD, so it’s a bit of a pain to transfer (I actually place a HPGL pattern from AutoCAD into the FPE editor and manually place the holes and cutouts), but the results are worth the trouble.
I love electronics surplus stores. Unfortunately they are disappearing left and right. If you’re fortunate enough to have a good one nearby, buy stuff from them and try to keep them in business! If not, there are a few places online that you can go. Unfortunately the nature of the surplus business does not lend itself to an Internet store model – often they only have a few pieces of each item, so it would be way too difficult to try and catalog everything and post it online. Nevertheless, a few have succeeded…
Surplus Sales of Nebraska – www.surplussales.com
The best of it’s kind online, Surplus Sales carries a lot of parts. Don’t expect to find bargains – they know what their stuff is worth! They stock lots of mil-spec transformers and inductors, tubes and tube sockets, lots of RF parts, power resistors, you name it. They sometimes have items in large quantities that they give good price breaks on. Occasionally things on the site are out of stock, but all in all they do a fantastic job managing a huge inventory in an online environment!
Halted Specialties – www.halted.com
One of the Silicon Valley classics. Some have disappeared, but Halted is still there, and they sell online as well. They tend to have lots of subassemblies and computer parts, but you can sometimes find deals on components.
Jameco – www.jameco.com
Jameco is somewhere between a surplus store and a mainline disti – they sell new parts in large quantities, but what they have seems to be surplus lots of components. That said, they have a large variety of things like semiconductors and electrolytic caps at prices considerably lower than Mouser or Digi-Key. If you’re on a budget definitely look here, you may save some money. Note that you might get brands you’ve never seen before (I bought some electrolytic caps thinking they were Nichicon – they had Nichicon part numbers – but they turned out to be from “ESC”) but so far I haven’t gotten anything that didn’t work. Great place to buy things like heatsinks and connectors, too.
There are lots of tube dealers around. I find it a little confusing because there are some dealers that run multiple web stores which all appear to be the same business. I tend to buy from the ones that have been around the longest.
Radio Electric Supply (RES) – www.vacuumtubes.net
RES is my favorite tube vendor. They have a huge inventory, good prices, and are trustworthy. They’ve been around for 35 years and carry just about every NOS tube type that exists (though of course the “unobtanium cult classics” are long gone). They carry a few Russian and Chinese tubes, mostly for ham use – don’t expect to find the latest designer 300B tube here, you’ll have to go to an audio specialist for that. Personally I love to go through the lists looking for cheap tubes that can work for audio – like the 6T10 in the “mighty midget“, available for $1.00 each! I asked how many they had in stock – 3,000 pcs! And another 4,500 12T10′s!
Antique Electronics – www.tubesandmore.com
I’ve had mixed experiences with AES. For a long time they were one of the only games in town, but they have a lot of competition now. I’ve gotten tubes from them advertised as new that were obviously used… and often get tubes that are assorted brands when I’ve asked for the same brand (maybe their inventory is getting low). Nevertheless, they can have good prices, and carry a good selection of sockets and other items (like John Atwood’s One Electron transformers and chokes, which are very good).
Tube Depot – www.tubedepot.com
A relative newcomer, I’ve ordered a limited amount from Tube Depot. No problems, though one tube I ordered was “out of stock” and took a couple of weeks to get, so maybe not everything listed is in inventory. They carry lots of current production guitar and hi-fi tubes, as well as NOS tubes.
Billington Export – www.bel-tubes.co.uk
Billington is really more of a wholesaler than a retail tube vendor – they have a steep minimum order, and their pricing on small quantities tends toward the high side. That said, they carry a great inventory and there are bargains to be had. In wholesale quantities – say, 100 tubes – ask for a price quote – you may be pleasantly surprised. Very pleasant to deal with and reputable,
These are the guys that cater to tube DIY experimenters, and hi-fi and guitar amp custom builders. I won’t try to list them all, but just include the ones that I do business with.
Parts Connexion – www.partsconnexion.com
pcX carries a broad selection of audiophile parts, including tons of expensive capacitors and resistors. I order things like high-end coupling caps and electrolytics from them (when I can justify them!), as well as DACT attenuators and TKD pots. Broad stock, seem to ship fairly fast (though it can take a while to get stiff from Canada, they usually ship FedEx).
Angela Instruments – www.angela.com
The vendor people love to hate. Steve (the proprietor) is a… I’ll be polite… a character. Like the “soup nazi” on Seinfeld. No parts for you!!! Nevertheless, I have been ordering from Angela for years, and will continue to do so, as they carry some items that are hard to find (their tube sockets are very good) and they have reasonable prices (especially on Hammond transformers). Don’t call them up and ask for advice on the best part. Don’t call them unless you know exactly what you want. Better yet, don’t call them at all – send them a fax with your exact order info and credit card number. If you do that you’ll get your parts post haste and not have any problems. If there is an issue with your order you’ll probably get a call from Susan, who is nice and pleasant to talk to.
Triode Electronics – www.triodeelectronics.com
I did a lot of business with Triode years ago, when uncle Ned ran the shop. Somebody else is running Triode now, and thankfully things seems to be just fine. Triode seems to concentrate more on Dynaco clone parts and replacement guitar amp transformers than they used to, but still maintain a decent selection of other tube-specific parts like capacitors and sockets.
Electra-Print – www.electra-print.com
Jack Elliano at Electra-Print builds custom tube audio transformers. I’ve used his iron in some commercial products I’ve done. He builds great stuff – but don’t try and tell him how to build it. He knows what he’s doing. Prices are very good for one-offs and small orders. Jack also has some designs posted that are well-recieved, and of course he can sell you the iron for them.
Sowter – www.sowter.co.uk
Sowter is a maker of audio transformers, including small pro-audio units, big tube interstage and output transformers, and power (mains) transformers. Though it can be pricey to ship iron across the Atlantic, it’s not as bad as you might expect. I very much like their MC stepup transformers and headphone output transformers, and have used their low-level input transformers with great success. Sowter also does custom work, as well as replacements for pro/vintage audio equipment. Most items, even if in their catalog, are wound to order… but the parts I’ve ordered showed up in less than 10 days, including shipping.