#include <SPI.h>
#include <LedControl.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h> // Include library for I2C LCD
// Define the pins for the LED matrix
#define DIN_PIN 11
#define CS_PIN 10
#define CLK_PIN 13
#define I2C_ADDRESS 0x04 // Define the I2C address for the Arduino
// Create an instance of the LedControl library
LedControl lc = LedControl(DIN_PIN, CLK_PIN, CS_PIN, 4); // DIN, CLK, CS, number of displays
// Create an instance of the LiquidCrystal_I2C library
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD I2C address to 0x27 for a 16 chars and 2 line display
void setup() {
// Initialize the LED matrix
for (int i = 0; i < 4; i++) {
lc.shutdown(i, false);
lc.setIntensity(i, 8);
lc.clearDisplay(i);
// Turn on all LEDs
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
lc.setLed(i, row, col, true);
}
}
}
// Initialize I2C communication as slave
Wire.begin(I2C_ADDRESS);
Wire.onReceive(receiveEvent); // Register a function to be called when data is received
// Initialize the LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Waiting for input");
Serial.begin(9600);
Serial.println("Waiting for input:");
}
// Function to handle incoming I2C data
void receiveEvent(int howMany) {
unsigned int number = 0;
while (Wire.available()) {
char c = Wire.read();
if (isdigit(c)) {
number = number * 10 + (c - '0');
}
}
// Ensure the number is within valid range (1-65535)
if (number >= 1 && number <= 65535) {
controlLEDs(number);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Number: ");
lcd.setCursor(8, 0);
lcd.print(number);
Serial.print("Controlling LEDs with number: ");
Serial.println(number);
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Invalid number.");
Serial.println("Invalid number. Enter a value between 1 and 65535.");
}
}
// Function to control the LEDs based on the given number
void controlLEDs(unsigned int number) {
int maxRows = 8;
// Iterate through each bit of the number
for (int set = 0; set < 16; set++) {
bool turnOff = bitRead(number, set); // Read the bit value (0 or 1)
int firstColumn = set * 2; // Calculate the first column of the set
int secondColumn = firstColumn + 1; // Calculate the second column of the set
for (int row = 0; row < maxRows; row++) {
int deviceIndex1 = firstColumn / 8; // Determine the device for the first column
int columnIndex1 = firstColumn % 8; // Determine the column index within the device for the first column
int deviceIndex2 = secondColumn / 8; // Determine the device for the second column
int columnIndex2 = secondColumn % 8; // Determine the column index within the device for the second column
// Control the LEDs in the two columns
lc.setLed(deviceIndex1, row, columnIndex1, !turnOff);
lc.setLed(deviceIndex2, row, columnIndex2, !turnOff);
}
}
}
void loop() {
// Code inside loop() is necessary for Arduino sketch, even if empty
}