Getting started with AVR and C

I am quite used to playing with PICs and JAL v2. I use the PicKit3 for programming and debugging.

Now I want to learn C and AVR. I thought it may be a good idea to do both at the same time.

I already have a device with an ATMEGA168 in it. I want to write my own firmware for this device.

I have installed the Atmel Studio 6 and downloaded the data sheet for the '168. Now I need a programmer/debugger. This is purely for hobby use, so I can't blow too much money on it.

So, I have a couple of questions:

  1. Which programmer/debugger should I buy? The JTAGICE3 is acceptably priced and appears to be very capable. Any reason to not get that one?

  1. Where do I start learning C? Is there a good online tutorial somewhere? I'd also be willing to buy a book. Is there one that stands out as the best?

Reply to
Robert Roland
Loading thread data ...

If you want to move on to 32bit AVR, no.

If you want just 8bit AVR, try Atmel AVR Dragon (ATAVRDRAGON)

AT $49 vs $99 its easier on the wallet.

There are so many projects on the AVR, using the WINAVR compiler, you can find a project your interested in copying and read the code they built.

Google WINAVR to find where to download the compiler. There are good tutorials on getting the compiler to hook up to the Atmel Studio 6.

Lots of FREE C books out there as well.


Reply to

The AVR dragon is cheap and does it's job well. Don't know about the JTAGICE3, can't give you a reason why to buy it or not.

There is a book by Ivor Horton about C, a very thick one, that is not bad. I am sure that there are many good tutorials around but also that there are tons of crappy ones and especially for someone who is new to the topic it may be difficult to distinguish between them, that way you run the risk of loosing much time (it is never really wasted but when there is a shortcut why not take that), perhaps someone can point you to a good one that he or she has read him or herself. Most books about C however are about writing pc programs and not firmware for an AVR or other embedded devices. Off course the language remains the same but the language itself is not complicated, the most important thing that one is doing when programming is glueing library things together with own code. Getting to know the libraries is what takes up most time. The libraries that one uses in an embedded program often are often very different from the ones that one would use to create a GUI based pc program. But this is something that one learns when walking the path, seeking on the web for info when needed. So I think I would recommend the book by Ivor Horton ("Beginning C: From Novice to Professional" by Apress) to start with and then just dive into deep water by setting yourself certain goals and just start working on them, looking for info and/or help when you need it.

Programming AVR's is great fun, I like it very much and I wish you a lot of joy. Getting to know the basics about C may be a bit boring in the beginning but when you get the hang of it, creativity will find it's way into your work and that's were the real fun starts. By the way, C also is very much fun, it is my favorite programming language. When you know assembler (which I suppose you do from the PIC), you will recognize many things.

Yours sincerely, Rene

Reply to

If you were anything other than an accomplished assembly programmer I wouldn't make this suggestion. But you are, so here goes:

First, get yourself a copy of Harbison and Steele's "C, A Reference Manual". It _will not_ teach you how to program in C from scratch. It _will_ show you what the C compiler does (H & S are compiler writers) and what is ANSI C vs. your compilers peculiarities and extensions.

Second, look for projects that already work. Some of the code will be good, some will be bad, so review what you find. What you're really looking for is help in getting C working in a bare-bones environment.

Third, figure out how to get your compiler to emit assembly language instead of (or in addition to) object code. If you already code in assembly, then nothing will teach you C faster than looking at what the compiler generates from what you type in.

Tim Wescott 
Control system and signal processing consulting 
 Click to see the full signature
Reply to
Tim Wescott

Here is a demo for programming PIC/AVR and wireless.

formatting link

Stay tune, more coming up.

Reply to

You say you want to learn. Ask yourself why. What are you gonna do with the knowledge when you get it? That can have a huge impact on your path. Makes little sense to learn how to program an AVR if your goal is to land a job programming a PC. With the AVR, you're more concerned about accessing the hardware directly. With a PC, you're more likely to need to manipulate a database.

Electronics is a hobby for me. I write PC programs with visual basic. I learned to write PIC programs with PICbasic. Both languages just work. They require very little configuration. And lots of macros/subroutines exist to do your bidding. You configure it with checkboxes.

My projects have evolved to building hardware interfaces and real-time stuff on a PIC that's connected to a PalmIII programmed in "dialect" that does the heavy lifting and touch GUI. I never attempted to do floating point math on the PIC...that's what the Palm is for. My development board has a character LCD and keyboard, but I haven't used them in years. All my programs have inline assembly code and are interrupt driven. I've found that software simulation is useless. Hardware debugging that has ANY impact on the program flow is more disruptive than helpful. The result is that I need a device programmer that makes it trivial to change the code and try again. A serial bootloader does that nicely. JTAG should do that if the required pins can be isolated. I've found a logic analyzer helpful debugging the relationship between some input and the failure symptom.

On several occasions I sought to learn C. First with the PIC, the MSP430 and then Arduino.

The C language is not difficult. If you can program in any language, C is a matter of different syntactical details. My difficulty with C was that C can't do much. It's all about the libraries. Coming from a BASIC background, I found it annoying that I couldn't even concatenate two strings without a library function call. On the surface, it's not difficult the second time you do it. The difficulty is determining that you need a function call, determining which library contains it, where to get it, how to include it with the correct parameters. No big deal the second time you do it. Pile up a dozen of these decisions, then try to figger out why it don't run. There are just too many unfamiliar development details to start from scratch. I also found that C took a lot more memory recall. I kept having to look up stuff that I hadn't used recently.

What the newbie needs is a set of example programs. "Hello world" ain't gonna do it. Code snippets ain't gonna do it. I needed FULL programs that accessed the internal hardware functions of the chip with all the little details, includes, libraries and configuration details for the specific toolset already configured to compile and run.

I messed around with the gcc microcontroller toolset. Never found the libraries I needed or any full tutorial on how to get all the tools installed and working. Lotsa tutorials on pieces, just not how to make it all work together.

A process that took one line in PIC basic looked like it would take a LOT of work in C. Those built-in functions really simplify stuff.

Toolsets that claim to just work cost big bucks. Available free demo versions are an option if the limits are acceptable.

In my case, my attention span was shorter than the time it took to get a FREE development environment up and running. And it didn't see where it gave me any more capability than I had with the PIC. Motivation has a lot to do with success.

I suggest you learn the basics of C on your PC. Maybe port to an AVR simulator. Then you'll be in a much better position to determine what hardware you want to buy. Sounds like the long way around, but I bet you get there faster and pull out less hair.

Sorry, I can't help with more info. I gave up before I found anything FREE I could use. The devil is in the details... the details that everybody knows...except they're not mentioned.

Reply to

Don't discourage someone trying to learn. You'll never know when it will be useful, even with limited capabilities like AVR. It's useful because the hardware is cheaper and lower power.

For the project i posted, there are four development environments:

  1. WinAVR/avr-gcc low end devices
  2. MPLab/mips-gcc coordinator
  3. MSVC++ bootloader/monitor
  4. Android ADT remote interface

All are necessary to put things together.

formatting link

Reply to

Apart from using a "hardware" programmer, there's an option to use a program that will interact with the MCU by directly "bit-banging" a hardware PC port, such as RS-232 ("serial port") or IEEE 1284 ("parallel port") one. Naturally, for RS-232 one'd need a MAX3232 (MAX232, if only 5V operation is necessary), or a similar IC.

The AVR serial programming interface is just four lines wide: /Reset, Clock, Data-to-Device (MOSI), Data-to-Host (MISO.) Unfortunately, /three/ of them are to be driven by the host, while MAX3232 provides only two level converters for each direction (and, generally, only two PC RS-232 lines are suitable for bit-banging.) So, a typical circuit would use a resistor and a Zener diode on the TxD RS-232 line for /Reset. For Clock and MOSI, RTS and DTR are used, while for the MISO line, either of the device-to-host lines (RI, DCD, DSR, CTS) may be used.

For the software, my preference is AVRDUDE [1]. Naturally, it allows for an arbitrarily-wired serial bit-banging dongle. For instance, the one I use is wired as follows:

--cut: avrduderc -- programmer id = "msiprog"; desc = "Modified Lancos SI-Prog "; type = serbb; reset = ~3; # /TxD sck = 7; # RTS mosi = ~4; # /DTR miso = ~8; # /CTS ;

--cut: avrduderc --

formatting link
FSF associate member #7257
Reply to
Ivan Shmakov
[Cross-posting to news:comp.lang.c, in the hope that someone could provide more suggestions, or correct me on C.] [...]

Frankly, I don't quite understand how did I learn C myself. FWIW, there were hardly any good book on that that I've read.

Two aspects of C are probably to be highlighted:

  • first of all, unlike some other, and higher-level, languages (like Pascal, BASIC, etc.), C has a very concise set of syntactic constructs; most of the power lies in libraries, and should you end up using AVR Libc, be sure to check its reference manual [1] (it isn't as good as the GNU C Library manual I'm using for the most time I need information on C, but it's still useful);
  • the C constructs tend to be translated into assembly in a rather straightforward manner (unless advanced optimization is involved, that is); consider, e. g.:

int8_t i; /* not necessarily translated; may force the compiler to "allocate" a register (say, r7), or a memory cell */ i = 3; /* ldi r7, 3 */ i += 2; /* adi r7, 2 */ i++; /* inc r7 */ if (i < 9) { /* cpi r7, 9 ; brge else_a */ int8_t j = 5; /* ldi r8, 5 */ while (j >= 3) { /* while_a: cpi r8, 3 brlt end_while_a */ PORTB ^= 1; /* in r9, PORTB eoi r9, 1 out PORTB, r9 */ } /* jmp while_a end_while_a: */ } /* else_a: */

Not to undermine its value, but as could be seen (I hope) from this example, for the most part, C only manages registers and memory (including function calling conventions) while the rest of its /syntax/ is comparable to that of a library of assembly language macros of some sort.

A cheat sheet for most of the C operators would probably be something like the following (where a, b, c, ... are either numeric literals, variable identifiers, or expressions.) Note that whenever all the operands are integer, an integer operation is performed. (So, 7 / 3 is 2.) The result is as wide as the widest of the operands. (So, i + j is 0 if i is 255, j is 1, and both are declared to be of the 8-bit unsigned integer uint8_t type.)

Operation Value Side-effect

Operations free of side-effects

  • a a - a - a * a the value of the memory cell at address a & a the address of a (must be an "l-value") ~ a bitwise negated a ! a 1 if a is 0, 0 otherwise a, b b NB: a is evaluated first, its result discarded. a + b a + b a - b a - b a * b a b a / b a / b (quotient of) a % b remainder of a / b a & b a (bitwise and) b a | b a (bitwise or) b a ^ b a (bitwise exclusive or) b a > b a times 2 ^(-b) (shift right) a < b 1 if a is less than b, 0 otherwise a > b 1 if a is greater than b, 0 otherwise a == b 1 if a is equal to b, 0 otherwise a = b 1 if a is greater than or equal to b, 0 otherwise

Conditional operations

a && b a is evaluated; if a is non-zero, the value is b; otherwise, the value is 0, while b is not evaluated at all a || b a is evaluated; if a is zero, the value is b; otherwise, the value is a, while b is not evaluated at all a ? b : c a is evaluated first; if a is non-zero, the value is b; otherwise, the value is c; the other ("unused") expression is not evaluated

Operations with side-effects

NB: a must be an "l-value" a++ a a set to a + 1 a-- a a set to a - 1 ++a a + 1 a set to value --a a - 1 a set to value a = b b a set to value a += b a + b a set to value a -= b a - b a set to value a *= b a b a set to value a /= b a / b a set to value a &= b a (bitwise and) b a set to value a |= b a (bitwise or) b a set to value a ^= b a (bitwise xor) b a set to value a = b a times 2 ^(-b) a set to value

Naturally, both "=" and "," can be "nested", thus:

for (a = b = 0, c = 5; c > 0; a++, b++, c--) { /* ... */ }

To note is that the for () form is just a short-hand for a specific while () loop. For instance, the for () statement above can be rewritten as follows:

a = b = 0, c = 5; while (c > 0) { /* ... */ a++, b++, c--; }

Thus, the only convenience of for () is that it allows for the "at-the-end-of-the-loop" part to be written above the loop body itself (i. e., together with the loop condition.)

One more thing to note is that there're two basic contexts: the statement context, and the expression context. The switch from the former to the latter usually takes place in obvious places, while it isn't possible (in standard C; AFAIK) to switch from the latter to the former. E. g.:

/* statement context */ while (a < 5 /* expression context */) { /* statement context */ b = 4 /* expression context */ ; /* NB: cannot switch back to the statement context, like: */ /* c = while (b > 0) { /* ... */ } ; */ }

As one may need a conditional operator in either context, C has both the ?:-operator (see above), and (perhaps a more conventional) if ():

if (a) { /* the code here will be executed iff a is non-zero */ } else { /* the code here will be executed otherwise */ }

The { }-grouping is only necessary if more than one statement is needed as the body; otherwise, it may be elided, like:

if (a) b = c;

This allows for convenient nesting, like:

if (a) { /* ... */ } else if (b) { /* ... */ } else { /* ... */ }

A similar idiom is possible for the ?:-operator just as well. Consider, e. g.:

a = (b ? c : d ? e : f);

which is not dissimilar to more verbose (and error-prone):

if (b) { a = c; } else if (d) { a = e; } else { a = f; }

An example program for an AVR could be as follows.

#include /* for PORTB, DDRB, etc. */ #include /* for _delay_ms () */

/* global variable declarations; not necessary in this example */

static void blink_led (void) { PORTB ^= (1

Reply to
Ivan Shmakov

Possibly the best, certainly the first, book on C is "The C Programming Language" by Kernighan & Ritchie.


Robert Roland wrote:

Reply to

This is not completely correct in general. For instance if you replace the /* ... */ with continue; then the for loop jumps from the continue statement to the increment clause of the loop, but the while loop jumps to the beginning of the loop body (causing an infinite loop).

Reply to
Richard Damon

I'll have a look...

No the return will be of type int in that case. The rules are rather involved, but the gist of it is that everything "smaller" than an int gets converted to an int. When the types involved are int or larger, both get converted to the larger type. Mixed signed and unsigned types generally result in the signed operand being converted to the type of the unsigned operand (after promotion).

The standard takes pages to describe these rules, so there is no way I can summarise them here with 100% accuracy. Given that you summary is not short, it might be worth including them. You'd then need to say to which operators they apply (for example they don't apply to the shift operators).

This rather reinforces a view of C are lower-level than it really is. The result might not square with how people think of a memory cell (for example, if a is a function pointer, or when it is pointer to a struct type).

You don't talk about array the indexing operator, [], not the function call operator, (). there are others, too, like sizeof and cast operators. In tabular summary, I don't think it hurts to be complete.

These ones are tricky because of all the corner cases (a shift equal or greater than the operand size, a shift of a bit into the sign position, a right shift of a negative quantity). In a summary like this may just a footnote to "beware".

Yes and it might help to say which of the expression yield and lvalue. For example, you can write ++*a but not ++!a. It's might well be obvious, but you could have a column for "is an lvalue".

a %=b is missing. But maybe it's better to generalise: a op= b and say what op can be?

In most tables of operators, you see both priority and associativity. Assign ment does not yield an lvalue, so a = b = 0 only works because = associates to the right a = (b = 0). Most C binary operators associate to the left (i.e. a - b - c means (a - b) - c).

You could make a really rich summary table that shows priority, associativity, whether the expression denotes an lvalue and what happens to the operands (are they just promoted as for the shift operands or are the "usual arithmetic conversions" applied as for + and *). I can see why you would want to avoid too much detail in a simple explanation like this, but it does seem like a useful thing to do.

Provided that /* ... */ contains no continue statements (except as part of a nested statement of course).

A sad omission for fans of BCPL!

You will find disagreement about that parenthetical remark in comp.lang.c.

Reply to
Ben Bacarisse

Wow ! I last programmed in BCPL in late 1977. And I still miss this construct ! Though I don't miss the Lvalue/Rvalue persnickity business (though BCPL wasn't as silly as BLISS).

Thanks for the memories, See ya, Dave

Reply to
Dave Nadler

WINAVR was the name of the package of the gcc compiler toolchain for the AVR, along with libraries, an editor, and a selection of utilities as a ready-to-install package for Windows. With Atmel AVR Studio 4 and before, you could set up AVR Studio to work with the toolchain from WINAVR.

But now the gcc toolchain is provided with Atmel AVR Studio. You don't need to get WINAVR separately - indeed you should not do so, because it has not been updated for a long time. When you use the "built-in" compiler in AVR Studio, you are using gcc already.

Most projects for "WINAVR" will work fine with recent versions of AVR gcc in AVR Studio 6, though there may be small differences.

(The AVR gcc toolchain is also available from Atmel without AVR Studio, for Windows and Linux, and of course you can put together your own avr gcc toolchain if you want. But the package along with AVR Studio is going to be the simplest way for most users.)

Reply to
David Brown

I'll second that - in fact it's not only the best book on C but the best book introducing ANY programming language.

(But for embedded stuff on an AVR it's not the whole story !)

Michael Kellett

Reply to






Reply to
Nick Keighley

useful, even with limited capabilities like AVR. It's useful because the hardware is cheaper and lower power.

Well, when you snip the conclusion... Life is all about priorities.

I'm downloading the AVR Studio 6. Looks good on paper, we'll see how the function libraries look. I've been really spoiled by PICBasic that hides all the quirks of the PIC and automagically configures I/O and formats I/O data...but I do like the AVR architecture better.

The OLIMEXINO-32U4 board looks good too. I'm still fighting with my cheaper side about paying $10 shipping on a $16 device that I don't really need. Be interesting to see which side wins. ;-)

Reply to

For some types of embedded programming, debugging that interrupts the flow of operation will not work. For example, you don't want to set breakpoints in the middle of a motor controller algorithm. For other types of work, disruptive debugging is fine. And simulation is often very useful - don't generalise from your limited experience.

The rest of the programming world manages to vast amounts with the C language - with and without libraries. I've done professional embedded programming for 20 years, and I can count on one hand the number of times I've wanted to concatenate two strings on a small embedded system.

If the only tool you are familiar with is a hammer, then you'll find it very difficult to use a screwdriver properly. If you come from a Basic background, and try to write your C systems as though C was "a bit like Basic, but can't do strings", then you will obviously have a lot of difficultly.

There are /hundreds/ of "gcc microcontroller toolset" packages available

- because gcc supports dozens of different targets, and there are lots of people making them. So such a blanket statement makes no sense.

In particular, there are gcc-based toolsets that are hard to install, and some that are easy to install. All come with at least basic libraries, but some come with more advanced ones. Some come with ready-to-use debuggers, editors and IDEs, others expect you to provide them yourself. Some come with top-class commercial support (at a price), others are entirely free and provide top-class free support. (And others provide poor support, either free or paid-for.)

In this particular case, AVR Studio 6 comes with a gcc toolchain. So assuming you are using Windows, the "tutorial on how to get it all installed and working" is "Download AVR Studio 6 from Atmel's website. Install it like any other Windows program by pressing "Next" a lot". It does not get any easier.

I don't know where you are getting your information - I suspect it is from very limited or very biased experience. There /are/ toolchains that cost big bucks - and there are some toolchains (for some targets) that are /worth/ big bucks. But no one ever claims that "big bucks" means the toolchains are easy to use - and people seldom claim that they are easier to install or use than free toolchains (at least, ready-packaged free toolchains). People who are willing to spend big bucks on tools are willing to spend time learning to make the most of them - they are not looking for "click and drool" interfaces.

Reply to
David Brown

MK wrote in news:mpqdnQCeHpt0kC

Thirded, but for most embedded stuff one specifically wants the SECOND EDITION which was rewritten for the ANSI C89/ISO C90 standard. That's much closer to the dialect of C many cross-compilers for small embedded systems use.

Also see "The C Book" (free, online, ANSI C89/ISO C90) - not quite as clear as K&R but pretty good indeed.

 Click to see the full signature
Reply to
Ian Malcolm

for me

are the same one call "r7", "i" and are the same

for the remain i possibly prefer my macroized part of the right side

than in the right side one can controll better the stack...

Reply to

ElectronDepot website is not affiliated with any of the manufacturers or service providers discussed here. All logos and trade names are the property of their respective owners.