#include <SPI.h>
#define NUM_DEVICES 2
#define CS_PIN 10
#define VERT_PIN A0
#define HORZ_PIN A1
uint8_t x = 0;
uint8_t y = 0;
uint8_t displayBufferRight[8] = {0}; // For device 0 (left matrix)
uint8_t displayBufferLeft[8] = {0}; // For device 1 (right matrix)
void sendCommand(uint8_t reg, uint8_t data, uint8_t targetDevice) {
digitalWrite(CS_PIN, LOW);
for (int i = 0; i < NUM_DEVICES; i++) {
if (i == targetDevice) {
SPI.transfer(reg);
SPI.transfer(data);
} else {
SPI.transfer(0);
SPI.transfer(0);
}
}
digitalWrite(CS_PIN, HIGH);
}
void initMAX7219() {
// Initialize each device separately
for (uint8_t device = 0; device < NUM_DEVICES; device++) {
sendCommand(0x0C, 0x01, device); // Shutdown mode: normal operation
sendCommand(0x0F, 0x00, device); // Display test: off
sendCommand(0x0B, 0x07, device); // Scan limit: all rows
sendCommand(0x09, 0x00, device); // Decode mode: no decode
sendCommand(0x0A, 0x08, device); // Intensity: medium
}
clearDisplay();
}
void clearDisplay() {
for (uint8_t row = 0; row < 8; row++) {
displayBufferLeft[row] = 0;
displayBufferRight[row] = 0;
sendCommand(row + 1, 0, 0); // Clear left matrix
sendCommand(row + 1, 0, 1); // Clear right matrix
}
}
void updateDisplay() {
for (uint8_t row = 0; row < 8; row++) {
sendCommand(row + 1, displayBufferRight[row], 0);
sendCommand(row + 1, displayBufferLeft[row], 1);
}
}
void setPixel(uint8_t x, uint8_t y) {
clearDisplay(); // Only one pixel lit at a time
if (x < 8) {
displayBufferLeft[y] = (1 << (7 - x)); // Device 0: bits 7 to 0
} else {
displayBufferRight[y] = (1 << (15 - x)); // Device 1: bits 7 to 0
}
updateDisplay();
}
void setup() {
pinMode(CS_PIN, OUTPUT);
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
SPI.setClockDivider(SPI_CLOCK_DIV16);
initMAX7219();
pinMode(VERT_PIN, INPUT);
pinMode(HORZ_PIN, INPUT);
}
void loop() {
uint16_t horz = analogRead(HORZ_PIN);
uint16_t vert = analogRead(VERT_PIN);
// Y movement (vertical)
if (vert < 300) y = (y < 7) ? y + 1 : 7;
if (vert > 700) y = (y > 0) ? y - 1 : 0;
// X movement (horizontal)
if (horz > 700) x = (x < 15) ? x + 1 : 15;
if (horz < 300) x = (x > 0) ? x - 1 : 0;
setPixel(x, y);
delay(100); // Adjust for responsiveness
}