
In the last installment of our tutorial series we built a simple circuit on a breadboard and programmed an ATmega168 to make it run. That proves that you know how to follow directions, but the eureka moments of doing everything yourself are on the way. This time around you will get down and dirty with the datasheet, learning where each line of the sample code came from, and give your recently installed compiler a test drive. We will:
- Talk about bitwise operators and how they work when coding for microcontrollers
- Discuss C code shorthand
- Review the sample code from Part 2 and talk about what each line of code does
- Learn to compile code
Prerequisites
- You must know something about C code. The ability to read it is probably good enough, Google can help you with the rest as you learn.
- It helps if you have a text editor that includes syntax highlighting. I’m purely a Linux user and I like to use both Kate and Gedit depending on my mood. But I also use nano from the shell quite frequently. This is a tool and your choice is purely personal preference.
- Grab the sample code from part 2 of the series. I’ve embedded it below but you may want it in a separate windows for reference.
- Datasheets; the instruction manual for hardware. Grab the datasheet for the ATmega168 as I’ll be referencing specific pages as examples. Knowing how to look up information in the datasheet and turn it into code will make it easy for you to use any chip in the AVR family.
Even though we’ll be writing code in the C language, we’re quite close to the hardware when programming microcontrollers. Because of this you must understand bitwise operators. Not just kind of, not*intuitively, you should know them well enough to teach them to someone else without looking it up.
Hands down the best*explanation*I’ve ever come across is by [Eric Weddington], who also co-authored the makefile that came with my example code. It is also known as Programming 101. Read it, know it, love it. But I’ll try to give a quick*crash*course for those to lazy to read his whole lesson.
Code Symbol Logic Function | OR & AND ~ NOT ^ XOR Shift Right
The list above shows all of the code symbols and their logic operation.
<ul> OR – true if either or both bits being compared are 1
AND – true only if both bits being compared are 1
NOT – results in the opposite of a value (~1 = 0, ~0 = 1)
XOR – exclusive OR… true if one bit being compared is 1 but false if neither or both of them are
Shift Left – moves bits left within a binary number. (1