Go Down

Topic: programming tip: int vs. byte vs. #define (Read 2469 times) previous topic - next topic

kg4wsv

I've noticed several arduino programs (sketches) that start out

Code: [Select]
....
int myInputpin = 3;

void setup()
....


What we've done here is to use 2 bytes of RAM, which can be a scarce resource on a microcontroller, in order to store a value that couldn't possible be more than 28, and worse one than that it will never change!

If you know the range of a value will be limited, make the type reflect that:  a byte type can hold 256 values, but only occupies (you guessed it) one byte.

Even better, if the value is a constant that never changes (will you suddenly change that input to a different pin during program execution?  probably not!) use a constant to represent that value, and use a #define preprocessor directive to give a meaningful name to that constant:

Code: [Select]
#define MYINPUTPIN 3
this way we have a symbolic name for the value and we save RAM (to store that huge array we want to have in some other part of our program).

The all-caps MYINPUTPIN is a common style to tell us at a glance that we're dealing with a preprocessor directive, rather than a variable or a function.  Spelling it "myInputpin" would work just fine, but it may cause confusion especially if others use your code and are expecting the all-caps convention.

Sorry for the lecture.  :)

-j

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy