EmbeddedRelated.com
Forums
The 2024 Embedded Online Conference

Getting started with AVR and C

Started by Robert Roland November 24, 2012
On 11/24/12 4:18 PM, Ivan Shmakov wrote:
> for (a = b = 0, c = 5; c > 0; a++, b++, c--) { > /* ... */ > } > > To note is that the for () <statement> 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--; > }
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).
Ivan Shmakov <oneingray@gmail.com> writes:

>>>>>> Robert Roland <fake@ddress.no> writes: > > [Cross-posting to news:comp.lang.c, in the hope that someone > could provide more suggestions, or correct me on C.]
I'll have a look... <snip>
> [...] 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.)
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).
> Operation Value Side-effect > > Operations free of side-effects > > + a a > - a - a > * a the value of the memory cell at address > a
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).
> & a the address of a (must be an "l-value") > ~ a bitwise negated a > ! a 1 if a is 0, > 0 otherwise
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.
> 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 left) > a >> b a times 2 ^(-b) (shift right)
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".
> 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 less than or 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"
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++ 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 is missing. But maybe it's better to generalise: a op= b and say what op can be?
> 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 > a >>= b a times 2 ^(-b) a set to value > > Naturally, both "=" and "," can be "nested", thus:
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.
> for (a = b = 0, c = 5; c > 0; a++, b++, c--) { > /* ... */ > } > > To note is that the for () <statement> 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--; > }
Provided that /* ... */ contains no continue statements (except as part of a nested statement of course).
> 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) { /* ... */ } ; */ > }
A sad omission for fans of BCPL!
> 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):
You will find disagreement about that parenthetical remark in comp.lang.c.
> if (b) { > a = c; > } else if (d) { > a = e; > } else { > a = f; > }
<snip example> -- Ben.
On Saturday, November 24, 2012 5:12:09 PM UTC-5, Ben Bacarisse wrote:
> > 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) { /* ... */ } ; */ > > } > > A sad omission for fans of BCPL! > > Ben.
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
On 24/11/12 17:55, hamilton wrote:

>> 2. 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? > > 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. > > hamilton
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.)
On 24/11/2012 21:49, dbr@kbrx.com wrote:
> Possibly the best, certainly the first, book on C is "The C Programming > Language" by Kernighan & Ritchie. >
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
On Nov 24, 9:18&#4294967295;pm, Ivan Shmakov <oneing...@gmail.com> wrote:
> >>>>> Robert Roland <f...@ddress.no> writes: > > &#4294967295; &#4294967295; &#4294967295; &#4294967295; [Cross-posting to news:comp.lang.c, in the hope that someone > &#4294967295; &#4294967295; &#4294967295; &#4294967295; could provide more suggestions, or correct me on C.] > > [...] > > &#4294967295;> 2. Where do I start learning C? &#4294967295;Is there a good online tutorial > &#4294967295;> somewhere? &#4294967295;I'd also be willing to buy a book. &#4294967295;Is there one that > &#4294967295;> stands out as the best? > > &#4294967295; &#4294967295; &#4294967295; &#4294967295; Frankly, I don't quite understand how did I learn C myself. > &#4294967295; &#4294967295; &#4294967295; &#4294967295; FWIW, there were hardly any good book on that that I've read.
K&R?
On 11/24/2012 11:42 AM, me@linnix.info-for.us wrote:
>> 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. >> > > 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. >
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. ;-)
> 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. > > http://youtu.be/MG2MCtA75o8
On 24/11/12 20:28, mike wrote:> On 11/24/2012 8:41 AM, Robert Roland wrote:
>> 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? >> >> 2. 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? > > 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. >
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.
> 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.
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.
> 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.
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.
> > 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.
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.
> > 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 me...so they're not mentioned.
MK <mk@nospam.co.uk> wrote in
news:mpqdnQCeHpt0kC_NnZ2dnUVZ8oydnZ2d@bt.com: 

> On 24/11/2012 21:49, dbr@kbrx.com wrote: >> Possibly the best, certainly the first, book on C is "The C >> Programming Language" by Kernighan & Ritchie. >> > > 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 > >
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. <http://publications.gbdirect.co.uk/c_book/> -- Ian Malcolm. London, ENGLAND. (NEWSGROUP REPLY PREFERRED) ianm[at]the[dash]malcolms[dot]freeserve[dot]co[dot]uk [at]=@, [dash]=- & [dot]=. *Warning* HTML & >32K emails --> NUL
On Sun, 25 Nov 2012 04:18:32 +0700, Ivan Shmakov <oneingray@gmail.com>
wrote:


> 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: */
for me
> i = 3; /* ldi r7, 3 */ > i += 2; /* adi r7, 2 */ > i++; /* inc r7 */
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...
>[1] http://www.nongnu.org/avr-libc/user-manual/

The 2024 Embedded Online Conference