I'd like to 'clean up' some code that involves several pinMode()
and digitalWrite()
lines by using a single line of an array. I'm very new to both arrays so I'm a bit confused. The following examples are sections from code that controls a 4 digit, 7 segment LED.
// Define display pins
// Digit pins (common cathode)
int digit1 = 13; //Display pin 1
int digit2 = 12; //Display pin 2
int digit3 = 11; //Display pin 6
int digit4 = 10; //Display pin 8
// Segment pins
int segA = 2; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = 6; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15
void setup() {
pinMode(segA, OUTPUT);
pinMode(segB, OUTPUT);
pinMode(segC, OUTPUT);
pinMode(segD, OUTPUT);
pinMode(segE, OUTPUT);
pinMode(segF, OUTPUT);
pinMode(segG, OUTPUT);
pinMode(digit1, OUTPUT);
pinMode(digit2, OUTPUT);
pinMode(digit3, OUTPUT);
pinMode(digit4, OUTPUT);
}
#define SEGMENT_ON LOW
#define SEGMENT_OFF HIGH
switch (numberToDisplay){
case 0:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_OFF);
break;
Defining pins:
I'm pretty sure the code below is the correct way to store the pins as an array (but please correct me if I'm wrong).
digitPins[] = {13 12 11 10};
segPins[] = {2 3 4 5 6 7 8};
pinMode():
I understand I could use a for loop to set the pin modes but is there an even simpler way? Would something like this work?
pinMode(digitPins[], OUTPUT);
pinMode(segPins[], OUTPUT);
digitalWrite():
I could access the appropriate pin from the array to use in digitalWrite()
like the code below but that would result in the same number of lines of code (and be even more confusing). Is there another option?
digitalWrite(segPins[1], HIGH);