While looking through sample code examples for assign pin values to a variable I see that people are using integers like: int ledPin = 13; // LED connected to digital pin 13
Is there a reason for not defining the variable as a byte since that is adequate to hold values 0-255?
LED_BUILTIN is a defined symbol in pins_arduino.h. It should be used. Don't made a variable for it.
(as of 1.00 4/10/12 it is incorrectly defined if using ETHERNET board, it should be 9 )
There is a big difference between using #define and int
#define
acts as an alias and is a preprocessor directive. The substitution occurs when the source is compiled. It allocates no storage. The hardware instruction set contain a class of short "immediate" instructions which do not require fetching an operand for small values, like 13. Using define permits the compiler to use them
int
allocates 2 bytes in precious RAM (even byte takes one).
In addition the generated code cannot use an immediate instruction.
The value for LED_BUILTIN is not actually the number of a hardware pin, rather is is a software definition used by the library functions- Unfortunately digitalWrite as defined in wiring_digital.c as seen in some examples is hugely more complicated then simply setting a value on a pin. The code generated for the call is longer with the int
The hardware instruction set for the ATmel AVR micro contoller (as well an many other micro computer systems ) includes other immediate instructions. These include instructions for setting, resetting and testing flags. They handle I/O ports extremely efficiently. There also exist immediate instructions to add, subtract(with and without carry), and, or and compare as well as skip instruction which test I/O ports directly. They require referencing the specific port and pin.
Refer to ATmel AVR instruction set document 0856I–AVR–07/10 at
For example CBI Clears a bit in an I/O register which is specified in the instruction takes only 2 bytes (see page 48)