Hi! We are trying to build a version of a BattleShip Game with an Arduino Mega board, and a GRB LED Matrix ws2812.
The main problem we are experiencing is that we are unable to control the Matrix by the buttons. We have tried individualizing each button/pin but we still can't make it work in a way that if you press the button corresponding to the row X and another for column Y the LED in X Y lights on.
Here is the code that works this area:
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
// Which pin on the Arduino is connected to the NeoPixels?
#define PIN 22
// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS 64
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_RGB + NEO_KHZ800);
// Constants to define each button
const int numButtons = 16;
enum buttons {
R0_BUTTON, R1_BUTTON, R2_BUTTON, R3_BUTTON,
R4_BUTTON, R5_BUTTON, R6_BUTTON, R7_BUTTON,
C0_BUTTON, C1_BUTTON, C2_BUTTON, C3_BUTTON,
C4_BUTTON, C5_BUTTON, C6_BUTTON, C7_BUTTON,
};
const int pinsB[numButtons] = {
37, 35, 33, 31, 29, 27, 25, 23,
39, 41, 43, 45, 47, 49, 51, 53,
};
bool pushed[numButtons];
// To convert every pixel to an array of [row][column]
int pixRC[8][8] = {
{0, 1, 2, 3, 4, 5, 6, 7} , // initializers for row indexed by 0
{8, 9, 10, 11, 12, 13, 14, 15} ,
{16, 17, 18, 19, 20, 21, 22, 23} ,
{24, 25, 26, 27, 28, 29, 30, 31} ,
{32, 33, 34, 35, 36, 37, 38, 39} ,
{40, 41, 42, 43, 44, 45, 46, 47} ,
{48, 49, 50, 51, 52, 53, 54, 55} ,
{56, 57, 58, 59, 60, 61, 62, 63} ,
};
int R = 0; // The row the player will input
int C = 0;// The column the player will input
int rowsCol[] = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}; // Rows & cols according to button
void setup() {
Serial.begin(9600);
pixels.begin();
pixels.setBrightness(5);
for (int i = 0; i < numButtons; i++) { // Activate in/out modes
pinMode (pinsB[i], INPUT);
pushed[i] = false;
}
// initialize all pins in orange to try them, this works!
for (int j = 0; j < 8; j++) { // check pixels
for (int i = 0; i < 8; i++) {
int pixel = pixRC[j][i];
pixels.setPixelColor(pixel, pixels.Color(255, 215, 0));
pixels.show();
}
}
// set all pins to off, this works too!
for (int j = 0; j < 8; j++) {
for (int i = 0; i < 8; i++) {
int pixel = pixRC[j][i];
pixels.setPixelColor(pixel, pixels.Color(0, 0, 0));
pixels.show();
}
}
}
void loop() {
// Read button value
for (int i = 0; i < numButtons; i++) {
bool previous = pushed[i];
pushed[i] = digitalRead (pinsB[i]) == HIGH;
if (pushed[i] != previous) {
if ((pushed[i]) && (i <= 7)) { // button just pressed
R = rowsCol[i];
}
else if ((pushed[i]) && (i > 7)) { // button just pressed
C = rowsCol[i];
}
}
}
int pixAttacked = pixRC[R][C];
pixels.setPixelColor(pixAttacked, pixels.Color(255, 0, 0));
pixels.show();
delay(10);
}
Would really appreciate any advice on the matter, thank you so much in advance!