I notice problems with my output pins when I use this method of setting their pinMode
:
int allOutputPins[] = {3, 4, 9, 10, 5, A3, 11, 12, 7, 8, A1, A2};
for(int a = 0; a < sizeof(allOutputPins); a++){
pinMode(allOutputPins[a], OUTPUT);
}//end for
Am I doing something wrong?
1 Answer 1
Re "Am I doing something wrong?", yes :)
The sizeof(allOutputPins)
expression returns the size of allOutputPins[]
in terms of bytes, so is 24 because the array contains 12 two-byte integers. The loop's last 12 pinMode()
calls will be garbage.
Among other ways of fixing the problem, you could change the expression to sizeof(allOutputPins)/sizeof(int)
[which has the same value, 12, as (sizeof allOutputPins)/sizeof(int)
; eg see the syntax entries for the sizeof operator at cppreference.com] or you could change the base type of the array to byte
or uint8_t
.
-
2I would recommend using
sizeof allOutputPins / sizeof allOutputPins[0]
instead. This idiom is more robust because it works independently of the type of the array. I would use it even if I changeallOutputPins
base type touint8_t
.Edgar Bonet– Edgar Bonet2015年09月05日 06:07:26 +00:00Commented Sep 5, 2015 at 6:07 -
1What you needed and were expecting was the count of the items in the array. I need this so regularly, I keep a countof macro,
#define countof(a) (sizeof(a)/sizeof(a[0]))
in mylocal.h
file (personal file of common idioms).JRobert– JRobert2015年09月05日 11:30:50 +00:00Commented Sep 5, 2015 at 11:30 -
Thanks @JRobert that's a good idea. Is that all I need to define to use it?Michael Rader– Michael Rader2015年09月05日 20:07:16 +00:00Commented Sep 5, 2015 at 20:07
-
1You also need to use the
countof
define like this:for(int a = 0; a < countof(allOutputPins); a++){
2015年09月05日 21:28:18 +00:00Commented Sep 5, 2015 at 21:28 -
1You would need to
#include <local.h>
in your sketch (the Arduino IDE won't know to do it for you); thereafter you can use it anywhere in your sketch, such as how @NickGammon just described.JRobert– JRobert2015年09月05日 22:16:34 +00:00Commented Sep 5, 2015 at 22:16