Вы находитесь на странице: 1из 119

Beginning Embedded

Electronics - 1
by Nate |
June 19, 2008 |
49 comments

Lecture 1 - Background and Power Supply


This is a series of lectures written for those with mild electronics background (aka
Sophomore in Electrical and Computer Engineering) to learn about the wild world of
Embedded Electronics. I assume only that you know what electricity is and that
you've touched an electrical component. Everything else is spelled out as much as
possible. There is quite a lot here so take your time! It is also my intention to get
book-hardened EE's students to put down the calculator and to plug in an LED.
Remember, if it smokes, at least you learned what not to do next time!
You can get all the parts for this lecture here.
Sorry for the confusion. When these tutorials were written and photographed, we
used the ATmega8. We now carry the newer ATmega328. You will find all
ATmega328 information in the following pages, but the pictures will show an
ATmega8.
What's a Microcontroller?
You may know what an OR gate is. An OR gate is a logic gate that takes two inputs
and controls an output. You may have played with these types of gates, even
possibly a DIP packaged OR gate with 4 OR gates built into it. This DIP package
required a power pin and a ground pin. Electricity flowed through the IC and allowed
it to operate. You may not be sure how the IC was built, but you understand that if
you change the inputs, the output changes. You can do this by tying the inputs to
either power (also known as VCC) or ground (GND). You probably played with one
of the DIP ICs in a breadboard. If any of this is completely alien to you, don't fret!
We'll try to ease you into it.
A microcontroller is the same as an OR gate. You have some inputs, you have
outputs. The crazy thing is that a micro runs code. Machine code to be specific. For
instance, with a little bit of work, you can monitor the input of two pins A and B. And
based on those inputs, you can control an output pin C. So to replicate an OR gate:
if (A == 1 || B == 1)
{
C = 1;
}
else
{
C = 0;
{
It's C code! You can code up all sorts of different applications, compile code, load it
onto a micro, power the micro, and the code runs. Very simple! Microcontrollers are
used in all the electronics you take for granted such as your microwave, TV remote,
cell phone, mouse, printer, there's over 150 microcontrollers embedded into new
cars! There's one waiting for you to depress the brakes (BRAKES == 1) and for the
tires to lock up (LOCK_UP == 1). When this happens, the micro releases the brakes,
and you have ABS (anti-lock brake system).
In the old days, microcontrollers were OTP or one-time-programmable meaning you
could only program the micro once, test the code, and if your code didn't work, you
threw it out and tried again. Now micros are 'flash' based meaning they have flash
memory built inside that allows their code to be written and rewritten thousands of
times. I've been programming micros for years and always burn out the
microcontroller far before I hit the limit of flash programming cycles.
Flash micros are different than computers and RAM. Computers require tons of
power and components to get up and running. Computers run HOT. Computers take
forever and a day to boot. Micros are on and running code within milliseconds and if
they're warm enough you can feel heat coming off of them, something is very
wrong and you've probably blown the micro. Oh - and micros cost about $2.
Now back to that OR gate IC. It had a bunch of pins, all dedicated to being either
inputs or outputs of the various built-in OR gates (4 gates in one package = 8
inputs, 4 outputs, 2 power/gnd pins). 14 pins of fun. Now with a micro, the most
basic pin function is GPIO - general purpose input/output. These GPIO pins can be
configured as an input or an output. Very cool. Each input pin can be monitored and
acted upon. Example:
if (PORTC.2 == 1)
then do something...
Each output pin can be pushed high or low. Example:
while(1)
{
RB3 = 1;
delay_ms(1000);
RB3 = 0;
delay_ms(1000);

}
Guess what that code does? It toggles a pin high/low every 2 seconds. Fancy right?
This is the 'Hello World' of the microcontroller world. It seems trivial, but by god
when you've been trying to get a micro up and running after 5 hours of tearing your
hair out and you see that LED blinking for the first time, it's just glorious!
What types of microcontrollers are there and how do I get one blinking?
Here's a very shallow breakdown of the micros in my world:
• PIC - This is the classic micro from Microchip. Very simple, very proven, but it
lacks many of the features that other mfg's are building into their chips. This is
a big deal for me. I was a die-hard PIC person for years and I've started to see
the limits of PICs and the benefits of other micros!
• AVR - This is basically a direct competitor of PICs. They do everything a PIC
does, but in my new opinion, better, faster, cheaper, and simpler.
• MSP - These are very good micros by Texas Instruments (TI), not as beefy as
AVR or PICs. However they truly excel at low-power applications. More on this
later, but imagine running a complete system on one AA battery for 5 years.
This is in the realm of nano-amp current consumption. Crazy!
• ARM - Why are all these three letters? I don't know actually... ARMs are the
new kids on the block and they are huge. Very powerful, very low-cost, they
are taking over the world but can be really intimidating if you've never played
with a micro before.
• 8051 - The '8051 core' was the de facto standard in 8-bit (and 4-bit!)
microcontrollers. Developed by Intel in the 1980s, it still seems to be the
instruction set they love to teach you in college. They are based on archaic,
but field proven instruction sets. Very old tech in my humble opinion, but these
ICs have been significantly improved over the years (now Flash based, ADC,
SPI, etc.).
• 68HC08/11 - Another very common instruction set developed by Motorola.
Extremely popular, and a micro commonly taught at university, it's the
microcontroller I love to hate. These original micros often lack on-board RAM
and flash based memory.
Google any of these for more info. I have chosen the ATmega168 as the learning IC
of choice. Why?
• 20 MIPs (million instructions per second!) is powerful enough to do some
really cool projects
• It's cheap! $2.13 currently
• It's got all the goodies under the hood (UART, SPI, I2C, ADC, internal osc,
PWM, kitchen sink, etc)
• 16K of program memory is enough for almost any beginner project
• The tools are free! (C compilers for many of the other micros cost a lot of
money)
• The programming and debugging tools are low cost ($20 will get you started)
With a little work and probably $40 worth of parts, you too can get an LED blinking.
As with any new hobby (also known as a drug addiction), the extra cost of 'goodies'
can grow very quickly.
You want to play microcontrollers today?
With any IC, you need to power the thing. There are two power connections on basic
micros : VCC and GND. What the heck is VCC? This is the label for the positive
voltage. Don't worry, after a few days of this, seeing 'VCC' will become very normal.
GND is short for ground. All electrical current needs a way to flow back to ground.
This can be called 'common' but is often just labeled GND.
There are thousands of different micros out there, but 5V (five volts) is the typical
VCC. 3.3V is also typical but you'll also see 2.8V and 1.8V VCCs on more exotic
micros. For now, just worry about 5V and GND.
Where do I find this 5V?
You can get all the parts for this lecture here.
You need to hook up 5V and GND to your micro. Your house outlet runs at 110V AC
(or 220V for many countries). AC = alternating current and is very bad for 5V DC
(direct current) micros. So you'll need to convert the 110V AC from your outlet to a
useable 5V DC.
Quick note: If you reverse the connection on your micro - bad things happen.
Always make sure your 5V power supply is connected to the VCC pins and GND to
GND. If you reverse this and connect 5V to GND on the micro and GND to VCC on
the micro, things won't explode, probably no smoke, things will probably heat up
like crazy, and you'll probably damage your $2 micro. You probably will. I did. Many
times. Try not to do it.
Ok! You need 5V. Time to build a simple voltage regulator circuit!
You can buy something called a 'wall wart'. Don't ask me why they call it that, ask
google. A wall wart takes a higher voltage and converts it to a lower voltage. DO
NOT assume a wall wart labeled '5V' will output 5V. This is a major misconception - I
know, I know, faulty advertising. Just hook up your multimeter to the barrel plug and
see what voltage you read. Probably more like 8 or 9V. This will kill your micro so
keep reading! For a more detailed explanation check out the Unregulated Power
Supply Tutorial.
Let's assume you are using a wall wart with an output of something nice like 9V.
Dandy. Unfortunately this 9V output is rather noisy - meaning there is a lot of ripple.
Ok what does ripple mean? You want a DC voltage meaning you want a solid
voltage (the opposite of alternating). A wall wart uses some cheap tricks to get
110V AC down to 9V DC. So the DC signal coming out of the wall wart tends to
alternate 100-500mV. Instead of a solid 9VDC, you see a signal that rises and falls
between 8.5 and 9.5 volts. This 'ripple' can cause havoc with your system, and 9V is
too high (we need 5V!) so we need to pass 110V through this wall wart, and send
the 9V through a regulator to get down to a clean 5V DC signal. If this all sounds
scary - don't worry. After you get your 5V power system built, you'll wonder why
you were scared in the first place (it's simple, I swear).
The most common regulator is called the LM7805. Why? I dunno. I've never actually
touched a component with LM7805 stamped on the outside. There's always other
letters stamped on the outside like 'LM7805' or 'LV78X05' or some such crazyiness.
Just know that there are many many manufacturers out there and they are all
producing the same basic part, with small tweaks to each one. What you need is
one of these generic parts that is designated as a '5V linear regulator'. If you're
playing in a breadboard, you'll also want it in the TO-92 or TO-220 package. More
about packages in a later lecture, just go with it for the moment.
You've got your regulator in hand, you've got the wall wart. Time to connect them
up.

Here you can see the 'pin-out' of the LM7805. Say 'IGO' in your head and commit
this to memory (input, ground, output). You'll probably hook up a lot of these. When
in doubt, always check the datasheet before hooking up a new part - or else be
close to the on/off switch! Input is the input voltage of anything greater than about
7V. GND is ground. Output is the 5V output pin. Your wall wart should have two
wires. One is 9V, the other is GND. All grounds need to be connected together for
current to flow across the system. One more time - connect all grounds. This is the
#2 reason why novii can't get a system to work. For our breadboard, we will be
inputting 9V (or whatever transformer you've got up to about 15V) and outputting
0V (GND) and 5V to our breadboard rails.

We are going to go through a bunch of iterations of the power supply, adding parts
as we go. Shown above, we have a basic regulator configuration. 9V in, we should
see a rough 5V on the output.
Schematic note: The two ground pins are not shown connected. We assume that
nets (the green wires) of the same name are connected together. Schematics can
get big and complex, so you won't see all the wires together, but in your
breadboard you need to connect all the GND pins together. In this case it's the GND
wire from your wall wart connected to the GND pin on the regulator.
Cool. But why doesn't the multimeter read 5.000V? Electronics are not that good.
The cheap-o regulators are +/-5% tolerate meaning you'll see between 5.25 and
4.75V. In practice, you should see between 5.1 and 4.9V with most run of the mill
regulators. You can of course spend many $$ and get tighter tolerances but 5.1-
4.9V will work fine for our purposes.
Now we should be worried about ripple. There is noise coming in the input pin, the
regulator tries hard, but some of that noise gets onto the output pin. Your
multimeter says 5.08V, but that's because it's averaging many readings together
and showing you only the average. Do you know someone with a oscilloscope? If so,
show them this tutorial and ask them to show you the noise on your 5V rail. With no
filtering caps, you could see as much as 200mV of noise.
Whoa - what's a filtering cap? Filtering capacitors are large bulky capacitors that
help smooth out ripple. There've been lots of analogies about capacitors so here's
another one for ya:
Capacitors act like water tanks. When your circuit pulls a bunch of water out of the
system, the capacitor helps hold the voltage up temporarily until the power system
can catch up. For example: you may live in a city with water and water pressure. If
you take a shower you affect the pressure in the municipal water system ever so
slightly. If everyone turned on their shower and flushed every toilet in the city, odds
are the water pressure would fluctuate quite a bit! A big water tank helps minimize
these pressure fluctuations. A big cap helps minimize the voltage fluctuations on
your breadboard.
Is this something you can see happen? Unfortunately not really. You can probably
run your system without filtering caps, but it's not good engineering practice. Give it
a whirl without caps! But when things don't work, you'll wonder if it's the caps, or
your code, or your timing, or maybe you blew out the sensor. Too many unknowns
will make you crazy. My recommendation: just use a couple basic caps...

100uF (one-hundred micro farad) on the input and 10uF on the output. You will use
a lot of 100uF and 10uF around power systems and you will eat 0.1uF (point one
micro farad) caps like candy around micros. These two caps should smooth the
input into the regulator and will smooth the output nicely.
Capacitors cannot deliver their stored energy instantaneously. Larger caps (1ouF
and 100uF) store more energy, but they react more slowly. The smaller the
capacitor, the faster it can deliver its stored energy. If you have a large power
outage (power dips for 10-100ms), a big cap (100uF to 1000uF) will help 'hold up'
the falling voltage. A smaller cap (0.1uF) will help suppress higher frequency noise
and shorter power dips (noise in the 1us to 100us range). Therefore, 0.1uF caps are
located near the microcontroller to help with short bursts, where 100uF and 10uF
caps are used on the power rails.
Now you see the schematic symbol looks a bit odd. What's with + and curved lines?
This schematic component is indicating that the 100uF and 10uF cap are polarized.
Oh jeebus, what's that? Time for a capacitor breakdown:
• Electrolytic caps: These are larger caps capable of storing 10uF to 1,000,000s
of farads. They are cheap and great for bulk capacitance. They are polarized
meaning there is a positive pin and a negative pin.
The cap has a minus '-' sign on the cover indicating that pin needs to go to GND.
• Ceramic caps: These are the cheapest and most common cap you'll play with
on a breadboard. They are NOT polarized so you can stick em in the
breadboard any way you want. Ceramic caps cannot handle as large of
capacitance as electrolytics so you'll need both on your breadboard system.
• There are many more different kinds of capacitors but for the sake of your
head exploding, we won't cover them here.
Okay - now you need to work through some logic here. You know the positive part
of the 100uF cap needs to be connected to the input pin, but only the negative pin
is marked. Yes it's confusing - but you'll get used to it. Negative marked pin goes to
ground, the other goes to the input pin.
What happens if you get them switched? Well here's where things may go poof.
From the left: Bad, good, ugly
This is what happens when you over-voltage or reverse voltage a polarized
capacitor. The middle cap is normal. The cap on the left, you can see the top is
slightly raised up. This is what happens when the electrolyte inside expands. And
the cap on the right shows us what happens when this pressure is so great, it busts
through the metal top. Notice the '+' imprinted into the tops of these caps? That
imprint is there so that if the pressure does build up, the cap will fail like the unit on
the right - rather than blowing the top half of the cap across the room.
This picture was taken from the inside of an old Gateway computer (circa 1999).
Gateway had used some 'marginal' 1000uF/16V capacitors. The /16V means they
are rated to 16V. A 16V rating means they can withstand voltages up to 16V but no
more. These caps were sitting on the 12V rail to smooth out the ripple but obviously
they where failing. Gateway was trying to save $0.50 by using a capacitor that was
too close to the maximum. Manufacturing is not perfect! With any production run,
the population of capacitors and their tolerance looks like a bell curve. The majority
of the 16V rated caps can withstand 16V. Some can 18V, even 22V! But the
tolerance bell curve goes both ways; a small number of the capacitors rated at 16V
will fail at 10V, some at 8V. You get a big enough ripple on the 12V line and you
could pop the 16V rated cap. This is why most engineers talk of 'de-rating'
capacitors. If you have a 5V rail, you do not stick a 5V rated cap on the rail! A good
rule of thumb is to de-rate any capacitor by 50%. So a 12V cap is good to be used
on 6V rail, 24V cap on a 12V rail, etc.
Guess what happens when an electrolytic cap fails like the ones above? They quit
working. In most cases, they 'fail safe' meaning they won't work as a capacitor
anymore but they won't short to ground. The real fun begins when the failure is so
bad that the internals fuse together and you get a short to ground - then you can
have some fun melt downs! In the case of this computer, the motherboard had all
sorts of bad software failures because the power supply had too much ripple! The
big filtering caps on the power supply had failed so the 12V was all over the place.
Similar failures can happen if you reverse the polarization of the cap. If the voltage
is low (less than around 25V) the cap will probably just be damaged a bit. If you've
got a vacuum bell sitting around and you want to really cause some damage, ask a
trained professional to hook up 10V cap backwards to 10,000V. It should
instantaneously blow up like a pop corn kernel.
For your power supply filtering caps, I recommend using a 25V rated 100uF cap
(100uF/25V) on the input and a 10uF/10V cap on the output. Engineers will tell you
to 'derate' the cap by 50% meaning if the label says 100V don't trust it past 50V.
This is generally good practice. Following this idea, our 100uF/25V is good for inputs
up to about 12.5V before we should worry that we may pop the electrolytes. Again,
not mandatory, just don't expect a 5V rated cap to withstand a 9V input.
Back to our power supply! Don't worry about blowing things up just yet, you should
be at low enough voltages you won't do any harm. Again, if things heat
up/smoke/spark, just unplug or turn off the system. Speaking of turning things off -
we need a power switch!

This will allow you to turn on/off the system. Handy. It can get really annoying
pulling and inserting the power wires to power/kill your system.
Inside the small black enclosure, is a switch. The switch has three pins. It looks like
a see-saw inside. The center pin is always connected to the middle of the see-saw
and as you slide the switch back and forth, the see-saw rocks up and down. Slide
the switch forward and the see-saw shorts from the center pin to the forward pin.
Slide the switch back and the see-saw disconnects from the forward pin and shorts
to the rear pin. We recommend you connect power to the center pin of the switch.
When you slide the switch forward, power will short to an unconnected pin and do
nothing (no power to your system). Slide the switch back and the center power pin
will short to the wire running into your regulator, delivering power to your system
(power on!).
Remember all the warning about reversing VCC and GND and how that is bad? Well
if you connect your power supply backwards, that's bad. So let's protect ourselves!
That's a diode (marked D1). A diode lets current flow in one direction (in the
direction of the arrow) and it blocks current from flowing in the opposite direction.
This will allow 9V to flow in the right direction, and if you accidentally hook your
power supply up the wrong way, it will block current from flowing backwards and
damaging your system. Is it overkill? Pretty close. But we always design them into
our development boards because we don't know what type of power supply you
knuckleheads (also known as our paying customers) will plug on to our boards. If
you plug the wrong type of wall wart onto a board, we want to protect you from
yourself.
There are some down sides to a protection diode:
• All diodes have a voltage drop, meaning 9V on one side will drop to about
8.5V on the other. So your 9V wall wart just became 8.5V.
• Diodes have a current rating. If you try to suck 1A (1 amp) through a 0.1A
(one hundred mili-amp) rated diode, the diode will quickly heat up and fail. For
reverse protection, we recommend a 1A 1N4001 diode. These are dirt cheap
and very common.
Note that diodes are polarized. They have a direction that you need to pay attention
to. Many diodes have a band indicating the cathode. What's a cathode? Go google.
All you really need to know is that the line on the schematic part is the same as the
line on the diode. If you can't remember which is which, remember 'arrow is for
anode'. Cheesy, yes.
So if you want to install this 'reverse protection diode', the 9V from your wall wart
goes into the end of the diode without the band (the anode). The banded end
(cathode) goes into your switch. Your switch then goes into the input. Throw the
switch and you should see 5V on the output using your multimeter. Nifty. But I am
tired of using my multimeter each time to check the 5V output. There must be a
better way! Time to wire in the power LED.
Light emitting diodes (LEDs) are bits of silicon that light up when current flows
through them. Go google for the science. As a general rule of thumb, LEDs can have
20mA max current flowing through them before they begin to fail.
So if you hooked up your LED like in the above schematic, it would light up very
bright for a split second and then burn out. That's cause the LED is a diode and the
current will flow from the anode (arrow) to the cathode (line) to ground -
uncontrolled! The silicon will flow current at something like 1 amp for a split second
and burn up. To limit this current flow to 20mA, we need Ohm's law. Yea, the book
worms in the room suddenly perked up:
V = IR (this is Ohm's law)
If we have 5V, and we only want 20mA flowing through the LED:
5V = 0.02 * R
R = 250 Ohm
Now this is not completely true because the LED has a forward voltage drop, but
don't worry too much about that. Hooking up LEDs is very common with micros. All
you need to remember is that you're going to need to limit the current. The most
basic way to do this is with a resistor. 220 Ohms will work (LED will be brighter),
330Ohm is also good (LED a bit dimmer), 1K (1000) will work as well. 220, 330, and
1K are more common resistor values.
I highly recommend you get your hands dirty. Hook up an LED to a 1k resistor, then
a 330, then a 220, 100, 50, then finally blow the thing up by hooking it with no
resistor. That was fun right? Good. You had a back-up right? Once the bit of silicon
inside the LED is burned out, it is no good and the LED can be thrown away.

Eagle schematic / PDF


Our final power supply circuit. It seems like a lot of work, but once you set this up
on your breadboard, you might never take it off. This is the basis for all things
micro. The input voltage may change, the output voltage may change (to 3.3V for
example), but the basics are all there. Flip the switch and you should have a nice 5V
rail and an LED letting you know that everything is a-ok. If the LED does not light
up, that means that something else on the 5V rail is sucking so much current that
the LED cannot light up. This is a very strong indicator something is wrong. If you
turn on your system and the Power LED does not turn on, immediately
turn off the system and check your wiring.
You may be wondering if the resistor/LED order matters. It does not. The resistor
can come first and then the LED or as shown. Either configuration will correctly limit
current through the LED.
If you think you may have blown up your LED then your LED will never turn on. You
may want to check your power system with a multimeter instead.
Good, you've made it this far. Now for some technical info about ripple/noise and
why it's bad.
If you've got major ripple on your power rail, say 500mV or more, this can cause
your micro to latchup. This means that it was running fine a 4.8V, but at 4.3V it's
not happy and will go into an unknown state. When the rail returns to 4.8V (because
the ripple is bouncing the rail up and down), the micro goes from unknown to
possibly latching up or freezing up. This is pretty rare these days because the chip
manufacturers have done a good job of internally protecting against this, but in
general, ripple is bad.
Say you've got 500mV of ripple on your system and you're doing analog to digital
conversions off of a temperature sensor. The temp sensor has an output pin that
will output an analog voltage that will vary 100mV for every 1 degree C. So at 25
degrees C (room temperature) the sensor will output 2500mV or 2.5V. If your micro
is doing analog-to-digital conversions on this signal, it has to compare what it
'thinks' is a solid power rail of 5V against this changing analog signal from the
temperature sensor. Well if your 5V 'solid' rail has 500mV of ripple, the micro
doesn't know this, and will report a regular 2.5V reading as varying between ~3.0V
(3000mV = 30C) and ~2.0V (2000mV = 20C). This is wildly bad. You need a good
'clean' power rail if you are doing anything with analog signals.

Now some notes and photos on breadboards:


Go read Tom Igoe's breakdown of the breadboard. In short, the power rails (the
red/blue rows) are connected internally. The columns within the main area of the
board are interconnected. So you can insert a wire into one hole and it will be
electrically connected to a neighboring hole (vertical connections for the numbered
columns, and horizontal connections for the blue/red power rails).
Historically, the blue rail or the horizontal row of holes next to the blue line is 'GND'
or ground. You can connect all the ground pins of all your components to this rail.
Similarly, the red rail is for VCC. In our case, this is 5 volts.
Power jack, switch, LM7805, power LED
Here you can see power from the barrel jack being delivered to the slide switch, and
then to the input pin of the v-reg. When the switch is thrown to the on position, the
yellow LED turns on.
I cheated a bit.
Do you see that odd thing in the upper right corner of the picture? That is my wall
wart plugged into a DC barrel jack. Most wall warts are terminated with a round
connector called a 'barrel'. The outside metal sheath is ground, and the inside metal
is 9V. The two metal contacts are isolated. The DC barrel jack accepts this wall wart
barrel (wall wart barrel slides into the jack with some friction to hold it in place). I
don't like hacking the ends off power supplies and inserting the bare wires into a
breadboard. Having energized bare wires bothers me. If the wires get pulled out of
the breadboard because you kicked out the power cord, you'll have some tense
moments until you get the power brick unplugged. So I soldered some short leads to
the barrel jack so that I can plug/unplug my power cable from the breadboard.
Easier to transport.
See the orange wire at the end of the barrel jack? That pin inside the DC barrel jack
connects to the center of the wall wart barrel. The center of our wall wart barrel
connectors are '+' or 'hot' or '9V', whatever you want to call it. So the end of the DC
barrel jack is soldered to an orange wiring meaning it is '+'. This orange wire is then
connected to the center pin of the power switch.
All ground connections are connected together. You will see a small black wire
underneath the DC barrel jack. This is the pin that connects to the outside sheath of
the wall wart barrel. This is the ground connection on the wall wart. This small black
wire connects the ground of the wall wart to the ground on the breadboard.
I did not install a reverse protection diode. I *only* use center positive power
supplies so I know I'm safe. If you do anything similar, check your wall wart carefully
with a multimeter before doing any testing.
Note: Our breadboard will have 5V and 0V rails. The blue rail is GND (considered
0V). Red is VCC (or called 5V).
Note on LEDs: LEDs are a polar device meaning you've got to hook them up in the
correct direction. Light emitting diodes (LED) have a cathode and an anode. How do
you tell the difference? Imagine the schematic element:

An LED
Do you see the arrow? Do you see the flat line? A is for arrow. A is for anode. The
physical LED will have a flat side corresponding to the flat line (the cathode) in the
schematic picture. And there you go! When connecting an LED, you know that
diodes only pass current in one direction (from anode to cathode - in the direction of
the arrow!) so the flat side of the LED needs to be connected to ground some how
(usually through a resistor first) and the other side (remember arrow) is the anode
and needs to be connected to power for current to flow. If you hook it up backwards,
it won't turn on, and you might damage the LED but probably not. Just verify that
you've got 5V on the correct rail and then flip your LED around if need be.

Power supply with 10uF and 100uF caps in place


Note the polarization of the caps. The larger 100uF cap is directly connected to the
Input and GND pins of the v-reg. The '-' sign is connected to the ground pin. The
smaller 10uF is connected on the power rails. The '-' sign (in white) is connected to
ground, the opposite leg is inserted into the '+' rail. The power LED is on!
Note: The center pin of the wall transformer is connected to the red wire on the
rear of the barrel jack. This short wire is then routed by another wire to the slide
switch. Do not connect this center pin/9V source to the power rail on your
breadboard!
The slide switch has three legs. The center pin is considered the 'common' pin. If
the switch is thrown to the right, there is a connection from the center pin to the
right pin. Slide it to the left and a connection to the left pin is made. When dealing
with power, we want the raw voltage (9V in our case) delivered to the center pin of
the switch. When I slide the switch to the left (as pictured above), current is allowed
to flow from the center pin to the left pin and on to the voltage regulator. When I
slide the switch to the right, the center pin is connected to the right pin (which is
not connected to anything). In this state, current does not flow anywhere and the
breadboard remains powered down. Voila! We have a power switch.

Power LED is not lighting!


This picture is key. When I initially wired up this circuit, I flipped the switch and the
power LED didn't light. That was VERY bad indicating there is a massive short
somewhere. Even the good guys screw up now and again. Whip out your trusty
multimeter and start probing in continuity mode.
Quick note: I highly recommend you purchase a multimeter with a 'continuity'
feature built in. This mode allows you to 'tone' out circuits. In this mode, if you
touch the two probes together, you should hear a tone indicating that there is a
direct connection between one probe and the other (obviously - you have them
touching!). This feature is used countless times during trouble shooting. In the
above example, by probing from one GND rail to another, I noticed that I could not
get a tone. Therefore, there was a break in the circuit somewhere which lead me to
realize the break is in the rails.
If you've got a medium sized breadboard such as the one shown above, you'll notice
something horribly odd. The various holes of the power rails are not connected!
The yellow lines show what holes are inter-connected and where the breaks occur
There is a reason why the power rails are broken. If you have a breadboard with
multiple and different power rails, you cannot share them on the same row of holes.
So modern breadboards break the rails up so that you can isolate different parts of
your circuit. For example, if you were building a really complex design you may
need to have 5V and 3.3V on the same board. Because the rails are isolated from
each other, you could just use various strips around your breadboard to be designed
at 5V, 2.8V, etc. For the purposes of this tutorial (and for almost all breadboarding)
we assume that you'll only be using 5V and GND. Therefore, we need to use short
jumper wires to interconnect all the isolated rails, forming one continuous 5V rail
and one continuous GND rail.
When I first wired up my power supply, I only had the long black/red jumpers on the
right side of the board, but didn't have the small jumpers in the middle of the rails.
Without these middle jumpers, only the bottom left rails (next to the 5V supply)
actually have 5V and GND. Since the LED is connected to the upper left power and
ground rails, the LED never got power! Therefore, you will probably need to use
very short jumper wires (and some long ones on the end) to connect all the '+' rails
(5V) together and all the '-' rails (GND) together.
Some additional nit-picky notes about breadboarding:
1. You won't listen to this rule. Neither did I initially. Use a few different
colors of wire! It's really helpful to see where the power and gnd wires go if
GND is black and 5V is red. I wired 200 connections using only orange. When
things didn't work, it was hard to figure out where all the connections went.
2. Don't worry about super-tight wires, and don't use huge loops. When
cutting and stripping wire for breadboard connections, don't spend exorbitant
amounts of time making the wire perfectly flat. It doesn't matter. That said,
don't use 9" of wire when 1" will do. Make it clean.
3. The 'making things clean' rule applies to LEDs, resistors, and crystals
as well. Clip the legs! If you've got OCD like I do, it can be hard to permanently
alter a part in this way. What if I need the legs to reach further away on a
future project?! It's ok. Resistors cost $0.005 each. If in the future, you need a
resistor with full legs to reach from point A to point B, just get a new one. It's
not worth having lots of exposed legs that could bend and short to other
exposed legs.
Now with your power supply built up, turn your multimeter to voltage and check
your board voltage by probing from the Blue rail (0V or GND) and the red rail (5V or
VCC).
Note: To use a multimeter you need to use both probes. Voltage refers to a
potential. Using only one probe will get you nothing because you have to compare
something against something else. In our world, we assume ground is 0V. So touch
your black probe to any ground connection. Now you can measure the voltage on
any other pin with the red probe. In the picture below, the black probe is touching
the ground rail (0V), and the red probe is touching the 5V rail - thus we are viewing
what voltage is exposed on the red probe compared to ground. If we put both
probes on the 5V rail, the multimeter would show 0V because there is no difference
in voltage between the probes.
Guess what happens when you push the black probe against the 5V rail and the red
probe against the ground rail? The multimeter will show -5V. This is because the
multimeter assumes the black probe is touching 0V. There is still a difference of 5V
between the probes so the multimeter shows -5V.

4.98V on the 5V rail


So you don't have 5.000V. Nothing in engineering is perfect. If you're within 100mV
you're doing just fine. These cheap-o voltage regulators are cheap for a reason -
and we don't need high-precision. 4.9V to 5.1V is just fine.
Congratulations! You've built up your very first breadboard! Now leave this 5V
power supply wired in your breadboard! You are going to use it many times...
A 500mA PTC
Quick Note: PTCs are your friend! PTC = positive temperature coefficient.
Beginners will often create shorts or accidentally hook things up backwards. A PTC
(also known as a thermistor) is a device that will increase in resistance as current
flows through it. These PTCs can be designed so that at a certain current flow (let's
say 500mA), the resistance increases dramatically, thus limiting the current flow.
Basically, the PTC acts as a resettable fuse! You will want to place this device in
series, before your voltage regulator. If your circuit draws more than 500mA (if you
short power to ground for instance), the PTC will heat up and limit the current to
250mA. Once you remove the short, the current will drop back down, the PTC will
cool off and the circuit will start operating normally again. Very cool little
component that has saved many of my designs from smoking.

This is how the PTC looks in circuit. The PTC is wired in line. As the current of the
circuit flows through the PTC, it will trip if the current is too large, cutting off the
rest of the system.

Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=57>


Lecture 2 - How to Get Code Onto a
Microcontroller
You can get all the parts for this lecture here. We also highly recommend that you
get a multimeter with a 'continuity' setting. A good quality multimeter with this
setting goes for ~$60 and as high as $300 for a really spectacular one. We like our
$60 cheapo.
Sorry for the confusion. When these tutorials were written and photographed, we
used the ATmega8. We now carry the newer ATmega328. You will find all
ATmega328 information in the following pages, but the pictures will show an
ATmega8.
I'm assuming you've got your 5V supply tested and working. Next, we need to insert
the ATmega into the breadboard and connect up power and ground.

ATmega8 (works the same with ATmega168, and 328) straddling the middle row of
the breadboard
You will need to slightly bend in the legs of the DIP (dual inline package) to get the
ATmega to straddle the breadboard center. Be careful! Do not bend the pins too far
inward. The pins of the ATmega should insert into the inner two most rows on the
breadboard. I find it best to to insert one side and then slightly push the IC sideways
until the other side of pins can insert into the opposite row on the breadboard.
Confusing, I know.
Note: The 5V 'rail' is the horizontal row of holes next to the red line. You should
have a wire connecting your 5V power regulator circuit to one hole on the 5V rail.
This will energize all the holes next to the red line with 5V. This is true about the
blue line as well. All the horizontal holes next to the blue line are connected
together. One of these holes should be connected to the ground pin on your voltage
regulator, and to the ground connection of your wall wart. You can connect the VCC
pins on the ATmega328 to any holes along the 5V rail, and you connect the GND
pins on the ATmega328 to any hole along the blue GND rail.
Oh, hey! If no one ever told you, there is a really simple way to figure out where pin
1 is on an IC. The manufacturer of anything polarized (tantalum caps, electrolytic
caps, LEDs, ICs, etc) will always put some sort of marking on the device to indicate
the how the device is supposed to be oriented. For ICs, there is a small dimple on
one end of the IC. The blue arrow in the picture is pointing to this dimple. The
orange arrow points at pin 1, and the blue labels show how the pin numbers
increase.

Pin labeling on an IC
Counting from the dimple, pin 1 is on the left and increases down the left side of the
IC. The pin numbers jump to the right side row of pins and count up. See image
from the ATmega328 datasheet below.
The ATmega328 should be in the breadboard, pin 7 (VCC) and pin 20 (AVCC) should
be connected to your 5V rail and pins 8 and 22 (GND) should be connected to GND
on your bread board. If you turn your power circuit on, the ATmega328 is now
running, but it has nothing to run!
Actually this is not wholly true - there is one more connection that needs to be
made before the ATmega328 starts running code. The RESET pin on the
ATmega328 needs to be connected to VCC. You can either wire the RESET pin
directly to 5V or you can 'tie it high' by connecting the RESET pin to VCC through a
resistor. This will allow you to add a momentary reset button. What's this? The reset
line on the ATmega328 is exactly what it sounds like - it resets the micro just like
the reset works on your computer. If you look at the ATmega328 datasheet you'll
see the RESET label is written with a line above it. This is nomenclature that
indicates the reset pin is active low. What is 'active low'? The RESET pin is an input.
A low level on this pin will put the micro into reset - i.e. the pin is activated with a
low input, aka 'active low'. So unless you want your ATmega328 to stay in reset,
you'll need to pull this pin high.
Now you need a reset button. A momentary switch is a switch that is activated (or
closed) while you're touching it and open when you release the button. These are
often called 'tactile switches' because they 'click' when you depress them giving the
person pressing the button some 'tactile' feedback.
This is what the schematic part looks like. Notice pins 1 and 2 are connected
together. 3 and 4 are connected together. And when you press 'de button, it
temporarily connects 1/2+3/4 together.
Notice this button has five legs. If your button has five legs, just ignore the middle
leg - it's not connected to anything and can be clipped off.
To test this button, whip out the trusty multimeter and set it to the continuity
setting. This is the setting on nicer, mid-grade multimeters that is crucial to
troubleshooting and experimenting. Touch the probes together - you should hear a
tone indicating that there is continuity or a (nearly) zero resistance path between
the probes. Insert the button into the breadboard and probe the two pins on one
side of the button. If you picked pins 1/2 or 3/4 you should hear a tone. These pins
are permanently connected inside switch. If you picked pins 1/3 or 2/4, you won't
hear a noise - but hit the button. By hitting the button you will make an electrical
connection between all four pins - and you should hear the tone! This means you
have electrical continuity.
The schematic shows pins 1 and 2 of the reset switch connected together
(connected to ground) and pins 3/4 connected together (connected to !RESET) . In
practice, you just need the switch to work. Play with your multimeter and find two
pins that don't make noise when the button is not touched, and do make noise
when the button is depressed. Use these two pins.
The schematic shown above is what we're going for. The 10K resistor 'pulls' the
reset pin high during normal activity. By pulling the reset pin high, the ATmega328
runs normally. When you push the reset switch (S2), the reset pin sees a continuous
connection to ground. Since the resistance through the depressed switch is nearly
zero, it wins (compared to the resistance of the 10K resistor!) and the reset pin is
pulled low, RESET is activated and the ATmega328 goes into reset. Release the
button and the reset pin is pulled high again and the ATmega328 comes out of
reset. Nifty!
ATmega328 pinout
See the dimple from the ATmega328 datasheet? Looking at the top of the IC (legs
down), with the dimple to the top, pin numbers increase starting from 1 in the top
left corner. This is how every IC pin is number. However, the orientation marking
varies a bit between manufacturers and between packaging types. Look for a non-
congruent marking like a dimple, small dot, white arrow, a notched corner -
anything that makes that area of the chip different from the other parts of the chip
probably indicates pin 1. When in doubt, check the datasheet.

Reset wired next to a ATmega8 (same applies for the ATmega168, and ATmega328)
Learn how to use the the continuity setting on your multimeter. It will be vital to
troubleshooting down the road!
Each microcontroller manufacturer has a different method to get code in the flash
memory of the micro. In the past few years there has been emphasis placed on ISP
or "in system programming". ISP allows you to program the IC without having to
disconnect the microcontroller from the application. This is not trivial! History was
much more painful. Atmel has designed a relatively straight forward method that
requires the control of a few pins (6 total). Because of this simple interface, the
hardware programmer that is required to connect your computer to this ISP
interface is very straight forward (cheap!) as well.

The red stripe indicates the location of Pin 1


Remember how we identified pin1 on the IC from the dimple? Well connectors also
need polarization so that we don't reverse the orientation of the connector and fry
things. Unfortunately the way connectors are numbered is opposite that of ICs. In
the picture of the ISP connector, you see the red stripe indicating pin 1. An IC
counts sequentially down one side. Connectors on the other hand, increase pin
numbers, back and forth, as you work your way down the connector.
The programming chain looks something like this:
1. There is a free C compiler called AVR-GCC. User writes code in C and
then compiles that code into HEX files
2. AVR-GCC can be installed on the Windows platform with an easy
WinAVR install program
3. The user gets this HEX code onto an AVR via the ISP pins
4. Both a serial port programmer and a parallel port programmere have
been designed to connect the computer port to the AVR ISP pins
5. The computer runs a command line program to transfer the HEX file
from the computer, to the serial or parallel port, and out to the AVR ISP pins
6. The micro runs the machine code (*.HEX files) once powered or reset
What's a C compiler? This is a program that inputs a program written in the C
language and outputs a HEX file. We prefer to program in C because it is easier for
us than assembly and more flexible than BASIC.
What's a HEX file? This is a file that contains various hexidecimal characters. These
hex 'codes' represent machine instructions that the ATmega328 understand. This
file is what gets sent down to the programmer, and the programmer loads these
machine instructions onto the ATmega328.
Before we can get too crazy, download and install WinAVR on the computer that you
will be doing your code development on. If this link goes out of date, a google
search should take you straight to it. The windows install should be fairly straight
forward - follow all the defaults. WinAVR contains a version of the GCC compiler and
various other tools including avrdude and Programmer's Notepad. avrdude is a
simple command line program that takes a HEX file and sends it to the serial or
parallel port for programming onto an Atmel microcontroller.
Working backwards up this list, I'll provide you with an example 'Hello World' HEX
file that will prove that everything is working correctly on your micro. With any
micro controller board, the first trick is always to get an LED to blink. This is the
'Hello World' of embedded systems. Guess what blink_1MHz.hex does?
With the blink hex file in hand, you now need to get it onto the micro. You will need
to connect the AVR-PG1 (or the AVR-PG2) to the ATmega328. The easiest way to do
this is with 9 wires running from your breadboard to the 10-pin connector on the ISP
connector on the AVR-PG1/PG2.

Jamming wires into the ISP connector is not a good long-term solution but for the
sake of getting the LED to blink, it'll do. I've cut short wires and stripped both ends.
One stripped end is inserted into the end of the black programming connector, the
other end is inserted into the breadboard.
The AVR-PG2 parallel programmer wired into the ATmega328. I've also wired up two
0.1uF caps. These decoupling caps are placed near the VCC and GND pins on the
ATmega328 to help reduce noise into the IC. You may think you have a straight DC
5V but not really - these 0.1uF caps help reduce ripple on the 5V line. Yes, the
ATmega328 will probably run without them but they're good to have installed.
AVR ISP Note: You really do have to wire all 4 GND pins. You cannot wire just one
of the GND pins on the ISP connector.
Additionally we need an LED to control. This can be tied to any GPIO pin. PC0 looks
like a good spot.
The resistor/LED order does not matter - just remember (from Tutorial 1) that you
must have the resistor! The GPIO pin doesn't actually matter. blink_1MHz.hex will
toggle all the pins on all ports so you can hook the resistor to any pin. As you add
more peripheral hardware you will want to dedicate some pins for alternate use
(such as TX and RX pins for serial communication).
You're getting closer! Time to program the chip!
Once WinAVR is installed, you should have a few new icons on your desktop.
Programmers Notepad is a nice code editor and highlighter.
What's a code editor/highlighter? When programming, you will need a text editor on
your computer so that you can create (type) code. Once you've created this 'code'
on your computer (inside the code editor) you will pass this code to the compiler
(you will click a button that runs the compiler with the C file you've typed) and the
compiler will create a HEX file (assuming there are no problems or typos in your
code). The highlighter? When creating code, it's often nice to have various parts of
your program color coded so that you can tell a common things like for( ) and
#define. This highlighting helps a lot when programming.
Use whichever text tool you like. Notepad will work, but is pretty rudimentary. I also
like JFE from my PIC days. Both have a 'tools' option which is great but JFE is better
in my opinion because it lists the C functions that you can double click on and
navigate to. If there is a way to do a similar trick in Programmer's Notepad 2, please
let me know! Because Programmers Notepad v2 (aka PN2) comes with the WinAVR
installation, we'll use it!
AVR-GCC is extremely powerful, very complex, and difficult to use initially. I am
used to passing a *.c file to a PIC compiler (CC5x) and getting a HEX file back out.
No fuss, no mess. Believe you me, the pain of getting AVR-GCC up and running is
worth it. AVR-GCC is a truly nice compiler, and it's free. I've included a stock
Makefile and blink_1MHz.c file in blink_1MHz.zip to get you started. I am by no
means a Linux or make type of person. All you need to know is that when you type
'make' at the command prompt, the compiler is going to look for a file called
'Makefile' (no file extension!) and use that file to direct how to compile your C file.

These are the only two files you should need to get blink to compile. Open up
blink_1MHz.c in programmer's notepad and click on Tools->Make All. This is the
same as typing 'make all' from the command prompt from what ever directory you
saved these two files. For example
C:\Code\Blink>make all
should compile your code as well. It's just a bit easier to do this through the
Programmer's Notepad interface rather than toggling back and forth to the
Command Prompt window. Once you have successfully compiled the C file into a
HEX file, you now need to get that hex file onto the AVR. It's finally time to power up
your system! The cheap AVR programmers require the target (that's your
breadboard) to provide power to the programmer (that's the AVR-PG1 or PG2).
Power up your bread board - you should see the power LED come on. From here on
out, I will assume you're using the AVR-PG2 parallel port programmer.
There is only two spots in the makefile that you should be concerned about at this
time. These two spots are located under the programming options section. This
makefile is huge, but scroll down to the Programming Options (avrdude) section.
Now put a '#' in front of lines you want to comment out.
If you're using the AVR-PG1 (serial port programmer) you edit like this:
#AVRDUDE_PROGRAMMER = stk200
AVRDUDE_PROGRAMMER = ponyser

# com1 = serial port. Use lpt1 to connect to parallel port.


#AVRDUDE_PORT = lpt1
AVRDUDE_PORT = COM1
If you're using the AVR-PG2 (parallel port programmer) you edit like this:
AVRDUDE_PROGRAMMER = stk200
#AVRDUDE_PROGRAMMER = ponyser

# com1 = serial port. Use lpt1 to connect to parallel port.


AVRDUDE_PORT = lpt1
#AVRDUDE_PORT = COM1
Of course the port numbers depend on your specific computer but once you get
things working, you'll be set for life. Assuming you've edited and saved your
makefile, go back to PN2. With your breadboard powered, click Tools->Program.
This will send the command 'make program' to the command prompt. If everything
is setup correctly, you should have successfully loaded blink_1MHz.hex onto your
target ATmega328 and your LED should be blinking.
If you get an error :
can't open device "giveio"
Then read this page. Basically you need to copy the giveio.sys file from
C:\WinAVR/bin to the C:\Windows directory, then type install_giveio.bat at the
command prompt.
Typical Problems:
If you still are not able to program the AVR - this is where 99% of first time users
end up. Dig in and troubleshoot.
Are the ISP connections correct? It's easy to get the ISP connector backwards. Take
a look at the photos above.
Is there a loose wire? Pull out the multimeter and check that you've got 5V being
delivered to the VCC and GND pins on the ATmega328. Do the wires going into the
ISP connector have a good solid connection?
Do you have your ATmega328 connected to both power and ground?
Is your 5V supply outputting 5V?
Do you have the right COM port or LPT port selected in your makefile?
There is a multitude of things to check. It's hard! I know. But once you get things
correctly set up, and that LED blinks - it will feel fantastic!
Ok - I'm going to assume that you got the code correctly loaded onto the AVR and
that the LED is blinking. Congratulations! You are now well on your way to a whole
world of pain! Once you get one thing working, it's hard to stop! GPS, datalogging,
RF, PCB layout - it's all just a couple hops away.
You can get all the parts for this lecture here.
Here are some additional resources for AVR programming:
• http://piconomic.co.za/fwlib/index.html
• http://www.salvitti.it/geo/sequencer/dev_tools/tutorial/GNU_C_Tutorial.html
• http://palmavr.sourceforge.net/cgi-bin/fc.cgi

Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=93>

Lecture 3 - What is an oscillator?


You can get all the parts for this lecture here.
Sorry for the confusion. When these tutorials were written and photographed, we
used the ATmega8. We now carry the newer ATmega168. You will find all
ATmega168 information in the following pages, but the pictures will show an
ATmega8.
You've got the LED blinking on your ATmega168 - congrats! That's a huge step. Now
it's time to make it blink faster!
You loaded code onto the chip and the ATmega168 is running that code, but how is
it running? And how fast? Any micro needs a clock source. Think of it like a a type of
'musical beat' that the micro uses to to execute its code in a set manner. Without a
clock, the micro doesn't know how to run the code, and with a sloppy clock (one
that varies a lot) the code runs at an undetermined rate. You must have a clock of
some sort and sometimes you need a very accurate clock. You ever try dancing to a
CD that skips? It can be very hard!
There are many ways to generate a 'beat' for the microcontroller. The ATmega168
gives many options. Here is a quick breakdown of the different types of beat
generators:
1. External RC - This is generally used for *very low cost* applications.
Using a resistor and a capacitor, the charge/discharge rate can be used as a
clock input. I've never really used this type of clock.
2. Internal RC - This is the super cool oscillator. Found on newer micros,
you can just ask the ATmega168 to generate its own clock! The silicon has a
built in oscillator. Unfortunately it's not very accurate.
3. External Oscillator - The is the defacto standard. Attach a quartz
crystal ('crystal' for short) to the two osc pins and the code executes at this
given frequency.
4. External Resonator - A resonator is a bit cheaper than an oscillator but
has worse tolerances.
5. External Clock - Instead of an oscillator, you can use a powered clock
driver. Handy if you have multiple devices that need to run on the same
frequency. I've never used this option.
For some great information about clock sources and their uses, checkout this app
note from AVRFreaks.
I really only use 3 out of these 5 options so I'm going to delve into them more:
Internal RC -
Atmel is very smart! They ship the ATmega168 preconfigured to use the 1MHz
internal oscillator. The ATmega168 (and AVRs in general) can operate at 1
instruction per clock cycle. This means that every time the oscillator goes through
one cycle, one instruction is completed (this is roughly true - there are some
instructions that take more than one clock cycle). Because we are using stock
ATmega168s, we are running the blink code at 1MHz or 1MIPS (million instructions
per second). You read that right - 1 million things a second! That's pretty
impressive. What's the problem with the internal osc? It has a tolerance of +/-5%
and a max speed of 8MHz. +/-5% tolerance means your ATmega168 might run at
1,000,000 * 1.05 = 1,050,000 IPS while your neighbors' ATmega168 runs at
1,000,000 * 0.95 = 950,000 IPS. This may not sound like much difference but in the
digital world, this is huge! Also, the ATmega168 has a max speed of 20MHz (the
internal osc runs max up to 8MHz) so if you really wanna push this IC to the max,
you'll need a to use an external oscillator.
External Oscillator -
This one is most common type of clock source.
Quartz crystal oscillators come in all different flavors and frequencies. Some of the
more common freq are 20MHz, 16MHz, 10MHz, 4MHz. There are also some
frequencies like 14.7456MHz, 9.216MHz, and 32.768kHz that are available because
these frequencies are multiples of speeds needed for serial communications and for
timing. For example - if you need really accurate 9600bps serial communications,
9.216MHz divided by 960 = 9600. There is no integer that divides nicely into 16MHz
to get 9600. So serial communications at 9.216MHz will be very accurate while
serial at 16MHz will always have some small amount of error.
Inside the metal housing is a small piece of quartz crystal that has been precisely
cut in size so that the piece of crystal vibrates at a specific frequency. The
ATmega's internal osc was +/-5% tolerant. On the other hand, a crystal is normally
'+/-20ppm'. This means the frequency is accurate within +/-20 parts per million! So
you might have a 16,000,020MHz crystal while your neighbor has a 15,999,980MHz.
This is equivalent to +/-0.00000125%. The crystal is 4 million times more accurate
than the internal oscillator!
Technical note: Sorry to swamp your brain with nitty gritty details, but this is
reasonably important. The silver metal device shown above is a crystal. It is
not technically an oscillator. Crystals are cheap. True oscillators are expensive
($2-$4 range). What is the difference? An oscillator uses power and creates a
true frequency pulse. This pulse can be used to drive all sorts of peripherals. A
crystal is a purely passive device that requires some external drivers to get it
to become an 'oscillator'. Luckily for us and the purposes of this tutorial, 99%
of all microcontrollers have built-in circuitry so that by attaching a cheap
'crystal' to the two input pins, the internal drivers will drive the crystal, create
an oscillator, and the micro will have a good clock source. Please forgive us
and all the other technical documents that incorrectly use 'oscillator' and
'crystal' interchangeably.
Some negatives of crystals:
1. Crystals are a bit expensive. $0.25 compared to $0.10 of a resonator.
2. They cannot be made as small as a resonator (crystals take up more
PCB area).
3. Crystals require 'load capacitors'. Load capacitors start the crystal
oscillating. Without the load caps, your crystal may function today, but
someday it may not. Load caps are cheap, but they take more room on the
PCB.
External Resonator -
Resonators fall in between the internal RC and a crystal.
A resonator is a piece of ceramic that is manufactured in such a way to oscillate at a
given frequency. Unfortunately this process is difficult to do well. Resonators have a
standard tolerance of +/-0.5%. So resonators are 10 times more accurate than the
internal oscillator but they are still a bit 'loose' compared to crystals.
Resonators tend to be cheaper than crystals. Resonators tend to be lower frequency
than crystals. Resonators are cool because they have the 'load caps' built into the 3-
pin device! Resonators can be made *very small* and can minimize your PCB area.
So pick your poison. For many applications the internal oscillator is just fine! But if
you're trying to do serial communication, 5% is usually too poor (serial tolerance is
1-2%). I've used crystals for most of my projects. But for the really small devices,
I've used a resonator. Anything that deals with digital RF signals requires some
really tight tolerance crystals. Any oscillator will fluctuate a bit over time (this is
called 'aging') and any clock will vary with temperature.
As mentioned earlier, the ATmega168 ships configured with an internal 1MHz osc.
But we can push it faster - and better! Let's setup the ATmega168 to run at 16MHz
with an external crystal.
What are some of the side-effects of running the ATmega168 at this higher
frequency? You will not be able to run the IC at this higher freq at lower voltages
(such as 3.3V or 2.8V). Since we are dealing with a 5V supply, this is not a deal
breaker. At 20MHz the micro will consume more power than at 1MHz. These are all
things to consider when developing your own system.
How fast can I push it?
The max speed for the ATmega168 is 20MHz or 20MIPS! That's blindingly fast!
Get your 16MHz crystal out and find pins PB6/7.
Plug the crystal legs into these two pins and connect these pins to ground through
two 22pF caps.
This completes the needed hardware, now we need to tell the ATmega168 to use
the external crystal.
Fuse Bits -
This was one of the wildest, hardest thing to get used to with AVRs. The fuse bits
are a very low-level configuration system. By setting or clearing these bits you can
completely change how the AVR functions. I was a PIC guy for many years and PIC
configuration bits were easy. You just clicked on a nice Windows GUI or
programmed the bits directly into your C code. No fuss. AVRs are very different and
you can literally break your AVR if you program the fuse bits willy-nilly.
There are two bytes on the ATmega168 that make up the 'fuse bits'. If you haven't
already, download the full ATmega168 datasheet (currently it's 376 pages long!)
and save it to your desktop. If you've never read a datasheet, don't worry! You don't
need to know all 376 pages, you just need to know how to absorb information from
it - and that's not trivial!
Let's do a search for 'fuse bits'. We get directed towards the 'Clock Sources' section.
What a coincidence! (Be sure to have the book marks or section bar open so that
you can see the different sections of the datasheet.) There are so many options for
clock sources into the ATmega168. Let's start with tweaking the internal oscillator
from 1MHz to 8MHz.
From page 34 (section 8.6): "By default, the Internal RC Oscillator provides an
approximate 8.0 MHz clock. Though voltage and temperature dependent, this clock
can be very accurately calibrated by the user. The device is shipped with the
CKDIV8 Fuse programmed. See “System Clock Prescaler” on page 37 for more
details."
So to get the internal oscillator to run faster, we need to change the CKDIV8 fuse
bit.
Ahah! Here we see how the ATmega168 worked right out of the box. Atmel ships
these to use the 'Calibrated Internal RC Oscillator' (8MHz) with the 'Divide clock by
8' set as well (1MHz). Very good. Now we just need to change the CKDIV8 bit.
Default Low Fuse Byte : 0b.0110.0010
New Low Fuse Byte : 0b.1110.0010
Using these new fuse bits, the ATmega168 should start running at 8MHz internal
osc and we should see the LED blink 8 times as fast! There is a couple ways to do
this, but the way that I've found to be most straight forward is a bit command line
intense. Open up a command prompt and type 'avrdude'. You should get a mass of
help text. If you're using a PG1 (serial) or PG2 (parallel) programmer, you'll need to
select the right string:
To read the ATmega168 fuses:
• PG1 (serial):
o avrdude -p m168 -P COM1 -c ponyser -U lfuse:r:-:h -U hfuse:r:-:h
• PG2 (parallel):
o avrdude -p m168 -P lpt1 -c stk200 -U lfuse:r:-:h -U hfuse:r:-:h
Again, I am going to assume you're using the PG2, but you can modify the strings to
work with a serial programmer. This basic string should cause avrdude to report
back the default fuses for the ATmega168 - High fuse = 0xDF, Low fuse = 0x62
How do I form a new fuse byte? Keep searching for 'fuse bits' until you hit page 288.
This shows the two fuse bytes (high and low) and their default values. All you need
to do is change the lower fuse byte from 0x62 (0b.0110.0010) to 0xE2
(0b.1110.0010). Now we splice this into the previous read string and switch from
read to write.
Internal 8MHz:
• avrdude -p m168 -P lpt1 -c stk200 -U lfuse:w:0xE2:m
Run this string at the command prompt and wamm-o, your AVR should be running
at 8MHz. I have had a few instances where avrdude reports some errors reading the
fuses and prompts if I want to 'recover' the fuse settings or some such error. I'm not
sure what the error is. You can say yes/no (doesn't matter), and then send the same
string. The second try should successfully set the fuses. All right, the LED should be
blinking like crazy, now let's take it up one more notch to 16MHz.
Notice how I don't have 22pF load caps on my 16MHz crystal? Bad engineer! Bad!
What are 22pF used for? These small capacitors help 'load' the crystal allowing it to
oscillate. Without them, the crystal may not start oscillating - hence, your system
might not run. This rarely happens, but in a full blown product, this would be
disastrous! It's ok to skip them for bread boarding purposes, but good engineering
practices require them.
You will need to have the 16MHz crystal attached to the oscillator pins as shown in
the last schematic above. Go back to the 'Clock Sources' category in the datasheet
and do a bit of research for the external crystal oscillator option. I'll give you a hint,
it's going to look something like this:
• CKDIV8 = 1
• CKOUT = 1
• SUT1 = 1
• SUT0 = 0
• CKSEL3 = 0
• CKSEL2 = 1
• CKSEL1 = 1
• CKSEL0 = 0
16MHz external osc:
• avrdude -p m168 -P lpt1 -c stk200 -U lfuse:w:0xE6:m
Once you get this programmed, the ATmega168 should be utilizing the external
16MHz oscillator blinking the LED super-fast. If not, check your load capacitors and
the xtal connections. The ATmega168 has a maximum speed of 20MHz (20 MIPS!).
Try overclocking your micro some day with a 30MHz or 40MHz crystal. More than
likely it will work just fine, but you'd never want to design a real system around an
out-of-spec clock speed.
Homework time. You will need to learn how to use your multimeter to measure
current consumption. Because current is measured in series (voltage is measured in
parallel) you will need to find a spot on your breadboard where all the current being
used by your bread board can be interrupted and measured. Measure the current
draw:
1. When the ATmega168 is in reset = ?
2. When the ATmega168 is running with 1MHz internal osc = ?
3. 8MHz internal osc = ?
4. 16MHz external osc = ?
A great resource that we use religiously is the AVR fuse calculator:
http://palmavr.sourceforge.net/cgi-bin/fc.cgi
Use it to double check your fuse settings and avoid permanently killing your AVR.
During each one of these experiments, do a quick temperature test of your voltage
regulator. In general, the regulator should be cool enough to touch. If it's red hot
(be careful!) you should turn off your breadboard and check for shorts.
Why do regulators heat up? We are using a very basic linear regulator. This type of
regulator inputs a higher voltage (in my case 9V) and outputs a lower voltage (5V).
The difference in voltage is expelled as heat through the metal tab. This heat is
measured in wasted power or Watts. If your input is 9V, output is 5V, and your 5V
system uses 50mA:
• (9 - 5) * 0.050 = 0.2W or 200mW
200mW will cause the regulator to heat up a bit. How about an amp?
• (9 - 5) * 1.000 = 4W!
That's some serious heat! The regulator will be very hot and may be permanently
damaged if it's allowed to run at super-high temperatures for extended periods of
time.
You may have noticed, by lowering the input voltage, we can reduce the amount of
heat expelled. Why not just input 5V and call it a day? These cheap linear voltage
regulators require something called 'drop-out voltage'. This is a very non-technical
term for the extra voltage the regulator needs to output the required voltage.
Anything below this voltage and the regulator will 'drop-out' the output voltage
below the rated voltage. For LM7805 it's a good rule of thumb to have 1.5V of
overhead meaning you need to input at least 6.5V to get 5V on the output. If you
input less than 6.5V (4 AA batteries for instance), the 5V output is not guaranteed.
Each voltage regulator is different so check the datasheet for the part in your hand!
Some v-regs are specifically designed to have low drop out voltage. Some smaller v-
regs have as low as 50mV! Our standard 3.3V regulator requires a minimum of
3.35V to output a solid 3.3V.
Many regulators have an internal shutdown feature that prevent the regulator from
destroying itself if there is a short on the output. If you flip the power switch on your
breadboard and the LED doesn't turn on, odds are your voltage regulator is trying
so hard to output enough current (because you've hooked up a component
backwards or worse) that the regulator shuts down and the LED has no power to
illuminate. If this is the case, shut down your breadboard asap.
In general, voltage regulators will run warm. This is ok. It you ever smell something
odd or you can feel a heat wave from your breadboard, just shut things down and
take a second look.
You can get all the parts for this lecture here.
From now on we will run things with an external 16MHz crystal. Vary as your project
needs it.

Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=95>

Lecture 4 - UART and Serial Communication


Hello, Hello World
You can get all the parts for this lecture here.
Sorry for the confusion. When these tutorials were written and photographed, we
used the ATmega8. We now carry the newer ATmega168. You will find all
ATmega168 information in the following pages, but the pictures will show an
ATmega8.
The ATmega168 has tons of hardware built into it. Let's unleash the serial
communication. Everyone has programmed the 'Hello World' program. You've got
your micro breadboarded and running at 16MHz. You've got WinAVR up and
running. We've already demonstrated LED control. Now it's time to pass some serial
data back and forth.
I am not a huge coder. I just want my printf() statement to do what it is supposed to
do. I don't use a hardware debugger, I debug by printf statements. Sure, there are
limitations with this, but for 90% of the applications out there, debugging with printf
statements works just fine.
First, a quick history of RS232. What is RS232? It's just a name for a standard that
has propagated from generation to generation of computers. The first computers
had serial ports that used RS232, and even current computers have serial ports (or
at least USB ports that act like RS232 ports). Back in the day, serial information
needed to be passed from devices like printers, joysticks, scanners, etc to the
computer. The simplest way to do this was to pass a series of 1s and 0s to the
computer. Both the computer and the device agreed on a speed of information -
'bits per second'. A computer would pass image data to a printer at 9600 bits per
second and the printer would listen for this stream of 1s and 0s expecting a new bit
every 1/9600 = 104us (104 micro-seconds, 0.000104 seconds). As long as the
computer output bits at the pre-determined speed, the printer could listen.
Zoom forward to today. Electronics have changed a bit. Before they were relatively
high power, high voltage devices. The standard that is 'RS232' dictates that a bit
ranges from -12V to +12V. Modern electronics do not operate at such high positive
and negative voltages. In fact, our ATmega168 runs 0V to 5V. So how do we get our
5V micro to talk the RS232 +/-12V voltages? This problem has been solved by the IC
manufacturers of the world. They have made an IC that is generically known as the
MAX232 (very close to RS232, no?).
The MAX232 is an IC originally designed by a company called Maxim IC that
converts the +/-12V signals of RS232 down to the 0/5V signals that our ATmega168
can understand. It also boosts the voltage of our ATmega168 to the needed +/-12V
of the RS232 protocol so that a computer can understand our ATmega168 and vice
versa. To get our ATmega168 IC sending serial characters to a computer, we have
to send these serial signals through a MAX232 circuit so that the computer receives
+/-12V RS232 signals. Don't worry if you're working with a chip labeled 'ICL232' or
'ST232' - these are just generics of the MAX232. Everyone says 'MAX232' just like
they say 'Kleenex' or Coke. The ICs all function the same and nearly all have the
same pinout.
The MAX232 circuit that we will be breadboarding looks like this:

MAX232 Circuit - Eagle schematic / PDF


This MAX232 IC uses three 0.1uF capacitors (C5, C6, C7) to operate (go read about
'charge pumps'). You must have these installed. The forth (C8) is what is called a
'decoupling cap'. As the MAX232 IC switches various signals (from +/-12V to 0/5V) it
uses bits of current. Because it needs these bits of current in bursts, it can disrupt
your 5V supply. The C8 0.1uF capacitor helps 'decouple' or remove the ill effects of
this IC (switching back and forth) from your power supply. This decoupling cap
should be placed near the VCC and GND pins of the IC. This helps remove noise
from your power system. Will your breadboard work without decoupling caps? Sure
it will! Go without! But the day will come when something stops working and you're
not sure why. Could it be my code? Do I have a short somewhere? A disconnect? Or
perhaps I don't have enough decoupling caps?
A decoupling cap is meant to provide a quick burst of energy if the power supply
dips down - sort of like a UPS system for your IC. The further the decoupling cap is
from the IC, the less ability it has to provide that quick burst (long wires have
intrinsic capacitance of their own). It's always good engineering practice to have at
least one 0.1uF cap near any IC. Placing them within 0.5" of the VCC and GND pins
is good. Placing them all the way across your breadboard won't do harm, they just
won't provide as much help.
JP2 is a DB9 connector. It's called a 'DB9' connector because it contains 9 pins and
is used universally for serial connections. You'll need a male to female serial cable
to connect your breadboard's DB9 connector to the computer. The 'male' end of the
cable has the metal pins, the 'female' end has the black colored plastic that
receives the pins. If you look very close at a DB9 connector in real life, you can just
make out some small numbers next to the holes.
So what all does this do? The ATmega168 is going to send 5V signals to the MAX232
IC. The MAX232 IC in turn will convert those 5V signals to +/-12V RS232 signals that
the computer can understand through the DB9 port on the back of the computer.
Admittedly this can be a bit ugly to setup at first. Will you believe me that once
setup, this will be your life-line to sanity? The serial connection is everything! You'll
need one on almost every application you do.

Breadboard with MAX232 and large loop-back jumper installed


Once you have everything wired, you'll need to open up a terminal program. If
you're playing under Windows, you can open up the included 'Hyperterminal'
program normally located under Programs->Accessories->Communications. Linux
and Apple people, you probably know how to get a terminal program running (sorry
I can't be more help!).
All terminal programs have the same basic function: to do serial. All you need to
specify is a few simple rules to get your micro playing successfully with your
computer. Let's just get through the Hyperterminal screens:

Call it whatever you want


More than likely, the serial port on your computer is COM1

You want 9600bps 8-N-1 without flow control


The main settings are 9600bps and 8-N-1. This means that the micro and the
computer agree to talk at a rate of 9600bits per second (bps) and that each byte
will have 8 data bits, with no parity bit, and only 1 stop bit. This '8-N-1' is very
common and basic. If you like pain, go read about parity, 1.5 stop bits, and 5 data
bits. No one really uses it in the breadboarding world.
Mkay, you've got hyperterminal open and kicking. You've got your MAX232 (or
equivalent circuit) built up and powered on. Before you connect it to your micro, you
should test that the MAX232 circuit works. The easiest way to test a MAX232 circuit
is to tie TX and RX together. It's called a 'loop-back' (the big yellow wire pictured
above). Pretty self explanatory, but just follow along:
When you press the 'A' key on the computer in the hyperterminal window, a series
of 1s and 0s get generated and pumped out the serial port on the back of your
computer (8 bits: '01000001' to be specific = 65d = 41h - see www.asciitable.com
for more info). These 0s and 1s hit the MAX232 on your breadboard which dutifully
changes these RS232 signals to TTL signals. The 0s and 1s get asserted on the
R1OUT pin. Because you've tied the TX and RX pins together (R1OUT should be
shorted to T1IN) these 0s and 1s get sent right back out the MAX232 and down the
DB9 serial cable. Upon hitting the computer, the computer 'sees' these 1s and 0s
and says 'oh! there is a device passing me the ASCII character A'. The computer
then displays the character 'A' in the hyperterminal screen. This is the essence of a
loop-back test. If everything is kosher, you should be able to jam away on the
keyboard and see those letters echoed back to the terminal window. Pull the jumper
out and the characters should stop echoing. Got it? Use it! In the future, when you
need to test a serial interface, short TX and RX together to make sure things are
working correctly.
All right, you've got the MAX232 working correctly. Now connect the TX and RX pins
of the ATmega168 to the MAX232 circuit.

ATmega8 with power supply and MAX232 circuit. Eagle schematic / PDF
You may have noticed C9 magically appeared next to the ATmega168 in the
schematic above. This is a 0.1uF decoupling capacitor for the ATmega168. A 0.1uF
capacitor places near the ATmega168's VCC and GND pins will help reduce power
supply noise being injected into the ATmega168. Again, your board will more than
likely run without decoupling caps but I just want to instill in you a habit of using
0.1uF like candy.

TX and RX connections between MAX232 and ATmega8


Savvy travelers will note (upside down) the picture MAX232 IC is actually a
SP3232(EBCP). What is this 'SP3232'? It's a the Sipex generic of the MAX232. Notice
the '3' in front of the 232? The original MAX232 ICs were designed to interface 5V
logic to RS232. Because circuits started to run on lower voltages (3.3V for instance)
the IC manufacturers had to redesign the MAX232 ICs to be more efficient so that
they could take this lower voltage and boost it up to 12V for RS232. Hence the 3V
designation 'SP3232'. This IC can input 3V TLL signals and successfully convert
them to RS232. We are operating our breadboard at 5V but we are able to run our
MAX232 from 3V up to 5V without problems.
Trivia: In the picture above, which IC is the older sibling? These ICs have simple
date codes: 0641 and 0625 means both ICs were manufactured in 2006 in the 41st
and 25th weeks of the year.
You should now have the hardware in place to allow you to do printf statements.
Let's mess with some code!

Feedback from a reader:


"Friends don't let friends use hyperterminal. It is one sucky program.
TeraTerm works much better."
We agree. Hyperterminal is a bit buggy and can lock up. TeraTerm is much
better. However, since nearly every Microsoft installation on the planet has
Hyperterminal already installed, we stuck to using it to ease readers into serial
communications. In general, once you get over the serial hurdle, stop using
Hyperterminal and start using TeraTerm.
Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=104>

Lecture 5 - AVR GCC Compiling


Sorry for the confusion. When these tutorials were written and photographed, we
used the ATmega8. We now carry the newer ATmega168. You will find all
ATmega168 information in the following pages, but the pictures will show an
ATmega8.
I know very little about the ins and outs of the AVR-GCC compiler. I've learned a few
basics that helped me along the way, but when you run up against a jam, google
and AVRfreaks.net are your friend.
First, we did the blinky. Open this code in PN2 and make sure you can compile it.
Click on Tools->Make All. The window in the bottom screen should say 'Process Exit
Code: 0' meaning the compilation was successful. If not, there should be a line
number listing of the problem line of code. Be sure to check above and below the
indicated line for problems.
In the second example C file called basic-out-atmega168.c (basic-out.c for the
ATmega8), I've inserted a handful of functions and lines of code. First of the black
magic:
#define FOSC 16000000
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1
What is all this noise at the top of the file? This is a series of defines that calculates
the MYUBRR variable with the correct number. Since serial communication depends
on the fact that we will be transmitting and receiving at 9600 bits per second, it's
crucial to tell the ATmega168 what bit rate to set. Because the ATmega168 is
dictated by the oscillator that it is using, we must correctly calculate what value we
need to load into the ATmega168 hardware so that the ATmega168 sends the serial
pulses at the correct rate with a given oscillator type. In our case, we are using a
16MHz oscillator so we can setup the define statement as shown. MYUBRR is
calculated at compile time and is loaded successfully into the hardware UART
during run time.

A reader's untested submission:


The UBRR value calculation in Lecture 5 could be more accurate with the
following macro:
#define MYUBRR (((((FOSC * 10) / (16L * BAUD)) + 5) / 10) - 1)
There is also pretty useful web form for UBRR calculation:
http://www.wormfood.net/avrbaudcalc.php

static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);


This line creates a buffer for the printf statement to post to. I'd rather not explain it,
simply because I don't understand it. When I am working on a new coding project I
never start from a blank page, I *always* start from a known working program and
slowly bring in bits of other projects to get the code I need, writing bits along the
way. Please start from this printf example and build away. The purpose here is to
get your printing string to the terminal window.
Checkout the ioinit() function. You'll notice some new commands.
UCSR0B = (1<<RXEN0)|(1<<TXEN0);
This is the really funky, but very practical, method of setting bits on the AVR series.
RXEN0 is defined in some file as '5'. 1<<RXEN0 translates to 'shift a 1 to the left by
5 spaces'. This is handy because you don't need to remember specifically where
the RX enable bit resides, you only need to know to set (or not set) the RXEN0 bit by
using this bit command. Same goes for TX enable. Using the example code above,
these two bits (RXEN0 and TXEN0) get set and loaded into UCSR0B register,
enabling the TX and RX hardware on the ATmega168.
Finally, we see the very comfortable line of code:
printf("Test it! x = %d", x);
What did you say? This is not a comfortable line of C code for you? Ok - printf is
somewhat of a universal function to pass serial strings and variables to the outside
world. The line of code above will pass the string "Test it! x =" to the serial port and
it should display on the terminal window. After that, the %d gets converted to an
actual decimal number so that whatever digital number is currently stored in the
variable x gets printed to the terminal screen. So what? This simple printf statement
allows you to print variable contents and see what's going on within your C
program.
Time to load the basic-out-atmega168.c file onto your breadboard. Open up PN2,
compile basic_out-atmega168.c. Power up your board, click on Tools->[WinAVR]
Program from within Programmer's Notepad. The code should now be loaded onto
your ATmega168. If WinAVR throws a verification error, try again. Open up the
terminal window at 9600bps if you don't already have it open.

Text output from the ATmega168 and MAX232 circuit


All right! We've got output from the ATmega168! Now let's talk about some more of
the code:
sbi(PORTC, STATUS_LED);
Another funky one if you're not used to the AVR series. To toggle a GPIO pin
(general purpose input/output pin), you need to read the state of the port, mask the
bit change into the state-word, and then write the 8-bits back onto the port
effectively modifying just the one bit. Instead of doing all that by every time you
want to toggle a port pin, there's this handy macro:
#define sbi(var, mask) ((var) |= (uint8_t)(1 << mask))
SBI sets a bit. CBI clears a bit. You have to specify which port you're working with
and which pin you want to alter. Throw another define at the top of your code:
#define STATUS_LED 0
Now you can control your STATUS_LED on PORT C using these two simple
commands:
sbi(PORTC, STATUS_LED);
To turn on the LED and
cbi(PORTC, STATUS_LED);
To turn it off.
You should have an LED tied to pin 23 on the ATmega168. When in doubt, toggle
your status LED to figure out where the code is hanging or use a printf statement.
There are also some tweaks to the delay_ms() routine. Because we increased the
oscillator from 1MHz to 16MHz, I increased the loop iterations to tie up the
processor for longer. I didn't do any real calculations so don't depend on my
delay_ms routine. delay_ms(1000) looks to be roughly a 1 second delay.
Open basic-in-atmega168.c (basic-in.c for the ATmega8) and load up your
breadboard:

Key presses and various responses


Here we see that whatever character we hit, the ATmega168 responds with 'I
heard : ' and the character. Also, if you hit return, X, or g, you will see various
special output.
key_press = uart_getchar();

printf("I heard : %c\n", key_press);

if(key_press == 'g') printf(" GO!\n");


if(key_press == 'X') printf(" EXIT\n");
if(key_press == 13) printf(" RETURN\n");
uart_getchar sits waiting for a character to appear in the UART. Once received, the
ATmega168 outputs the character (%c) and goes to a new line (\n). It then checks
to see if the key press was one of three special cases. If so, it prints an extra string
accordingly. I hope you are starting to see the power of the input/act-upon/output
that a microcontroller is capable of. With a little bit of work, you could program your
own text-based adventure game. Go to town.
Remember back when you were struggling to get your power supply wired up? Nice
job! Time to heat up your irons.

Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=105>

Lecture 6 - Soldering Basics


Say it with me - 'Yes, I really can solder that'. Yes, you really can solder that and
anything else.
First, we will solder a through-hole component kit. Here are the ground rules for
soldering:
• Rule 1: Irons get hot. Don't poke your lab partner in the eye with it.
• Rule 2: You need to wet your sponge. This may seem counter-intuitive, just
do it. I hate seeing people ruin irons because they're too lazy to get the sponge
wet. This wet sponge is used to clean the corrosion on the tip of the iron. A dry
sponge does nothing but damage the tip. Every time you pull the iron from the
stand, it's a good idea to swipe the tip on the sponge just to clean it off and get
a nice silver tip - it will allow you to solder much quicker and much cleaner.
• Rule 3: The point on the iron-tip is NOT the hottest part. This takes some
practice but learn to use the side of the tip near the point. It's all about getting
the heat to flow from the iron to the joint. If you sit in one spot for a long period
of time and nothing is flowing, take a step back, clean your tip, add a bit a
solder to the tip, and try soldering the joint again.
• Rule 4: The soldering iron is only there for heat, not solder. You use the iron
to heat two things - the part and the board, and then you add solder to the two
heated parts. You do not add a glob of solder to the tip and then rub this mess
against the two things you're trying to solder together. Use the side of the iron
(remember, not the point) to heat the two parts while adding solder from the
opposite side.
• Rule 5: Perfectionism kills. If you solder a joint, and it looks alright, let it be.
Do not solder, then touch up, and re-solder, and then have to touch up a third
time. This heating/reheating stresses the PCB (printed circuit board). You will
quickly delaminate the board, lifting traces, pads, and destroying the board. Do
this for fun on your own time.
• Rule 6: This is really getting ahead of ourselves here, but it's good to hear as
many times as possible. When soldering joints that have a lot of thermal
weight, heat the joint up for an additional 5-10 seconds. When you solder to a
big part or a pad that has a lot of copper attached to it (very common with
GND connections), it takes a few extra seconds for the iron to pump enough
heat into the part to get it to the correct temperature to form a connection. If
you notice your iron tip feels 'sticky', or if you see the solder balling to the pin
instead of flowing to the joint, this is because one part of the joint is not hot
enough. Hold the iron on the joint for a few extra seconds and allow the solder
to flow correctly.
Here is a short video to demonstrate how to clean your iron tip, solder a through
hole component, and clip off the extra leads.
Now about irons:

This is my cheap-o Sunkko iron. It was under $100, it can solder lead-free solder just
fine, and I use the standard included iron tip. You don't really need a digital read-out
for home use, but do get an iron that has an adjustable temp dial. I set mine temp
to about 350C for leaded solder. Notice my sponge is wet!

A cold iron tip. You can see the barrel and upper area of the iron are discolored by
heat over time. No problem. You do not need an needle-sized iron tip to solder SMD
devices. This is a common fallacy. This tip works very well!
Here's my solder. I stole this from work because 1) It's leaded and we use lead-free
for production. 2) It's 0.020" diameter which is really too thin for production.
Because it's so thin, the assemblers would have to use many many inches of solder
to solder larger joints (like DB9 connectors). Smaller diameter solder helps you
control how much solder goes into very tight pitch joints but it's not magic - it is not
required. Just don't buy the solder at the hardware store that they sell for copper
pipe plumbing, that stuff is ridiculously thick.
This solder is SN63PB37 meaning it's 63% tin and 37% lead. It's also called 'rosin
core solder' because it has an organic core of rosin. As you melt the solder into the
joint, a small amount of rosin inside the core will come out and help the solder flow.
Rosin basically changes the surface tension of the solder allowing it to flow better
(we're talking about liquid metal after all). Rosin will burn off and that's the small
amount of smoke you see while you're soldering. Standard rosin smoke is not
harmful! It has been known to irritate some people's eyes but I've never known
anyone to have a problem with it. When in doubt, get a fan or open a window. Lead
is known to be a carcinogen. In general, don't eat the solder. Wash your hands
before you eat and you should be safe.
This is a 1lb spool which should last me until 2020. $18.95 from JB Saunders.
JBSaunders is a surplus shop in Boulder, CO. They sell some handy tools and
supplies but it's not your standard hobby shop - it can be tricky to get help some
days. Solder aficionados may watch the DOM (date of manufacture) and claim that
solder will go bad at some point. I have no idea. I imagine the rosin may change
slightly over time but this solder is probably good for many years to come.
Here is a hot iron, with a blob of oxidized solder on the tip.

A quick double swipe on the sponge and the tip is clean and shinny. This is the iron
you should be soldering with! Keep your tip clean and shinny. Clean it often. Wipe it
on the sponge every time you take it out of the base. Add a bit of solder to the end
of your cleaned tip to increase heat flow
That's the starters. Soldering takes practice! Just go and get your hands dirty
already.

The Shifter board assembled


You will be assembling the 'Shifter board'. (Please note: the component placement
on the shifter board in the photos in this tutorial might not be the same as the
shifter board you purchase. Make sure to follow the silkscreen indicators on the
board you receive for proper component placement.) This board is a MAX232
equivalent circuit meaning it does some dirty tricks to convert RS232 signals to TTL
level signals. It does this with a few pennies worth of parts instead of a proper
MAX232 IC.
The benefits of the shifter board vs. a conventional MAX232 circuit:
1. The shifter board is smaller than a MAX232 DIP with its charge-pump
caps
2. Cheaper
3. Works at voltages down to 2.5V (compared to the MAX232 that only
works at 5V)
Problems with the Shifter board:
1. It's a bit dirty, meaning it does not follow the proper RS232 +/-12V
convention (shifter board only puts out -3V to +5V)
2. It will not operate faster than 115200bps (some MAX232 ICs can
operate up to 1 mega-bit per second)
3. It only has TX/RX where a MAX232 has TX/RX/CTS/RTS (additional
control lines)
In response to problem 1 - I've never come across a modern computer that the
shifter board does not work. This is because the RS232 ports on modern computers
are designed to deal with poorly designed serial devices! So even though our shifter
board can't quite get to the -12V and +12V, the computer can still understand what
it's trying to say.
Problem 2 - Windows simply can't handle serial speeds faster than 115200bps (well,
not without some serious finagling). The shifter board works fine at this speed so
the MAX232 has no real advantage for the every-day application.
Problem 3 - Almost all the serial interfaces you will be building, hardware flow
control (CTS/RTS = clear to send and ready to send) is rarely used. The shifter
circuit is simple. Replicate it twice if you want flow control.

So let us build up this kit and replace the MAX232 circuit in the breadboard with our
shifter circuit. Always lay out all your parts to make sure you've got everything you
need.

Plated through-hole (PTH) resistors have color bands on them. Surface mount
device (SMD) resistors have readable numbers on them. I can't read the color bands
on resistors to save my life, but your multimeter can! The shifter kit is easy to tell
which is which - there are five 10k resistors and two 220Ohm resistors.
Resistors are non-polarized meaning they can be inserted into the board either way.
You can pre-bend the resistor leads if you like. After the resistor is inserted into the
board, bend the legs out the other way so that it stays in place. Pull out your iron
and solder the resistor from the bottom side of the board.

Hold the iron against the PCB and the leg of the component. Insert solder into this
trio. It should melt as you add it. If not, re-orient the iron to get better heat
conduction. It's not hard, just practice. Once you've got the two joints soldered, clip
off the legs.
Clip off the legs. Don't worry about clipping the legs absolutely flush. Doing so can
stress the mechanical nature of the joint and the PCB.
The kit has various indicators showing the assembler how to orient parts. Pay close
attention to these and the resistor values.

Notice the small pool of solder at the base of the resistor legs we just soldered in?
This is good. Enough solder was applied to come through the holes from the bottom
of the board to fill all the way through the via.
The single diode in the kit is polarized so you'll need to get the orientation right. In
the picture above, the black line on the diode matches with the white line on the
silkscreen.

Soldering the diode like this would be bad. Make sure you get the component flush
against the PCB, within reason. Some components (like the transistors we're about
to solder) ride above the PCB. Solder up the rest of the resistors.

All the resistors and diode


Soldered and trimmed. Notice the small amounts of residual flux - it's the clear,
shiny, sticky material left of the board. For production assemblies, this flux is
cleaned off with a light solvent or rubbing alcohol. Flux is slightly acidic and will
degrade solder joints over a period of years. For our purposes, this flux is ok and
shouldn't cause any problems.
Solder in the electrolytic capacitor noting the '-' sign polarization matching with the
silk screen.

LEDs installed. Note the flat side of the LED matches the silkscreen polarization.

Install the 2N3904 and 2N2906 transistors. Note the flat side of the BJT transistor
matches the flat side of the silkscreen. Make sure you get the correct '3904' and
'3906' labeled parts in the correct spot.
Here is a short video to demonstrate how to clean your iron tip, solder a through
hole component, and clip off the extra leads.
Install and solder the DB9 connector.

You can see now why it would have been a bad idea to solder the DB9 connector
first. The PCB would have been at an angle during soldering.
Solder in the four connection wires - VCC, GND, TX, and RX. Pick your own color
scheme. I only recommend that red and black go to VCC and GND respectively.

The shifter board, all assembled!


Guess how we're going to test it? A loop-back jumper of course! Plug the shifter
board into your breadboard, VCC and GND, and insert the TX/RX wires into one row,
shorting them together.

Power your board, pound some characters into hyperterminal and verify that you
get an echo. You should see the TX and RX LEDs blink briefly. Congrats! You now
have a serial connection for all your future breadboard prototypes! This should open
up some significant space on your breadboard and allow you to skip building a
MAX232 circuit for future breadboard projects.
In the end, I use the shifter board on all my breadboard prototyping and a
conventional MAX3232 circuit on my PCB designs. Sorry to confuse you so much.
When you solder together as many prototype PCBs as I do, you really want to limit
how many solder connections you have to solder. Inserting through-hole
components for the shifter circuits takes much more time than a MAX3232 circuit. I
also like the MAX3232 circuit because it has fewer parts that could break.

Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=106>

Lecture 7 - SMD Soldering


You can get all the parts for this lecture here.
Remember, 'Yes, I really can solder that'. It's time to put Simon together! This SMD
kit will show you just what it takes to solder SMD components.
The SparkFun SMD Soldering Workshop is a pseudo-class that we've been working
on at SparkFun. We hand out some paper materials and teach people these lectures
and have them assemble a Simon kit. It's a lot of fun! You can download the
handout here that contains the following material and a bit more.
Here are the various files you will need:
• Simon Assembly Procedure (follow the steps! [5MB])
• Simon Board (component print)
• Simon Eagle Files (for trouble shooting)
• Simon ATmega168 Firmware (for programming)
• Simon (Old) ATmega8 Firmware (for programming)
• Simon Schematic (for general reference)
Here is some good information for SMD soldering:
• SMD Soldering Basics (big 4MB)
• SMD Soldering Workshop
Here is some basic code examples to show how to control various parts of the
Simon board:
• Basic Simon Control
For more soldering tutorials, there are some great videos and instructions on the
SparkFun website here. Read up on those basics as well.
Two words : solder wick. Get some. Actually, get a lot.
Simon SMD Kit
This is what we will be assembling today.

Assembled and blinking!


Make sure you've got all the components you need. Remember, SMD resistors are
marked, capacitors are not so be sure to correctly identify the caps by writing on
the tape immediately after you cut it off the reel. If you've just got a Digikey bag,
make sure the correct components make it back into the correct bag.
Through-hole components:
• 1 x Simon PCB
• 2 x AA Battery Clips
• 1 x Buzzer
• 2 x Slide switches
• 1 x ISP Header
• 4 x LED (Yellow, Blue, Red, Green)
• 1 x Momentary Push Button
• 6 x Screws
• 6 x Plastic Standoffs
• 1 x Rubber 4-Button Pad
SMD components:
• 5 x 10k Resistors
• 4 x 220 Ohm Resistors
• 1 x 47uF Capacitor
• 1 x 10uF Capacitor
• 1 x 0.1uF Capacitor
• 2 x 22pF Capacitor
• 1 x 16MHz Crystal
• 1 x MBRA140 Diode
• 1 x 22uH Inductor
• 1 x NCP1400 SOT-23-5 IC
• 1 x ATmega168 TQFP IC

Parts and assembly sheet


We created an Eagle shortcut button to help us produce assembly sheets. Pressing
Alt+F11 will turn off all the extraneous layers, and turn on only the layers we need
for assembly purposes. Pressing F11 will turn all layers back on.
All layers vs. assembly layers
Once you have just the assembly layers turned on, you can print the assembly
sheet. I like to scale this print out by 3 so that the printout is 3 times larger than
actual size. This helps when writing component values next to tightly packed
components. With the printout in hand, write in all the pertinent component values
so that you know what goes where.
When soldering a mix of through-hole and SMD components, always start with the
smaller, tighter pitch devices. If you go jumping into the easy ones (the power
switch, LEDs, ISP header, etc), you will run the risk of touching the iron against
these larger plastic items and melting them. Let's start with the power circuit:
The first thing we are going to build is the DC to DC step up power supply. This will
take the 1.5V from the AA battery and boost it to 5V.
NCP1400 surrounded by inductor and diode
Be sure to start with the inner most parts and work your way out. Otherwise, it can
be difficult to get the iron into tight spaces.
Let the videos begin!

Clean your iron on the wet sponge. Place a blob of solder on one or two pads on the
PCB. Slide the component into the blob and remove the iron. If the IC is not lined up,
or is not flat against the PCB, heat the blob back up and re-align the IC square and
flush against the PCB. You can do this 3-4 times before you start to thermally stress
the PCB.
Once you have the IC to your liking, solder the other pins. Don't worry about
jumpers.
If you have jumpers, pull out the solder wick. Watch the video closely! First I put a
blob of solder on the end of the iron, hold the wick over the jumper, then I hold the
iron w/ blob against the wick. You will notice a change in color of the wick - this is
the solder climbing the wick! The blob on the iron aids in transferring heat and flux
to the wick and jumper. After a few seconds, the blob travels up the wick and pulls
the jumper along with it. Remove the wick along with the iron (do not remove the
iron and allow the wick to attach to the component). The jumper is removed.
Not so bad, right? Now let's solder the diode.
Add solder to one pad. Make sure the white mark on the diode lines up with the bar
on the silkscreen. Slide the diode in, hold it in place while you remove the iron. If
alignment looks good, solder down the other end.
NCP1400 with inductor and diode

The inductor requires a bit more solder and patience. The footprint is pretty tight.
Make sure you slide the inductor all the way over your first pad so that you can
solder the 2nd pad.

Solder on the 10uF cap and 47uF cap. Make sure you get the polarization correct.
Solder in the power switch.
Solder in the AA battery lugs. They will require a bit more heat and time because
they act like heat sinks. Once you have all these power components attached, insert
a AA battery into the power clips. Be sure the '+' and '-' signs on the board match
up to the battery.
Whip out your multimeter, cross your fingers, flip the power switch to 'On', and
measure the voltage across the 47uF capacitor. It should read approximately 5V.
4.8V to 5.2V is fine. If you read something much lower, turn off the board
immediately and check to see if anything is warm. Check your polarization of
components (diode, caps, and battery). Check to make sure all the solder
connections are sound. Touch up as necessary and re-test. Make sure you've got a
solid 5V supply before moving on. Remove the battery to prevent accidental turn on
during soldering.
Time to solder the ATmega168!
Same steps: put a blob of solder on one or two pads as the anchor. Slide the IC into
the molten solder and align the IC. Once you have everything square and flush
against the PCB, remove the iron. Do not worry about jumper, but do not solder
more than 2-3 pads while you are doing this alignment step.
Soldering Side 1: Now that you've got the IC in place, jumper the opposite side like
crazy. Make sure each pin gets heat/solder. Then go back with wick and wick away
the excess.
Soldering Side 2: More of the same. Jumper, and wick away.
Soldering Side 3: If the wick starts to get in your way, cut off the used wick (once it's
silver, it's not re-usable) and throw it away.
Soldering side 4: Same motions, but two of the pins should already have a jumper.
Add solder to all pins like before, and wick away the extra.
The ATmega168 should now be soldered! Congrats! That was the hardest part! Let's
solder the crystal next.
Add solder to an anchor pad, slide and and align the crystal so that you can see
equal parts of all four pads. Solder the other four pads. Be careful not to allow
solder to jumper from the pad to the top cover. The crystal packaging is ceramic
(non-conductive) but the top is metal and will short pads together if you're not
careful. This shouldn't harm the crystal, it just won't oscillate.

0603 Resistor pinned down


Now we have a handful of discretes to solder down. Be sure you get the 220Ohm,
10k Ohm resistors, 22pF, and 0.1uF capacitors in the correct places. They are not
polarized.
Add solder to one pad (in the picture above I've added anchor solder to all
components on the board), slide the component in, and remove the iron. Add solder
to the 2nd pad. Add solder to the first pad if you want, to try to minimize the 'horns'.

220Ohm 0603 resistor all happy


Continue soldering all 0603 components.
Close-up of the ATmega168
Don't worry about the gunky brown stuff too much. That's residual flux and can be
cleaned off with a little rubbing alcohol if it bothers you.
Now it's time for the easy stuff! Soldering in the through-hole components!
Use the weight of the PCB to hold the ISP connector in place. Be sure to solder the
ISP connector so that the long pins point up when looking at the front of the board.
You will be soldering from the back of the PCB. Tack one pin down and check that
the ISP connector is flush against the PCB. If it's not, re-heat the one pin while
lightly applying pressure to the connector/PCB until they are flush. Now solder the
other 9 pins, finally touching up the original anchor pin.
Ground pins will require extra time/heat. Don't get speedy. Childs play compared to
SMD components, right?
Now insert and solder the reset switch. The reset switch should lock into place so
just make sure it's flush before soldering it.
Repeat these steps for all through hole components (sound switch, buzzer, etc).
Almost there!
Notice we have not yet soldered in the LEDs. Because they are clear, we don't know
which LED goes where. Also, we've been tricked in the past by mistakenly marked
LEDs (the flat mark on the LED did not correctly match with the silkscreen). We first
need to program the board with Simon game firmware and then hold the LEDs in
place for testing.
First step - add some stand-offs. This will levitate the board above your work area
and avoid the possibility of shorting bits of scrap wire across the back of your PCB.
Insert the AA and make sure we still have 5V on the board. If not, immediately
disconnect power and check for shorts. Continuity probe if necessary. Now attach
the AVR-PG2 programmer and open Programmer's Notepad as we did in Lecture 2.
The AVR-PG2 programmer requires power from the board so be sure to turn on your
board before attempting to program.
We will need to configure the ATmega168 to use its external 16MHz crystal. Review
Lecture 3 and in a command prompt send:
• avrdude -p atmega168 -P lpt1 -c stk200 -U lfuse:w:0xff:m -U hfuse:w:0xc9:m
If the fuse programming throws an error (it always does on the first try for some
reason), select 'n' and try again. The second time, it should complete successfully.
Here is the firmware for Simon for the ATmega168. Open Simon.c in PN2, select
Tools->Program and the firmware should load onto your Simon board. Now insert
one of the LEDs and hold it slightly at an angle. It should light up momentarily. Turn
off Simon. Whatever color the LED is, insert it into the appropriate place on the PCB,
bending the legs once it's flush against the PCB to hold it in place. Solder this LED in
place and repeat these steps for the other three LEDs. If the LED does not light up,
flip the LED around to see if it's an orientation problem. If the LED still does not light
up, check to make sure the firmware is loaded correctly.
Once you have all four LEDs soldered in place and blinking correctly, add the button
pad and secure it in two places with a screw and standoff.
Simon!
You should now have a functioning Simon game! Congratulations!
Now if you are the lucky type that runs into problems during assembly/testing, there
are a few things that should be checked. In order of priority:
1. Test for shorts between VCC and GND
2. Check that the board has 5V
3. Test ISP pins for shorts to GND, or shorts to VCC
4. Probe connections from ISP connector to given pins on ATmega168
5. Probe connections from pins on ATmega168 to various components
If any one of these steps fails, you should be able to localize the problem and cut
traces, green wire, whatever it takes to get the PCB working.
The parts for this lecture can be purchased here.

Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=107>

Lecture 8 - Eagle: Schematics


Welcome to the wonderful world of PCB creation! We've used a few software
packages over the years (namely Protel DXP) and have found Eagle Layout Editor
from CadSoft to be very easy to use, very cost effective, and very powerful.
Eagle is free! There are some limitations in place, but basic students and non-profit
groups can use it. Protel is currently about $12,000 a seat.
Eagle is not the 'hobbyists' tool you may think it is. I've seen some very complex 8-
layer BGA boards going into a firewall/router consumer product. I too was amazed
to hear it was created in Eagle. It can be done, you just need to dream up the
device!
There are a few files that you will need to download for this workshop.
1. Download Eagle itself. Currently we use v4.16 (~8MB). Versions are
available for Windows, Linux, and Mac. If the above link does not work, google
’eagle pcb download’ to get the latest version.
2. Download the SparkFun Eagle Library. This is the collection of all the
components SparkFun designs with and therefore components and footprints
that have been tested. Unzip and place the SparkFun.lbr file into the Eagle\lbr
directory. If the above link does not work, google ‘sparkfun eagle library’ to get
the latest collection.
3. Download the SparkFun Eagle keyboard shortcuts. Place this file in the
Eagle\scr directory. If the above link does not work, google ’sparkfun eagle
shortcut’.
4. Download the SparkFun CAM file. Place this file in the Eagle\cam
directory. This file is responsible for creating the gerber files for submission to
a PCB fab house.
Note: The SparkFun Eagle shortcut key script file has an .scr extension. This is a
common virus infiltration method. If you choose to download our keyboard
shortcuts, and you don't trust us, rename the file to a .txt extension and view it in a
text viewer. There's nothing there but text and Eagle commands. Just be sure to
rename the file to the .scr extension so that Eagle will use it.
To learn how to use Eagle, we are going to create a simple breakout board for a
popular USB IC. The FT232RL is a USB to TTL serial converter.
What is a USB to TTL converter?
Once the FT232RL is attached to the USB port on your computer, you will need to
install some simple drivers (available for Windows, Linux, Mac), and then you will
see a Virtual Com Port (VCP) appear on your computer. You can then use
hyperterminal to open this new com port number. Any letters that are typed in
hyperterminal are converted to a USB packet in the background, sent down the USB
cable to the FT232RL where it reconstructs the serial information and passes these
letters out the TX pin on the IC at whatever baud rate you choose. If you have a
device connected to this TX pin, it will hear the serial letter and react. This will
effectively give your device USB connectivity and you won't need to know a thing
about how USB actually works!
This IC is very popular, but only comes in surface mount device (SMD) packages
(sound familiar?). So let's spin a simple PCB that will allow us to use this handy IC.
• FT232R Page
• FT232R Datasheet
• FT232R VCP Drivers
When in doubt, follow the manufacturer's recommended circuit. This 'typical'
application is just what we need.
This is a bare-minimum feature setup for the FT232R. Just what we need for simple
TX/RX to USB. We want to plug the FT232RL on to the USB port, have it bus
powered, and possibly power the rest of our circuit. Our ATmega8 uses 5V so we'll
tie VCCIO to the USB 5V. A USB connector, a couple 0.1uF caps, a bigger tantalum
cap, a ferrite bead, this doesn't look so bad!
Before we can get started, we need to create or locate a library part for the
FT232RL. I really don't like using other people's footprints and schematic parts but
in this case, FTDI has created some free libraries for their parts. This page should
have the Eagle library (search the page for FT232RL) but if not, google 'ft232rl eagle
footprint'. We also have this part proven in the SparkFun.lbr library. Use their
library, use ours, create your own, it doesn't matter. But because we are most
comfortable with our own parts (we know they work!) we will be using the
SparkFun.lbr file for this tutorial.
Now let's add the FT232RL part to our schematic. Close the library editor and go
back to the Eagle Control Panel. Click on File->New->Project. Name this new project
'FT232-Breakout'. Right click on the FT232-Breakout project and create a new
Schematic:
The schematic editor should open. Now go back to the Eagle Control Panel and
expand the SparkFun Library:
You should see a long list of parts. Highlight the FT232RL-Basic part and in the right
screen click on ADD. The schematic editor will pop up allowing you to place the
FT232RL.
Now save your schematic!
I like to use a board name and a version number within the file name. -v10, -v11,
v12, etc as 1.0, 1.1, and 1.2 advance through layout changes.
Now add these other items to your schematic:
• 1 x FRAME-LETTER : This will add a nice frame to your schematic. Add all
parts inside this frame.
• 3 x CAP (Device name CAP0603) : 0.1uF/0.01uF 0603 capacitors
• 1 x CAP_POL (Device name CAP_POL1206) : 10uF tantalum capacitor
• 1 x INDUCTOR (Device name INDUCTOR0603) : Ferrite bead
• 4 x STAND-OFF( Device name STAND-OFF): This part will add a hole and a
keepout ring for a #4-40 screw. These can be used to raise your board up off a
surface or to mount your board to an enclosure.
• USB (Device name USBPTH) : USB Type B through-hole connector
• M04 (Device name M04PTH) : Four pin 0.1" connector
• GND (Device name GND) : Ground connections
• VCC (Device name VCC) : Power connections
Parts added to the schematic
You can click on the button you need on the menu on the left side of the screen.
You can also hover over each button and its name will pop up. This works great for
beginners but as you advance, you'll want to speed up layout by using keyboard
shortcuts. Here are some of the basic quick keys:
• Press escape at any time to stop the current action and return to the
schematic window
• F7 to move a part
• Alt+F7 to group a bunch together
• F3 to delete a part
• F4 to rename a part (change C7 to C2)
• F5 to re-value a part (change 0.1uF to 10uF, etc)
• F6 to smash a part (be able to move the name and value tags)
• F9 to start a wire
• Alt+F9 to add a label to a wire
NEVER change the grid size in the schematic editor. Leave it on 0.1inch steps and
don't use the alternate 0.01 step. If you do, you won't be able to hook wires to the
pin tie points.
Now we just need to begin wiring nets. Arrange the pieces so that there is as little
net overlaps as possible.
Primordial FT232RL breakout
To wire a pin (TXD) to a far point (the 4-pin connector for example), instead of
sending a wire half way across the page, we use net names. The green wire is not
physically seen on the schematic, but Eagle knows to connect the two points on the
layout because the two green wires have the same name.
Press F9 and click on pin 1 (TXD). Bring out the net a couple square widths and left
click again to end the net. Press Alt+F9 to name the net. Click on the wire you just
created. You should see a net name (like N$5) appear and be floating. Anchor it to
the wire and TX pin:
To change the name on the N$5 wire, press F4 (Name command) and click on N$5.
A window will appear - type 'TX' and press return. The TX pin should be correctly
labeled and we have a few of the schematic connections.
To rename a device (change U$1 to U1), press F4 and then click on the device you
want to rename. This also works to rename a net.
To change the value of a component (0.1uF to 10uF) press F5 and click on the
device you want to change the value of. To move a device, press F7 (move
command) and click on the device you wish to move. Now with a little renaming and
rearranging the various components:
We've thrown a 4-pin connector into the schematic and used a very stripped down
schematic symbol for the FT232R. For the purposes of this tutorial, we really only
care about VCC/GND/TX/RX - the bare minimum. If you need access to more of the
pins, use the more complete FT232R symbol and break them out!
Use the mirror command and rename the 4-pin connector (press F4 to rename a
device):
Eagle files / PDF
I probably could have wired JP1 directly to the various pins but I wanted to
demonstrate the net/name properties. This will also make it easier to label the pins
on the PCB. Speaking of which, if you have not already, click on the 'Board' button
to open the PCB editor:

All right! We've got the components onto a board and most of the nets connected,
time for PCB layout!
How to copy and paste in Eagle Schematic:
This is perhaps the most counter intuitive part of Eagle. As with any new technical
software, it's like learning a new language. Once you know the intricacies, you'll
love it.
To copy one thing within a schematic is reasonably simple. Click on the 'Copy'
button, then click on the thing you want to copy and that thing (component, wire,
net name) will be duplicated and floating under your cursor. Drop it wherever you
want it.
To copy a group of stuff within a schematic is completely wacky. First click on the
group command:
You are going to create a frame around the stuff you want to group together. Left
click and hold on one corner. Drag to the opposite corner. Now release the mouse
button. The items that are part of the group should now be highlighted like this:
Now click on the Cut button. I know you don't want to delete these items - this is
just how it works. Click on cut, move your mouse cursor to the middle of the group,
and left click. Nothing happened right? That's okay. The group of items has been
copied to the buffer. Now click on the paste button:
You should now have a copy of the group of items floating around. Drop these items
wherever you need them in the schematic, or hit escape to return to the schematic
window. I know, very odd but this type of group/modify steps comes in very handy
over time.

Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=108>

Lecture 9 - Eagle: PCB Layout


To learn how to use Eagle, we are going to create a simple breakout board for a
popular USB IC. The FT232RL is a USB to TTL serial converter. This section covers
the physical layout of the PCB.
We've got the schematic captured and the connections should be made correctly.
The next step is to arrange various components on a board and then send the board
files out to a manufacturer (also called a fabrication or 'fab' house).
Layout is an art and engineers make bad artists. It's all about the small polishing -
text labels, stand off holes, correct footprints. Just keep turning out PCBs and you'll
see your layouts improve dramatically with practice.
Before you do anything, turn on vector fonts! If you don't, your silkscreen text will
be off on every PCB you create:

From the Eagle control panel, click Options->User Interface


Select 'Always vector font'.
Above is a breakdown of all the different buttons in the Layout window. You can
view the name of each button by hovering over the button with your mouse. Many
of the short-cuts from the Schematic window still apply:
• Press escape at any time to stop the current action and return to the Layout
window
• F7 to move a part
• Alt+F7 to group a bunch together
• F3 to delete a part
• F4 to rename a part (change C7 to C2)
• F5 to re-value a part (change 0.1uF to 10uF, etc)
• F6 to smash a part (be able to move the name and value tags)
• F9 to start routing a wire
• Alt+F9 to rip up a wire
If you get this error while moving bits around:

This just means that you are trying to put a component outside of the allowed area.
With the Light edition of Eagle, you can only place components in quadrant I (upper
right quadrant), whereas the components show up by default in quadrant II (upper
left quadrant). Just move the parts to a positive X and Y coordinate and you should
be ok.
Starting with our current layout:
The first thing to do is correct the board outline. I don't know why Eagle slightly
offsets the default border.
Make sure you're on a 0.1" grid by pressing F10. Then hit F7 and hold control while
clicking near the origin. This will grab the frame corner and force it onto the 0.1"
grid. Make the bottom left corner sit at (0,0):

Do this for the other three corners bringing them in to make a 1.5x1.0" square
board size.
Now go to town bringing the components into the board area. Keep in mind the gold
color un-routed 'air' wires. The less twisted you make these by creatively arranging
your components, the easier the trace routing will be.
Remember:
• Press F7 to move a component
• Right click to rotate
• Hold control to grab a component at its origin
• Scroll wheel to zoom in/out
Hit the Ratsnest button from time to time to recalculate the air wires.
Here are the components arranged in a basic configuration. Another beef I have
with Eagle is the default colors for the various layers make it impossible to see what
is going to be printed on the silkscreen layer. Let's change the 'tPlace' layer to pure
white and change the 'tDocu' layer to lemon yellow.
Click on the 'Display' button, scroll down to layer 51 and double click on the gray
box next to 'tDocu':

Then click on the gray 'Color' box and change it to something interesting like lemon
yellow, then click ok. Anything you do on this layer will now be yellow. Do the same
for layer 21 'tPlace'.
Now this is starting to make sense! Anything in yellow is just there to indicate
physical size. The yellow part of the USB connector is only there to indicate that the
connector sticks over the edge that far. Only the white part of the USB connector
footprint will actually show up on the silkscreen print on our PCB. Anything in light
gray (tNames and tValues layers) will not print on the silkscreen layer. They're just
there for your own reference. We can of course change how the various layers are
processed (and include the value and name layers on the silkscreen) but this can
cause a lot of squeezing and hassle. It's up to you and your design but we will leave
the part indicators and values out of this layout.
The next thing we need to do, for all PCB layouts, is to add stand-off holes. These
holes will allow you to insert a simple screw and hold a stand-off in place. Without
standoffs, PCBs will sit uneven against a flat surface (because of the bumpy solder
joints protruding on the bottom of the board). Having a PCB sit flat against a surface
is also a bad idea electrically - I've sent $200 up in smoke because some bits of
clipped wire shorted against the bottom of my board when I was troubleshooting it.
I like to use 4-40 screws and 0.25" diameter plastic standoffs on everything. These
4-40 screws need a 0.13" diameter hole and the standoffs have a 0.25" outside
diameter that we will need to take into account. If you have not already done so,
add four of the 'Stand-Off' components to the schematic (and therefore PCB). This
component was created to couple the 0.13" drill with a keepout ring. This keepout
ring helps show were the screw head will fall. If you fail to take this keepout layer
into account, the screw will go through the hole, but the screw head may run into or
short components.
Throw four standoff holes around the corners of your board.
Ahah! Now I see why I made that keepout circle. You can see where the standoffs
would have run into the USB connector. Looks like we've got some bumping to do...

By using the group (Alt+F7) and the move (F7) commands, I increased the border to
1.5x1.2" which is a bit bigger than I would like, but for the purposes of this tutorial,
we're not going to stress tight packing of components - rather we want to stress the
basics for a good PCB. Notice how I flipped and dropped C3 and C4 down a bit? Time
to add labels!
A 'C2' label is handy when you're populating a board or when you're troubleshooting
a complex circuit, but on a day to day basis, you probably won't need to know
where C2 is. On the other hand, the TX and RX pins will probably be used every
time you use the board! You really should label anything that will be connected to
the outside world. To add a text label to a pin, click on the 'Text' button:

A window will pop up asking you what text you would like to add. Type 'TX' and
press enter. You will notice that the text may be appearing on an odd layer. Be sure
that you add text on the tPlace layer.

Drop down the layer menu and select tPlace for top silkscreen text
Once you've placed 'TX', press escape. Eagle will now show the text window again.
Enter 'RX' and press enter. Repeat for RX, VCC, and GND. When done, press escape
twice to return to the layout window.
In this case we have VCC/GND/TX/RX to label:

Make sure you add your labels to the 'tPlace' layer!

To check which pin is connected to which net, hit the eye button and click on a pin.
Checkout the text at the bottom of the Eagle window - pin 1 is VCC. Do this for all
the pins and arrange the labels accordingly. You should also take the font size down
to 0.05:

To change the font size, click on the Wrench ('Change' button), select 'Size', then
0.05. Now click on each text that you want to change the size on.
Labels in place and lined up
Try to get all the labels with the same vertical and horizontal alignment. This is a nit
picky aesthetic thing, but it shows on the final board.
You will have many board revisions. It's always good to add a date code to the
board so that you can match your files to the board version in hand. Add text to the
bottom copper layer to an inconspicuous spot. The easiest way to do this is to add
text to the top copper layer then hit the mirror button (you can also hit the scroll
wheel on the mouse to move the component to a different layer). This will
automatically mirror the text and drop it to the bottom layer.
6-3-07 mirrored, on the bottom copper layer, and underneath the USB connector.
There shouldn't be any signal traces in this part of the board so we're not wasting
space. You could add text to the bottom silkscreen layer but some fab houses don't
allow bottom silkscreen (it adds an extra printing step).
Also add some text to the top silkscreen layer indicating what the board is, what it
does, who made it, etc.
Above is the completed board ready for trace routing.
Many people swear up and down that an auto-router is a bad idea. It may be, but if
we're not concerned about trace impedance or high speed signals, an auto-router is
a great way to whip up protos. Spend your time innovating, not routing mundane
traces.

To auto-route the board, click on the 'Auto' button. The defaults are all fine except
for the 50mil grid:
Change the Routing Grid to 8 (our fab house uses 8 mil traces and spaces).

Demo board auto-routed. Eagle files / PDF


It's not immaculate, but it will work just fine and the router took under 2 seconds to
route. It would probably take me 5-10 minutes by hand. I will hand route sensitive
parts of certain boards, but this is a very simple proto.
Things to check on every layout:
• Date code
• Silkscreen title and pin labels
• Standoff holes
• All connections routed
• TX and RX routed correctly
• Print off 1:1 and check footprints
Routing TX and RX correctly? What does this mean? I can't tell you how many times
I've heard newbies say 'well my PCB would have worked, but the manufacturer
swapped the TX and RX pins'. No, the manufacturer did not swap them, the newbie
neglected to actually read the datasheet (RTFD!). Sometimes an RX pin is an input.
Sometimes an RX pin is an output. If you get it wrong, you'll look like a dunce. Read
the datasheet and verify that everything is kosher. In the case of our FT232RL
breakout, the TX pin is an output and RX pin is an input (pretty standard). I'm going
to change the silkscreen indicators to read 'RX-I' and 'TX-O'. This should remove any
doubt in my mind when I'm using the board a year from now - and so I don't have to
go digging up the datasheet.
The last thing to check - print off 1:1 means to print on paper and 1 to 1 scale of the
board layout. Then place the components on top the paper to verify that everything
fits their associated footprint.
Another quick note about printing layouts - this can be a great way to create an
assembly sheet. While you've got the PCB editor open, press Alt+F11. This will turn
off all the layers that are not pertinent to assembly. Print this, I normally scale it up
3 times, and hand write in what parts go where. Quick and effective way to create a
cheat sheet for PCB population. Pressing F11 will bring back the normal layers but
you may want to activate/deactivate a few others.
Now that we've got the board laid out, stand-off holes in place, date code in place,
and accurate pin labels, it's time to mash up the layers and create some gerber
files.
What's a gerber?
There are lots of different layout packages out there (Protel, Orcad, Eagle, PCB, etc).
One way or another all the PCB fab houses out there need a way to control their
machines to work with your layout files. The universal format is something called
Gerber Files. Basically these are txt files with coordinates that tell the PCB machines
to go to location X,Y and do something (drill, expose, etch, print, etc). Because
there are different layers to your PCB, you need to create different text files for the
different layers. This is where the Eagle CAM program comes into play.

Once you're good and happy with your PCB layout (there is no turning back after
you submit the files!), click on the CAM button to bring up the processor. This
window will allow you to do different things to different layers. Eagle comes with a
couple default *.cam files. The most common ones are the gerb274x.cam and
excellon.cam. I got tired of running two seperate processors. I am also a hold over
from Protel and a different naming convention so I created my own single file CAM
processor. You can snag it here. The sfe-gerb274x.cam is based on the default
Eagle file with a few tweaks:
• Layers are renamed for easier reading - top copper, bottom silkscreen, etc.
• All the mirroring is turned off - this will make gerber inspection much easier
• A top paste layer was added in case you want to create a solder paste stencil
• Excellon drill file is created along with the 6 magic layers
• Drill file is 2:4 Leading (remember this!)
What are these magical layers you ask of? Anytime you transmit a PCB layout to a
fab house, you need to pass them 7 files, and 7 files only:
• Top Copper (GTL)
• Top Soldermask (GTS)
• Top Silkscreen (GTO)
• Bottom Copper (GBL)
• Bottom Soldermask (GBS)
• Bottom Silkscreen (GBO)
• Drill File (2:4 leading - remember this)
What is this GTL, GTS? These are the file extensions that the CAM processor will
produce. A silkscreen is also called an 'overlay' (hence, GTO). And for your
reference, a soldermask is also called a solder 'stop layer' because the soldermask
prevents solder from being where it is not wanted.
Some fab houses will charge extra for a bottom silkscreen layer. You can just ignore
this layer if you need to. You will also see a GTP file extension. This is the Gerber
Top Paste file. You can use this file to get a solder paste stencil cut it you want. One
would think that a GTP file would be the same as the GTS (top soldermask file). But
no!
On the left, the soldermask layer. On the right, the top paste layer. The soldermask
layer exposes the pads and the vias. You wouldn't want solder paste in vias! So the
paste layer only has the SMD component pads exposed.
To create these layers, click on File->Open->Job

And select the sfe-gerb274x.cam file. Then click 'Process Job'. Some status bars will
blink by, and within a few seconds, you should have a handful of extra files in your
project directory:
The magic 7 gerber files
Something I highly recommend is to review the gerber files before submitting them
for fabrication. Viewing just what is going to the fab house can exposed potential
problems that were shrouded before by all the extra layers and graphics in the
Eagle layout window. There are some free viewers out there that will let you view
the gerber layers together. Most of the free viewers require you to enter an email,
require 15 seconds for them to advertise at you, limited to one layer, or other really
annoying limitations. Luckily, Viewplot still exists. This free program will let you
open and look at your layers easily and you don't have to fill out any silly forms to
get to the download link! Be sure to select the drill file type '2:4 Leading' to
matchup the holes to the layers.
Simple
But oh wait, what is that?

Silkscreen on top of a via


This silkscreen being broken up by the via is not a big deal. Mostly this is just to
show how difficult it can be to detect problems from within the layout program. By
viewing what you're actually submitting to the fab house, you can see exactly what
they are going to deliver - be it good or bad. Review your gerber files before you
submit! You'll save yourself time and monstrous amounts of money. If you want a
$50 coaster, I'll sell you a truck full.
Zip these 7 files together and shoot them off to the fab house of your choice
(Shameless Plug: we use BatchPCB). Depending on who you use and how deep your
pockets are, you'll have to sit on your hands for 1 day up to 20 days. What do I do? I
start other designs! While this board is being fabbed in 2 weeks, I create and submit
a new design 7 days into it. That way I always have a new PCB proto coming in
every few days. It's like Christmas every week! What am I getting this week? Is it
going to work? I can't wait to test out my new cat tracker!

With the magic of television, I can jump 20 days into the future and show you...

In the flesh
It looks great! Time to whip out some parts and the soldering iron.
Assemble your new board!
Soldering was not too bad. Silkscreen looks good. Standoffs look good. Time for
testing!
Always assume a proto will short out the first time you use it. Be very cautious and
be ready to kill power immediately. Plugging this board onto the computer - guess
what happens?

Uh-oh
What went wrong? Nothing is heating up. Nothing smoked or popped. The FT232 IC
doesn't seem to be enumerating onto the USB bus. But why? Let's check the
schematic one more time...
FT232 Breakout v1.0 Schematic
Son of a... This is why we prototype! Mistakes like this happens to the best of us.
What is the problem you ask? Checkout the GND pin on the USB connector. It's not
connected to anything. Without a ground connection to the board, no current can
flow, the FT232RL will never enumerate. The board is shot! Or is it?

The green wire fix


(I know the wire is not green, but this is the nick-name for an oops! fix) This is my
final thoughts on PCB layout - anyone can layout a PCB, but it takes a true magician
to get a bad PCB working. Scratch, cut, splice, and otherwise modify your PCB until
you get it working. This example was an easy fix. I've seen some really impressive
fixes over the years.
From the SFE PCB History Museum
Don't immediately throw up your hands and layout a new board. Instead, make sure
you get every bit of the functionality of your board working, by any means
necessary, and then make all the revisions. Otherwise, you'll constantly spin your
wheels with PCB revisions.
Things to remember:
• Be sure to save your schematic as a new file name: *-v11
• Be sure to update the date code on the board
• Be sure to update the silkscreen on the board

Updated v1.1 schematic with GND connection on the USB connector


Updated v1.1 board layout with new GND connection, updated silkscreen and date
code

Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=109>

Lecture 10 - Eagle: Creating a new part


You can dig around the Eagle libraries all you want. Very quickly you will discover
that you need to create a new part. This can be very daunting at first. The following
tutorial breaks down how we create a new part in Eagle. There are some
recommendations here that are good to follow, but we are by no means experts at
Eagle. This is going to be very long and painful, just try to get through it. These
basics will hopefully form the foundation of all your future project layouts.
You are welcome to use stock Eagle libraries but use them under extreme caution. I
rarely use other people's libraries. Trusting someone else' part or footprint can be a
sure fire way to render a pile of PCBs worthless. I've done this far too many times! It
takes lots of failures to get good at creating decent schematic parts and solderable
footprints. You will mess up, but you have to mess up before you can be good at it.
To get 5V out of a 1.5V battery, we use something called a DC to DC step-up
converter. This handy part is not in the stock Eagle library so let's create a new part
for this controller IC - the NCP1400 (datasheet).
The NCP1400 is a neat little step-up IC - we input a low voltage and get 5V out!
To start your first parts library:
Once the Library Editor is open, hit the Save icon and save your library with your
name on it:
Click on create a new symbol. Name it 'NCP1400':

Create a red box by clicking on the 'Wire' button:


Don't worry about centering the box at this time.
Key commands to try out:
• Scroll the scroll wheel on the mouse to zoom in/out
• Click the scroll wheel (on the main work area) and hold shift to move the
work area around
• If the work area image looks corrupt, just zoom in/out to refresh the area
Add 5 pins to the box:

Press F4 and click on a pin. Name them according to the datasheet.


Pins are named, but we need to clean up how this part is sized and where the
center is at. To grab the group press Alt+F7, click and hold, and drag from one
corner of the work area to the opposite corner - boxing in the pins and part:

Once you have everything selected (everything should be highlighted red), press F7
and right click to move the group over the center cross. In my example part, I the
right side was one block too far over so I sucked in the right side one square.
The image above shows the part centered and symmetrical.
• NEVER change the grid size in the library editor or in the schematic layout
editor. Leave it on 0.1inch steps and don't use the alternate 0.01 step. If you
do, you won't be able to hook wires to the pin tie points.
Name and Value tags are always nice. Click on the text button and type '>NAME'
and '>VALUE'. (Ok I lied. It's okay to use the alternate step size when moving
around non-critical items like text. Hold the Alt key down while your placing the
Name and Value tags to get them where you want them):

Once you have Name and Value placed, you'll notice that these are red when they
are normally gray in color. Be sure to modify what layer these two strings are on.
We need to change the >NAME tag to the Name layer, and >VALUE tag to the value
layer. To do this:
Click on the wrench, then Layer.. Choose the layer you'd like to change the object
to

Here is the final schematic part, centered and happy. If you want, you can change
the pin definitions to indicate which pins are inputs, outputs, pwr, etc. I find these
settings useful in a handful of situations. This is a simple enough part, we'll skip it.
Now for the footprint. Remember, when in doubt create your own footprint. Trusting
anyone else' footprint without scrutinizing it closely is a very bad idea. If you're
lucky, your datasheet will include a recommended footprint for the part you are
working with. If it does not, google for the words 'recommended land pattern SOT-
23' or whatever package you are looking for. The words 'land pattern' is the key.
Lucky us! The NCP1400 datasheet has a recommend footprint:
This takes some getting used to. There are two numbers from every dimension, and
not all the dimensions are indicated?! Lower left corner shows mm/inches meaning
the top number is the dimension in mm and the bottom number is that same
dimension in inches. Sorry folks, it's a metric world. More and more devices are
spec'd in mm only (connectors, ICs, etc). From the Library editor, click on Package
and let's start creating the footprint for this device. This is actually a pretty common
package type called SOT23-5, so let's use that name:

Throw down 5 pads:


Hmm, some of the layers are not showing - let's turn them all on:
Click 'All' and then 'Ok'. You should now be able to view the solder mask (in Eagle as
the 'Top Stop' layer) and solder paste layers (aka 'Top Cream' layer).
Now back in your datasheet you will find the width of each pad to be 0.7mm and the
height to be 1.0mm. Before we can go editing the pads, we need to put Eagle into
metric mode. Press Alt+F10 and you should see the coordinates in the upper task
bar switch to mm. To alter the size of the five pads to 0.7x1.0mm, click on the
wrench, then Smd, then '...':
You will then be prompted to enter the X and Y dimensions in mm with an 'x' in
between:

Remember the X dimension always comes first.


Now click on all 5 pads. All 5 pads should now be the correct size. I really prefer to
center the footprint with the center of the work area. This means we need to work
out the various dimensions:

Let's start with the easy pad - pin #2 will be located at (0,1.2). Before we can start
moving pads, we need to adjust the alternate grid so that we can get the the side
pads to 0.95mm. Click on the points/grid box:
Change the Alt: box from 0.1 to 0.05 and click on ok. Now lets move pin 2. In the
work area, press F7, then hold control and click on a pad:

F7 issues the move command. Holding control while clicking on a pad causes the
pad to try to center to the cursor (this way you know that the coordinates displayed
in the upper left task bar are displaying where the very center of the pad is at and
not where your cursor may have been off when you first clicked on the pad).
Because the pads are locked onto the 1mm grid, you'll notice the pad jump from
3mm to 4mm, etc. While holding control, hold alt as well. The pad should now jump
on the alternate grid of 0.05mm instead of 1mm. Important buttons to know:
• Again, the scroll wheel will zoom in/out
• Clicking the scroll wheel will drag the work area around
• Holding the shift key will allow you drag the work area further
To position this pad to (0,1.2) I literally had to:
1. Hold Control and click on the pad
2. Hold Alt, Shift, and control with one hand
3. Scroll in with the scroll wheel
4. Click+drag the scroll wheel to get the work area centered
5. Release Shift
6. Move the cursor to position (0,1.2) (Remember to hold alt!)
This sounds really scary but after creating two footprints, you'll have it down
without thinking about it.
Nifty
Press F4 and click on each pad renaming them to match the datasheet numbering:

Did you number them wrong? Double check. Make sure you get it right! We need to
add a dimensional layer to indicate the size of the device. This is different than a
silkscreen indicator. I like to use layer 51 (named 'tDocu' meaning top document
layer?). This layer will only be displayed while we're playing on the layout window
and won't show up on any production files. This allows us to display the physical
size of awkward parts, hopefully avoiding collisions between bulky parts when we
go to populate the PCB.
Why should be even care about these layers?

Here is our NCP1400 (label U4) next to three capacitors. See how crazy board layout
can get? Notice C1 is next to U4 but the distance between them looks ok? When we
add in the tDocu layer:

Whoa! That cap is way too close to the body of the NCP1400. You might be able to
get those two components soldered onto the board, but it would be a mash up job.
We need to know the rough physical outline of components during layout. To do
that, we need to add a frame to our footprint.
Before we add lines to our footprint to indicate the physical size of our part, let's
change the layer color - gray is a horrible color to try to see! Click on the 'Display'
button, scroll down to layer 51 and double click on the gray box next to 'tDocu':

Then click on the gray 'Color' box and change it to something interesting like lemon
yellow, then click ok. Anything you do on this layer will now be yellow.
Click on the 'Wire' button. Select layer 51 (this layer will be yellow in the drop down
box the next time you close/open the Library editor).
You should now be able to lay down yellow lines. Put four of them down in a box:

Press escape to stop drawing. Now we need to move the edges of the box to the
outside edge of our part. Checking the datasheet again:
Ahh manufacturing tolerances. They can't really tell us how big the B and A
dimensions will be, so I always pick a value in the middle of the min/max. A = 3mm,
B = 1.5mm. Remember we have to center the frame so the upper right corner of
the frame will be at (1.5, 0.75).
Now go back to the footprint, press F7 to issue the move command. Hold the control
key and click on the upper right corner of the frame. When you do this, the 1 pad
may light up - this is because Eagle does not know which part you are trying to
move - the pad or the line? If you left click, Eagle will begin moving the 1 pad
because it is highlighted. Right click and the frame should highlight. Now left click
and you should be moving the upper right corner of the frame. I know, its really
confusing at first. It's actually really handy once you're used to it!

Once you've got the corner at (1.5,0.75), left click to anchor the corner at that
location and adjust the other three corners.
I can almost see it now! Notice how the part extends past the edges of the pads? If
we would have put a component (like an 0603 resistor) next to pads 3 and 4 the
two component may have been bumping into each other. Electrically, the layout
would have been fine but when we would go to populate the PCB, this regulator
might have been right up against the neighboring part.
Finally, I highly encourage you to add a bit of silkscreen to this part. What does a
board look like without silkscreen?

Can you tell where the components go and how they are supposed to get oriented
without a silk indicator? I can't.
Add a little silkscreen and it's suddenly very apparent where the NCP1400 is
supposed to go.
When you get a PCB with nothing but silver pads, the 4/5 pads on this part look a lot
like the spot for an 0805 capacitor! Select layer 21 tPlace. You may notice this layer
is gray as well! I hate gray. Re-color this layer to white. When you get your PCBs,
the silkscreen is white, right? Might as well make them agree.

I zoomed way in, held alt to get onto the alternate grid, and ran the line from (-0.25,
-0.75) to (0.25, -0.75). You really do not want to put silkscreen across your pads.
This will negatively affect how the pads react to solder. It would foul a board or
anything, it's just best to keep the silkscreen layer away from pads. You could butt
the white line right up against the pad, but the silkscreen layers has the worst
tolerances and the greatest skew. The white lines in your beautiful layout could end
up a couple mm to the left or right when you get your PCBs from the fab house.
Besides, 0.25 is such a nice start/finish number!
Create silkscreen lines for the sides as well. Don't worry about itty-bitty silkscreen
lines inbetween the upper pads or the little corners. Very small silkscreen lines will
either be ignored by the fab house or else they will just flake off.

When we laid out the tDocu layer, the wire thickness was 0.127mm or 0.005".
0.005" is also pronounced as '5 mil'. Time and time again, you will hear that fab
houses can handle 8 mil traces and 8 mil spacing for their basic service (aka their
cheap service). This means that no trace can be less than 0.008" in thickness and
two traces cannot be closer than 0.008" to each other. Well guess what thickness
our silkscreen traces are? The 5mil tDocu lines don't matter because they will not
be printed or fabbed, but the 5mil silkscreen traces may give some fab houses fits!
The fab house may increase the line thickness to 8mil, they may try to print the
5mil line as is and have it come out very thin with no weight, or they may not print
it at all! Let's alter the thickness of the silkscreen lines to 8mil so that we are kosher
with any fab house.
We're switching back to Imperial units! Press F10. Next click on the wrench, width,
and '...':
Why doesn't Eagle have 8mil listed? I have no idea. Enter 0.008 into the box
prompt. Click on the three silkscreen lines:

It looks a bit odd, but once you see it on a PCB, it will look great! The last things we
need to do (I promise!) is to add a >NAME and >VALUE tag. Review the schematic
component section to see how to do this in detail. Add two strings ('>NAME' and
'>VALUE') and then modify the layers for these two strings to tName and tValue
respectively.

And we're done with the footprint creation for this one part! Now you see why
engineers and companies hoard their libraries. The first couple footprints you create
will be totally botched and will probably kill your PCB layout. But once you get a part
created, and you use it once or twice successfully, the part will be proven and you'll
never have to worry about it again! With a collection of 20-30 known good parts,
you'll be able to whip up very reliable PCBs in surprisingly little time.
To finish this part in our library, we need to relate the pin numbers on our footprint
to the pin identifiers on our schematic part. Save your library and click on the
Device button:

Name the new device NCP1400 and then click on the Add button:
Drop the schematic part in the center of the work area. Hit escape twice to get rid
of the part window. Now click on the 'New' button in the Package area:
Double click on the SOT23-5 listing.

Notice the yellow exclamation point in the Package area? This means that a
footprint is associated with the schematic part but the pins have not yet been
assigned. Double click on the 'SOT23-5' text in the Package area:
Review page 1 of the NCP1400 datasheet to know what pins connect to what pad
numbers:

Double clicking on a given name on one side will assign it to the highlighted choice
on the opposite side. You've done a great job up to this point! Double check that
your pad assignments are correct!
Right click on the Package name and click on Rename. Various different footprints
can be associated with any given schematic part. To differentiate between parts,
you can give the pin assignments different names. I mis-use this function a bit. I
often name variants 'SMD', 'A', 'B', '8', '10', or in this case 'NCP1400'. Pick your
poison.
It's ok if you do not give this device a variant name, but if you leave the default
variant name as " and then try to add a new pad assignment you will get the
"Package variant " already defined!" error:

Just rename one of the variants to a different name so that Eagle can add this new
variant with the default " name.
Now let's add this newly created part to our schematic. Close the library editor and
go back to the Eagle Control Panel. Click on File->New->Project. Name this new
project - in this example we'll do 'Simon'. Right click on the Simon project and
create a new Schematic:

The schematic editor should open. Now go back to the Eagle Control Panel and open
your new Library:
You should see the NCP1400 part and the SOT23-5 footprint. Highlight the NCP1400
part and in the right screen click on ADD. The schematic editor will pop up allowing
you to place the NCP1400.
And that's it! You now know how to create a component from scratch. Be sure to do
a 1 to 1 print of your layout before sending it to the PCB fab house to verify all the
parts against their respective footprints.

Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=110>

Common Mistakes, Tips and Tricks


1. All grounds need to be connected together.
2. TX/RX loop back trick: When in doubt of a serial conversion circuit,
short the TX and RX pins together to get an echo.
3. Normal length wires for breadboard connections: Don't use a 9" wire
where a 2" wire will do.
4. Minimize short potential in your breadboard wiring: Don't expose an
inch of wire from the insulation if all you need is 1/4".
5. You will learn best when you have a *simple* project to work on. Don't
create the 'house-pet robot' just yet.
6. Google is, of course, your friend. When you don't know, go do some
research.
7. for(x = 0 ; x < 400 ; x++) : If x is defined as an 8-bit integer, the for
loop will loop forever!
8. Soldering basics: Wet your @#$% sponge.
9. Take your time with ground plane solder joints. Do not be fooled by a
cold joint.
10. Never trick yourself into thinking you're that good. Print out a 1:1 and
compare the footprints!
11. Check that TX and RX are wired correctly to all peripherals. TX/RX
swap is the one of the greatest causes of PCB failures.
12. When laying out a PCB with SMD micros, don't forget to include the
programming port!
13. Don't run silkscreen across pads.
14. Connector PCB footprint mis-numbering: always check the pin number
on your connector - they can have very obfuscated schemes.
15. In Eagle, use vector fonts only!
16. Review your gerber files before submitting them.

Pasted from <http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=111>