Three simple button-LED c-programs illustrating the use of macros.
Here are three simple programs in c for the AVR tiny44 that all do the same thing: turn on an LED when a button is pressed. Refer to the datasheet for the functions of register DDRx, PORTx, and PINx, where x=A,B. Refer to c programming introductions for the use of operators that work on bits.
There is an LED on pin PB2, physically pin 5 of the Tiny44.
There is a button on PA5.
The three programs:
1. Here is a simple program and makefile to light an LED in response to a button.
Comments:
- It's simple. You can tell that it is all done by putting numbers into registers and checking values of registers.
- But, to see what is going on, you need to count bits and keep track of numbers. It's easy to make mistakes.
- If you need to change pins, or alter the program for another board arrangement, you have to change numbers in several places.
- It can get very confusing if you are doing anything more complex.
2. Here is a clearer way to do it, using macros.
Comments:
- It reads more like spoken language. Once you are comfortable with operations on bits of bytes, it is clearer than the first one.
- If you want to change pins, you still have to change numbers in several places, and remember for more than a second or two where you put things.
- If you wanted to change input or output to a different port, you would have to make several changes in the main function and keep track of them.
3. Here's another way to use macros to do the same thing.
Comments:
- Again, it reads like English. It has more levels of definitions and seems more complex.
- But, if you want to change or add pins, the change is done once, in the #define macros. No changes need to be done within the main function.
- There is no confusion, for example, if input and output are done on different pins of the same port.