// Create a new struct data type call "spi", which includes 4 pin numbers.
struct spi {
uint8_t csPin; // CS
uint8_t clkPin; // CLK
uint8_t mosiPin; // MOSI
uint8_t misoPin; // MISO
};
// Declare a new global spi variable, and assign the pin numbers.
const spi spi1 = {10, 11, 12, 13};
void setup() {
// Call once to initialize a SPI channel.
spiInit(spi1);
// Call once to initialize the display on defined SPI channel.
displayInit(spi1, 1);
}
void loop() {
// A dot moving on row 1.
byte data = 0x01;
for (int i = 1; i <= 8; i++) {
displayWrite(spi1, 0x01, data);
data <<= 1;
delay(500);
}
}
/*============================SPI Related Function============================*/
// A function to initialize 4 SPI pins.
void spiInit(spi spi) {
// Set pins mode.
pinMode(spi.csPin, OUTPUT);
pinMode(spi.clkPin, OUTPUT);
pinMode(spi.mosiPin, OUTPUT);
pinMode(spi.misoPin, INPUT_PULLUP);
// Set pins default value.
digitalWrite(spi.csPin, HIGH);
digitalWrite(spi.clkPin, LOW);
digitalWrite(spi.mosiPin, LOW);
}
// SPI send out a clock pulse on this port.
void spiClockPulse(spi spi) {
digitalWrite(spi.clkPin, HIGH);
digitalWrite(spi.clkPin, LOW);
}
// SPI write a byte without enable/disable and read.
void spiWriteByte(spi spi, byte data) {
// TO-DO: Write 8 bits to the slave.
// Be careful MSB or LSB first.
// Optional: You can use a for loop to reduce duplicate code.
for (int i = 0; i <= 7; i++) {
// Set MOSI (Current bit).
digitalWrite(spi.mosiPin, (data >> (7 - i)) & 0b1);
// Clock Pulse
spiClockPulse(spi);
}
}
/*==========================Display Related Function==========================*/
void displayWrite(spi spi, byte opcode, byte data) {
// TO-DO: Send a 16 bit cmd to display.
// Enable the line.
digitalWrite(spi.csPin, LOW);
// Write 2 bytes. MSB first.
spiWriteByte(spi, opcode);
spiWriteByte(spi, data);
// Disable the line.
digitalWrite(spi.csPin, HIGH);
}
// Set all LEDs off
void displayClear(spi spi, uint8_t numOfDisp) {
// TO-DO: Set all rows to 0x00.
// Write all LED to 0.
for (int i = 0; i < 8; i++) {
displayWrite(spi, i + 1, 0);
}
// Make sure the cmd above are shift through all displays.
for (int i = 1; i < numOfDisp; i++) {
displayWrite(spi, 0, 0);
}
}
void displayInit(spi spi, uint8_t numOfDisp) {
// Initializations of all max7219-matrix Dot devices.
displayWrite(spi, 0x0C, 1); // Set Shutdown register to normal operation.
displayWrite(spi, 0x09, 0); // Set Decode-mode register to no decode for digit 0-7.
displayWrite(spi, 0x0A, 5); // Set Intensity register to adjust the brightness, maximum is 15.
displayWrite(spi, 0x0B, 0x07); // Set scan-limit register to determine how many digits(0-7) are displayed.
displayWrite(spi, 0X0F, 0); // Set Display-test register to normal operation.
// Loop for all devices to initialization. Make sure the cmd above are shift through all displays.
for (int i = 1; i < numOfDisp; i++) {
displayWrite(spi, 0, 0);
}
// Initialize the led display: Clear all displays.
displayClear(spi, numOfDisp); //
}