Arduino BCD Conversion Interfacing MAX7219 LED Display Controller

by Lewis Loflin

This is very similar to two related projects with Arduino and the MAX7219. In this case I demonstrate how to convert from an integer value to binary coded decimal. (BCD) This is done without the use of any micro-controller specific libraries for functions.

The first four digits on the display will count from 0000-9999.

Arduino connected to MAX7219


#define Rb5  7  // CS
#define Rb6  8  // DATA
#define Rb7  9  // CLK

void setup()   {

  pinMode(Rb5, OUTPUT);
  pinMode(Rb6, OUTPUT);
  pinMode(Rb7, OUTPUT);
}

void loop()   {

  init_MAX7219();
  int digit;
  int count = 9999;
  // convert to BCD send to MAX7219
  for (int i=0; i<=count; i++)   {
    int j = i;	
    // get 1st digit of j
    digit = j % 10; // MOD J
    writeMAX7219(1, digit);
    // get 2nd digit of j
    j = j / 10; 
    digit = j % 10; // MOD j
    writeMAX7219(2, digit);
    // get 3rd digit of j
    j = j / 10;
    digit = j % 10; // MOD j
    writeMAX7219(3, digit);
    // get 4th digit of j
    j = j / 10;
    digit = j % 10; // MOD j
    writeMAX7219(4, digit);
    delay(200);
  } // end for


}
// shift data to MAX7219
// Rb7 -> CLK, Rb6 -> DATA, Rb5 -> CS not
void ssrOut(unsigned char val)  {  
  int j;
  for(j=1; j<=8; j++)  {   // shift out MSB first
    unsigned char  temp = val & 0x80; // MSB out first
    if (temp == 0x80) digitalWrite(Rb6, 1); // Rb6 DATA          
    else digitalWrite(Rb6, 0); 
    digitalWrite(Rb7, 1);
    delayMicroseconds(20);
    digitalWrite(Rb7, 0);
    val = val << 1; // shift one place left
  }  // next jvoid pulseCS(void)   {
  digitalWrite(Rb5, 1);
  delay(1);
  digitalWrite(Rb5, 0);
}


void init_MAX7219(void)   {
  digitalWrite(Rb5, 0); // CS NOT

  // set decode mode
  ssrOut(0x09); // address
  //	ssrOut(0x00); // no decode
  ssrOut(0xFF); // 4-bit BCD decode eight digits
  pulseCS();

  // set intensity
  ssrOut(0x0A); // address
  ssrOut(0x0D); // 5/32s
  pulseCS();

  // set scan limit 0-7
  ssrOut(0x0B); // address
  //	ssrOut(0x07); // 8 digits
  ssrOut(0x03); // 4 digits
  pulseCS();

  // clear MAX7219
  for(int i=1; i<=8; i++)   {
    ssrOut(i);
    ssrOut(0x00);
    pulseCS();
  }
  
    // set for normal operation
  ssrOut(0x0C); // address
  // ssrOut(0x00); // Off
  ssrOut(0x01);  // On
  pulseCS();

} 

void writeMAX7219(char address, char data)   {
  if ((address < 1) || (address > 8)) return;
  ssrOut(address); // valid numbers 1-8
  ssrOut(data); 
  pulseCS();
}



You Tube Arduino Microcontroller Video Series March 2012: