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:
- 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.
- 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.
- 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.
- External Resonator – A resonator is a bit cheaper than an oscillator but has worse tolerances.
- 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,320MHz crystal while your neighbor has a 15,999,680MHz. 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 anoscillator. 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:
- Crystals are a bit expensive. $0.25 compared to $0.10 of a resonator.
- They cannot be made as small as a resonator (crystals take up more PCB area).
- 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.
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):
- avrdude -p m168 -P COM1 -c ponyser -U lfuse:r:-:h -U hfuse:r:-:h
- PG2 (parallel):
- 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 = 0×62
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 0×62 (0b.0110.0010) to 0xE2 (0b.1110.0010). Now we splice this into the previous read string and switch from read to write.
- 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:
- When the ATmega168 is in reset = ?
- When the ATmega168 is running with 1MHz internal osc = ?
- 8MHz internal osc = ?
- 16MHz external osc = ?
A great resource that we use religiously is the AVR fuse calculator:
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.