Max7219
 
Notifications
Clear all

Max7219

9 Posts
3 Users
0 Reactions
3,885 Views
Posts: 137
Topic starter
(@cpwtech)
Estimable Member
Joined: 12 years ago
[#37350]

I have a question for everyone. Has anyone used the MAX7219 chips to drive a matrix? I have a working 32X8 matric using these chips, but I need to try to incorporate Renard protocol. I have a basic program but my limited programming skills are keeping me from completing it. It does work, but it will error out if you try and send the information to the Mega2560 to quickly. The Mega will lock up, resulting in me having to unplug it to reset it. Here is the code that I am using on the Mega;


#include "Renard.h"
#include "LedControl.h"
#include "Binary.h"
#include <avr/power.h>

// here we define the serial transmission rate and the size of incoming data packets.
// Note: without definition, the Arduino will not read beyond 63 bytes of data from
// Vixen.
#define BAUD 57600
#define PACKET_SIZE 256


/*
  Now we need a LedControl to work with.
  pin 51 is connected to the DataIn
  pin 52 is connected to the CLK
  pin 10 is connected to LOAD
  We have four MAX72XX.
  Note: This program was based around an Arduino Mega2560. Make sure your pin numbers
  are correct!!!
*/
 
LedControl cpwtech=LedControl(51,52,10,4);
Renard renard;
byte values[PACKET_SIZE];
 
void setup()
{
    power_adc_disable();     //Disable the Analog to Digital Converter module.
 power_timer2_disable();  //Disable the Timer 2 module.
  power_timer3_disable();  //Disable the Timer 3 module.
  power_timer4_disable();  //Disable the Timer 4 module.
  power_timer5_disable();  //Disable the Timer 5 module.
  power_twi_disable();     //Disable the Two Wire Interface module.
  power_usart2_disable();  //Disable the USART 2 module.
  power_usart3_disable();  //Disable the USART 3 module.

// Initialize the Renard protocol.  
   renard.begin((uint8_t*)&values, PACKET_SIZE, &Serial, 57600);

// The MAX7219 is in power-saving mode on startup; here's the wakeup call.
  cpwtech.shutdown(0,false);
    cpwtech.shutdown(1,false);
    cpwtech.shutdown(2,false);
    cpwtech.shutdown(3,false);
// Set the display to medium value  
  cpwtech.setIntensity(0,4);
  cpwtech.setIntensity(1,4);
  cpwtech.setIntensity(2,4);
  cpwtech.setIntensity(3,4);
// Clear display  
  cpwtech.clearDisplay(0);
  cpwtech.clearDisplay(1);
  cpwtech.clearDisplay(2);
  cpwtech.clearDisplay(3);
}
 
void loop()
{
  int nBytesRead = 0;
//Receive Renard data 
    if( renard.receive()) {
 
  for( int nByteNum=0; nByteNum<PACKET_SIZE; nByteNum++ )
  {
    int nValue = values[nByteNum];
//figure out which of the 4 MAX72XX needs to be addressed    
    float nAddr = nByteNum/64;
        if (nAddr >0 && nAddr <1)
    nAddr = 3;
    else if (nAddr >1 && nAddr <2)
    nAddr = 2;
 else if (nAddr >2 && nAddr <3)
    nAddr = 1;
 else if (nAddr >3 && nAddr <4)
    nAddr = 0;
//See if we should turn on the LED
    boolean bState = ( nValue ? true:false );
 //Now figure out which Column the LED is in
 //Then figure out what row to turn on to light the LED
     int nRow = (nByteNum/8)%8;
    int nColumn = nByteNum%8;

    cpwtech.setLed( nAddr, nRow, nColumn, bState );
  }

}}

If any of you programming guru's see where I can speed this code up, please feel free to offer up suggestions.

The rest I went with the MAX72XX chips is because that is what I had on hand, plus they only cost me $1.59 each, so why not, LOL

Thanks in advance,

Patrick


8 Replies
Posts: 459
(@shockwave)
Reputable Member
Joined: 15 years ago

I have

The 7219 is connected through spi, which is several orders of magnitude faster that the serial data coming in. I personally use double buffers, filling a data in buffer, setting a flag when ready for use. And then the writing out code senses the flag, moves data into the drive buffer, and clears the flag. I also use spi interrupts so that I can do other stuff while the spi block outputs data.

Good on you for working with such an oddball part btw.


Reply
Posts: 137
Topic starter
(@cpwtech)
Estimable Member
Joined: 12 years ago

This is what I have so far with a rewrite of the code. It works with Generic Serial protocol. Here is the code


#include "LedControl.h"
 
LedControl lc=LedControl(51,52,10,4);  // Pins: DIN,CLK,CS, # of Display connected
 
//unsigned long delayTime=100;  // Delay between Frames
int e = 0;

void setup()
{
  lc.shutdown(0,false);  // Wake up displays
  lc.shutdown(1,false);
  lc.shutdown(2,false);  // Wake up displays
  lc.shutdown(3,false);
  lc.setIntensity(0,1);  // Set intensity levels
  lc.setIntensity(1,1);
  lc.setIntensity(2,1);  // Set intensity levels
  lc.setIntensity(3,1);
  lc.clearDisplay(0);  // Clear Displays
  lc.clearDisplay(1);
  lc.clearDisplay(2);  // Clear Displays
  lc.clearDisplay(3);
Serial.begin(57600);
}
 
 
void loop()
{
  
   if (Serial.available() >= 34) {
     int uno = Serial.read();
     if (uno == 126){
       
       int dos = Serial.read();
       if (dos == 33){
   {
   for (int y =0;y<33;y++){
    e = Serial.read();
   

     if (y >=0 && y <=7){
      lc.setRow(3,y,e);
      }
      if (y>7 && y<=15){
        lc.setRow(2,(y-7),e);
      }
     if (y >=16 && y <=23){
      lc.setRow(1,(y-15),e);
      }
      if (y>=24 && y<=31){
        lc.setRow(0,(y-23),e);
      }
     }
}}}}}

and the video to go along with it working


Reply
Posts: 152
(@jetty)
Estimable Member
Joined: 14 years ago

Here are some changes to save you some CPU time (which is likely the cause of the data dropping) and help clean things up a bit:

1. Divides are extremely expensive on Arduino as there's no floating / point maths co-processor. This can easily take at least 400-800 cycles per divide at 16MHz on
an Arduino. Multiplies are a bit faster (but still slow). And add/subtract are faster still.

As you're dividing by 64, you can bit shift instead. 256 >> 1 (bit shift 1) is like dividing by 2, so you get 128.
But shifting by 6 is equal to dividing by 64 (64 = 2 to the power 6). And the best thing is that it only takes 1 cycle.

So:

byte nAddr = nByteNum/64;

Becomes:

byte nAddr = nByteNum >> 6; // Divide nByteNum by 64

2.
This code does nothing, and I suspect isn't doing something you need it to. Because nAddr is a byte, it can only be integer (whole)
so nAddr can never be >0 and <1, it's impossible, because it can't have a value between 0 and 1. Therefore none of those clauses ever get
filled, nAddr is therefore always equal to nByteNum/64.

if (nAddr >0 && nAddr <1) nAddr = 3;
else if (nAddr >1 && nAddr <2) nAddr = 2;
else if (nAddr >2 && nAddr <3) nAddr = 1;
else if (nAddr >3 && nAddr <4) nAddr = 0;

3. boolean bState = ( nValue ? true:false );
is redundant. Any integer variable is true if it's non-zero and false if it's zero anyway, so you can skip that line and just do:

cpwtech.setLed( nAddr, nRow, nColumn, nValue );

or if you want to do it portably, and setLed takes a boolean, you cast it to a boolean just in case you use the code elsewhere (defensive programming):

cpwtech.setLed( nAddr, nRow, nColumn, (boolean)nValue );

4. Another expensive div:

int nRow = (nByteNum/8)%8;
int nColumn = nByteNum%8;

replace with:

int nRow = (nByteNum>>3)%8;
int nColumn = nByteNum%8;

And also, because it's being mod'd with 8 (another expensive op), but it happens to be a power of 2, you can do this:

int nRow = (nByteNum>>3)&0x07;
int nColumn = nByteNum&0x07;

& (single ampersand) is a bitwise AND operation.

0x07 = 1 + 2 + 4, i.e. the first 3 binary bits

I.E. you're saying dump anything that's not the first 3 bits which is the same as modulus 8.

5. Arduino's have a limited serial buffer, you may need to move to interrupts to ensure you don't lose any data if the above doesn't solve it depending on the workload
of the data being sent.

6. You may also which to post the rest of the code to take a look at (LedControl / Renard)


Reply
Posts: 137
Topic starter
(@cpwtech)
Estimable Member
Joined: 12 years ago

I can't thank you enough jetty for trying to help me out with this.


Reply
Posts: 137
Topic starter
(@cpwtech)
Estimable Member
Joined: 12 years ago

Update on the Matrix. I have started a new post over in the Matrix area to keep it fitting the subject matter.


Reply
Posts: 137
Topic starter
(@cpwtech)
Estimable Member
Joined: 12 years ago

Well I have posted this in the Matrix area, but figured I would also post it here just in case somebody had the same idea I did. I have finally worked out how to get 8 MAX7219 chips to work with Vixen. I would like to ask the programming gurus to please take a look at this sketch and let me know if you see something that could be optimized for speed. I would like to at least double the size of the Matrix.

Thanks in advance,

/* Sketch to control a 32X16 matrix using 8 MAX7219 chips
 *  I took the LEDControl Library and stripped it down to just what I needed.
 *  Please feel free to use/change/delete whatever you see needs to be improved, because Lord knows I am no programmer.
 *  You have to connect the Data In to pin 51, Clock to pin 52, and Latch to pin 53 on the Mega2560
 *    Permission is hereby granted, free of charge, to any person
 *    obtaining a copy of this software and associated documentation
 *    files (the "Software"), to deal in the Software without
 *    restriction, including without limitation the rights to use,
 *    copy, modify, merge, publish, distribute, sublicense, and/or sell
 *    copies of the Software, and to permit persons to whom the
 *    Software is furnished to do so, subject to the following
 *    conditions:
 * 
 *    This permission notice shall be included in all copies or 
 *    substantial portions of the Software.
 * 
 *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 *    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 *    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 *    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *    OTHER DEALINGS IN THE SOFTWARE.
 */


#include <SPI.h>
// Change the following to how many MAX72XX chips you are using.
#define maxDevices 8
//Array to hold the data to be sent out to the matrix
byte spidata[32];
//Array to keep track of the status of the matrix
byte status[64];
//Array of incoming data from Vixen
int data[64];
//This keeps track of chip we are talking to.  the one closest to the Arduino is chip 0
int address =0;
//This keeps track of which row we are setting
int row = 0;


//the opcodes for the MAX7221 and MAX7219
#define OP_NOOP   0
#define OP_DIGIT0 1
#define OP_DIGIT1 2
#define OP_DIGIT2 3
#define OP_DIGIT3 4
#define OP_DIGIT4 5
#define OP_DIGIT5 6
#define OP_DIGIT6 7
#define OP_DIGIT7 8
#define OP_DECODEMODE  9
#define OP_INTENSITY   10
#define OP_SCANLIMIT   11
#define OP_SHUTDOWN    12
#define OP_DISPLAYTEST 15

void setup(){
  //Clearing all data and setting up the array matrix
  int maxbytes=maxDevices<<1;
    for(int i=0;i<maxbytes;i++)
        spidata[i]=(byte)0;
//Setting up the SPI connection
  SPISettings(2000000,MSBFIRST,SPI_MODE0);
  SPI.begin();
  setupdisplays(maxDevices);
  Serial.begin(57600);
}

void setupdisplays(byte numDevices){
  for(int i=0;i<(numDevices<<3);i++) 
        status[i]=0x00;
    for(int i=0;i<maxDevices;i++) {
        spiTransfer(i,OP_DISPLAYTEST,0);
                setIntensity(i,2);
        //scanlimit is set to max on startup
        setScanLimit(i,7);
        //decode is done in source
        spiTransfer(i,OP_DECODEMODE,0);
        clearDisplay(i);
        //we turn on the displays
        shutdown(i,false);

}}

void shutdown(int addr, bool b) {
    if(addr<0 || addr>=maxDevices)
        return;
    if(b)
        spiTransfer(addr, OP_SHUTDOWN,0);
    else
        spiTransfer(addr, OP_SHUTDOWN,1);
}

void setScanLimit(int addr, int limit) {
    if(addr<0 || addr>=maxDevices)
        return;
    if(limit>=0 && limit<8)
        spiTransfer(addr, OP_SCANLIMIT,limit);
}

void setIntensity(int addr, int intensity) {
    if(addr<0 || addr>=maxDevices)
        return;
    if(intensity>=0 && intensity<16)  
        spiTransfer(addr, OP_INTENSITY,intensity);
}

void clearDisplay(int addr) {
    int offset;

    if(addr<0 || addr>=maxDevices)
        return;
    offset=addr<<3;
    for(int i=0;i<8;i++) {
        status[offset+i]=0;
        spiTransfer(addr, i+1,status[offset+i]);
    }
}


void spiTransfer(int addr, volatile byte opcode, volatile byte data) {
    //Create an array with the data to shift out
    int offset=addr<<1;
    int maxbytes=maxDevices<<1;

   //put our device data into the array
    spidata[offset+1]=opcode;
    spidata[offset]=data;
    //enable the line 
    digitalWrite(SS,LOW);
    //Now shift out the data 
    for(int i=maxbytes;i>0;i--)
        SPI.transfer(spidata[i-1]);
    //latch the data onto the display
    digitalWrite(SS,HIGH);
}    

void setRow(int addr, int row, byte value) {
    int offset;
    if(addr<0 || addr>=maxDevices)
        return;
    if(row<0 || row>7)
        return;
    offset=addr<<3;
    status[offset+row]=value;
    spiTransfer(addr, row+1,status[offset+row]);
}


void loop() {
  if (Serial.available() > 62) {
    for (int y = 0; y < 64;y++){
     byte e = Serial.read();
//     byte e= data[i];
     if (y >=0 && y <=7){
        row = 7-y;
        address = address + 1;
     }
    
      if (y>7 && y<=15){
         address = address + 3;
         row = 7- (y-8);
     }
     if (y >15 && y <=23){
       address = address + 5;
       row = 7- (y-16);
     }
     if (y>23 && y<=31){
       address = address + 7;
       row = 7-(y - 24);
     }
     if (y >31 && y <=39){
      address = address;
      row = 7-(y -32);
     }
     if (y>39 && y<=47){
        address = address + 2;
        row = 7-(y -40);
        }
     if (y >47 && y <=55){
        address = address + 4;
        row = 7-(y -48);
     }
    if (y>55 && y<=64){
        address = address + 6;
        row = 7-(y -56);
        }
    if (address>7){
        address = 0;}
    
 
     setRow(address,row,e);
     address = 0;
      }
      byte wastechannel = Serial.read();
      }
     }

Reply
Posts: 152
(@jetty)
Estimable Member
Joined: 14 years ago

I'd start by tackling the loop, as that's the part that repeats and will soak up time.

Looks like you're trying to determine the row address with a large set of if clauses. Double check the logic, but I believe all of that code can be compressed down to the following
binary ranges (and also looks like y<=64 should be <=63 (i.e. you have a bug too):

00000000 - 00000111 0-7
00001000 - 00001111 8-15
00010000 - 00010111 16-23
00011000 - 00011111 24-31
00100000 - 00100111 32-39
00101000 - 00101111 40-47
00110000 - 00110111 48-55
00111000 - 00111111 56-63

Also, I suspect you have another bug with address. The first time address is used is address = address + 1;
however there's no initialization, as it's a global it will take on the value of the last run.

Seeing as the last 3 bits are the same, and your if statements subtract the offset each time, then you only need these 3 lines.
These lines to replace all the if's and row/address calculations. if's and subtractions and comparisons are expensive.

row = (~(y & 0x07)) & 0x07;
address = ((y >> 3) << 1);
address |= (~(address >> 2)) & 0x01;

Here's how it works:

// y&0x07 = Take the last 3 bits, all others become 0, this is equivalent to your (y-8, y-23, y-16 etc)
// ~(y&0x07) = Invert the bit result (this is equivalent to 7-(y-16), 7-(y-24) etc., but also sets the nonused bits high
// (~(y & 0x07)) & 0x07 = Fix the problem introduced by the ~ above, and now all the nonuser bits become low.
row = (~(y & 0x07)) & 0x07; // Approx 5 cycles (if using uint8_t, about double is using int)

// Shift y right by 3 bits to get to the part we need to calculate the address:
//y >> 3 address
//00000 1
//00001 3
//00010 5
//00011 7
//00100 0
//00101 2
//00110 4
//00111 6
//
// Because you're incrementing in multiples of 2 per range, shift left by 1 (pulls in 0 on the last bit)
// (y >> 3) <>2) & 0xFE would be equivalent here)
// At this point, we have 0, 2, 4, 6 for the last 2 bits
// Now we need to get 1, 3, 5, 7, 0, 2, 4, 6...
// This is controlled by the inverse of bit 2 (bits are indexed LSB from 0), so:
// we use that bit to twiddle the last bit:
// ~(result >> 2) & 0x01
address = ((y >> 3) << 1); // Approx 4 cycles (uint8_t)
address |= (~(address >> 2)) & 0x01; // Approx 6 cycles (uint8_t)

(I haven't tested the above code, there maybe a typo, but the principle is sound, you'll need to test)

I.E. At 15 cycles, that 3 lines of code could run at over 1MHz (excluding your serial read), comparing to the current code,
the execution time would be varying (depending on how many if's encountered), I'd estimate the speed of that code to be around
80KHz (subtract / add takes time)

Make row/address uint8_t and save more cycles, otherwise using int's you'll slow the speed by double or more.

For waste channel, just do Serial.read(), don't assign it to anything as you're not using it. Optimizer may spot that but if not, you'll save 1 cycle.
Increase Serial speed to 115200, faster data in means faster processing.

Personally I wouldn't use Serial.available() > 62, I'd just put it in a for loop and only use Serial.read, Serial.read will block if there's no data, that way you're spreading
out the processing and not doing it all in a block, and don't run the risk of losing Serial data in the meantime.

In set row, don't check an arguments with if's, you'll save cycles. Using the row approach above, the 0x07 in the calc guarantees row will be 0-7 on entry,
and address, well if you set a device that doesn't exist, nothing happens anyway so no need to check, if if you may overflow your array status, then:
addr &= 0x07
And setup all your arrays based on the constants you're defining, i.e. the [32] [64] should be based on maxDevices in some fashion so that you don't introduce
array overflows accidentally if maxDevices is ever changed (doesn't change the speed, just defensive programming / good practice).

You should also speed up spiTransfer and replace digitalWrite with bit twiddling of the ports directly, do that and you'll get a significantly performance increase.

All the other routines I wouldn't both speeding up unless you're planning on calling them a lot, i.e. there's not much benefit to doing so, although you could apply similar techniques to the ones here.


Reply
Posts: 137
Topic starter
(@cpwtech)
Estimable Member
Joined: 12 years ago

Thanks jetty! I will have to print out your reply and give it a try. I did not know that about Serial.read(), it blocking unless something is there. As far as the rest of the suggestions, I have no doubt that it will work, I just have to tr and wrap my head around it first, LOL. Big difference in working on cars and programming, but I will get there.

I wanted to do the matrix this way, because the chips with the little LED display are cheap (~$1.50). Once I get everything figured out I will expand it out to the breaking point. 🙂


Reply
Share: