Question

I have just entered into AVR MCU programming using gcc-avr, but when I see sample programs I am not able to make out much from the code:

DDRD |= (1 << PD7);
TCCR2 = (1 << WGM21) | (0 << WGM20);
TCCR2 |= (1 << COM20);
TCCR2 |= (6 << CS20);

I do not see also any declarations variables : DDRD, PD7, TCCR2, WGM21, WGM20, COM20, CS20, but they are directly used. Please let me know how I can know all pre-defined variables and its usage? It becomes very difficult in understanding the code without knowing the same.

Thanks in advance.

Était-ce utile?

La solution

That kind of code is very common when programming embedded systems, although you will need to look at the header files and the AVR documentation to learn what those specific identifiers mean. Be aware that it can be very complex if you're new to this, and you will need to understand how to work with raw binary and C-style bit shifts/operators. (There are lots of tutorials online if you need to learn more about that.)

I'll try to explain the basic principle though.

All of the identifiers you saw will be preprocessor constants (i.e. #define ...), rather than variables. DDRD and TCCR2 will specify memory locations. These locations will be mapped onto certain functionality, so that setting or clearing certain bits at those locations will change the behaviour of the device (e.g. enable a clock divider, or set a GPIO pin high or low, etc.).

PD7, WGM21, WGM20, COM20, and CS20 will all be fairly small numbers. They specify how far you need to offset certain bit patterns to achieve certain results. Bit-wise operators (such as | and &) and bit-shift operators (typically <<) are used to create the patterns which are written to the memory locations. The documentation will tell you what patterns to use.

I'll use a simple fictional example to illustrate this. Let's say there is a register which controls the value of some output pins. We'll call the register OUTPUT1. Typically, each bit will correspond to the value of a specific pin. Turning on pin 4 (but leaving the other pins alone) might look like this:

OUTPUT1 |= (1 << PIN4);

This bitwise OR's the existing register with the pattern to turn pin 4 on. Turning that pin off again might look like this:

OUTPUT1 &= ~(1 << PIN4);

This bitwise AND's the existing register with everything except the pattern to turn pin 4 on (which results in clearing the bit). That's an entirely fictional example though, so don't actually try it!

The principle is basically the same for many different systems, so once you've learned it on AVR, you will hopefully be able to adapt to other devices as well.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top