PCA9635 16-bit I2C-bus LED driver

Dependents:   digitalThermometer Counter SimpleClock printNumber ... more

PCA9635.cpp

Committer:
d_worrall
Date:
2011-06-29
Revision:
5:d8c2b5afde56
Parent:
4:056255549579
Child:
6:3f35bdfec837

File content as of revision 5:d8c2b5afde56:

//NXP PCA9635 library
//mbed Team     -   1st June 2011
//Ioannis Kedros 
//updated by Daniel Worrall - 28th June 2011

#include "mbed.h"
#include "PCA9635.h"

PCA9635::PCA9635(PinName sda, PinName scl) : m_i2c(sda, scl) 
{
    init(0x02); 
} 


//Driver Software Reset
void PCA9635::reset(void){
    cmd[0] = 0x06;           
    int ack = m_i2c.write(m_addr, cmd, 1); 
    if(!ack);
    else return;
    cmd[0] = 0xA5;
    cmd[1] = 0x5A;
    m_i2c.write(m_addr, cmd, 2);
}

void PCA9635::init(int address){
    m_addr = address;

    reset();

    //Mode-1 Register: 
    cmd[0] = 0x00;           
    cmd[1] = 0x00; 
    m_i2c.write(address, cmd, 2);

    //Mode-2 Register: 
    cmd[0] = 0x01;           
    cmd[1] = 0x22; 
    m_i2c.write(address, cmd, 2);
    
    //LED Registers into PWM Control
    for(char i=0x14; i<0x18; i++)
    {
        cmd[0] = i;           
        cmd[1] = 0xAA; 
        m_i2c.write(address, cmd, 2);
    }
}

void PCA9635::setAddress(int address){
    m_addr = address;
}

//Single LED On
void PCA9635::on(char led)
{
    cmd[0] = led + 2;     //led position      
    cmd[1] = 0xFF;        //brightness value
    m_i2c.write(m_addr, cmd, 2);    
}


//Single LED Off
void PCA9635::off(char led)
{
    cmd[0] = led + 2;     //led position  
    cmd[1] = 0x00;        //brightness value
    m_i2c.write(m_addr, cmd, 2);  
}


void PCA9635::bus(short leds)
{
    short temp = leds;          //check each bit of leds
    bool stat = false;          //check LSB of temp
    for(int j=0; j<16; j++) {
        stat = (bool)(temp & 0x0001);
        if(stat == true){       //set output accordingly
            on(j);                
        }
        else {
            off(j);
        }
        temp = (temp >> 1);     //bitwise shift right by 1 to scan next bit
    }
}

//Brightness control for single or all LEDs
void PCA9635::brightness(char led, char value)
{
    if(led == ALL)
    {
        for(char allLeds=0x02; allLeds<0x12; allLeds++)
        {
            cmd[0] = allLeds;           
            cmd[1] = value; 
            m_i2c.write(m_addr, cmd, 2);
        }
    }
    else
    {
        cmd[0] = led + 2;           
        cmd[1] = value; 
        m_i2c.write(m_addr, cmd, 2);
    }
}