Arduino - Variables declared in setup () are not part of the function

I planned to write a function that modifies a two-dimensional array so that each coordinate is set to 0. setup()I declared displayWidthand displayHeight, but could not access them generateBoard()because they are not in the same area.

The code:

void generateBoard(int board[][]) {
  // Modifies the array board by setting zeros

  for (int y=0; y < displayHeight; y++) {
    for (int x=0; x < displayWidth; x++) {
      board[x][y] = 0;
    }
  }
}

void setup() {
  int displayWidth  = 14;
  int displayHeight = 10;

  int board[displayWidth][displayHeight];
  generateBoard(board); 
}

void loop() {}

Local scope exception inside setting ()

error: declaration of 'board' as multidimensional array must have bounds for all dimensions except the first
error: declaration of 'board' as multidimensional array must have bounds for all dimensions except the first
In function 'void generateBoard(...)':
error: 'displayHheight' was not declared in this scope
error: 'displayWidth' was not declared in this scope
error: 'board' was not declared in this scope

The version fixed and worked:

const int displayWidth  = 14;
const int displayHeight = 10;
int board[displayWidth][displayHeight];

void generateBoard() {
  // Modifies the array board by setting zeros

  for (int y=0; y < displayHeight; y++) {
    for (int x=0; x < displayWidth; x++) {
      board[x][y] = 0;
    }
  }
}

void setup() {
  generateBoard(); 
}

void loop(){}
+4
source share
1 answer

Declare board, displayWidthand displayHeightglobally (outside the definition of any function). Like this:

 const int displayWidth  = 14;
 const int displayHeight = 10;
 int board[displayWidth][displayHeight];

void generateBoard() {
  // Modifies the array board by setting 0

  for (int y=0; y < displayHeight; y++) {
    for (int x=0; x < displayWidth; x++) {
      board[x][y] = 0;
    }
  }
}

void setup() {
  generateBoard(); 
}

void loop() {}

Declaring them inside setup () makes them local variables - local variables are only available for the function in which they are declared.

+4

All Articles