Inputs and Outputs in Arduino Mega

I would like to know how to program an Arduino mega board if I want multiple inputs and outputs. Here I have programmed the circuit with only a single input and output:

const int buttonPin22 = 22;
const int outputPin3 = 3;

int buttonstate = 0;

void setup() {
   pinMode(buttonPin22, INPUT);
   pinMode(outputPin3, OUTPUT);
   
}

void loop() {
  buttonstate = digitalRead(buttonPin22);
  
    if (buttonstate == HIGH)
    {
        digitalWrite(outputPin3, HIGH);
    }
    else{
        digitalWrite(outputPin3, LOW);
    }
}

You might be able to use an array for gpio pins. Try a search on "array gpio" or some such wording.

Repeat the code you have done, but instead of buttonPin22 and outputPin3, use for example buttonPin23 and outputPin4.

Use INPUT_PULLUP instead of INPUT. Buttons are normally wired between the DI pin and ground so are active when LOW.

Also, your code is ornate, this:

  buttonstate = digitalRead(buttonPin22);
  
    if (buttonstate == HIGH)
    {
        digitalWrite(outputPin3, HIGH);
    }
    else{
        digitalWrite(outputPin3, LOW);
    }

collapses into:

digitalWrite(outputPin3, !digitalRead(buttonPin22) );

Note the ! (not) ahead of the digitalRead

As your coding gets stronger, you'll learn to do this with an array of pin identifiers for input and output(the following works on a Nano). Then madmark's code could become something like:

int inarray[] = {1, 2, 3};
int outarray[] = {4, 5, 6};
int dioarraylen = 3;
int i;
void setup() {
  // put your setup code here, to run once:
  for (i = 0; i < dioarraylen; i++) {
    pinMode(inarray[i], INPUT_PULLUP);
    pinMode(outarray[i], OUTPUT);
  }
}

void loop() {
  int t;
  for (i = 0; i <  dioarraylen; i++) {
    digitalWrite(outarray[i], !digitalRead(inarray[i]));
  }
}

Hope that more fully addresses your question.
C

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.