Control Code with I/O and ADC working

Dependencies:   MODSERIAL mbed

MCP23008/MCP23008.cpp

Committer:
jrodenburg
Date:
2018-01-22
Revision:
0:a28a1035c31b
Child:
1:0182b86f9bd4

File content as of revision 0:a28a1035c31b:

#include "mbed.h"
#include "MCP23008.h"
#include "MODSERIAL.h"

MODSERIAL pc2(USBTX, USBRX);

namespace {
    const uint8_t I2C_WRITE         = 0x00;
    const uint8_t I2C_READ          = 0x01;

    /* MCP23008 registers */
    const uint8_t IODIR             = 0x00;
    const uint8_t GPIO              = 0x09;
    
    //Channel addresses
    const uint8_t CHNL_0     = 0x01;
    const uint8_t CHNL_1     = 0x02;
    const uint8_t CHNL_2     = 0x04;
    const uint8_t CHNL_3     = 0x08;
};

MCP23008::MCP23008 (PinName sda, PinName scl, uint8_t address, int freq): i2c( sda, scl ){
    addrI2C = address;
    i2c.frequency(freq);
}

void MCP23008::setAddress(int address){
    addrI2C = address;
}

void MCP23008::writeOutput(int chnl, bool val){
    char data[2];
    int chnSel = 0;
        
    //select channel to read
    switch (chnl){
        case 0:
            chnSel = CHNL_0;
            break;
        case 1:
            chnSel = CHNL_1;
            break;
        case 2:
            chnSel = CHNL_2;
            break;
        case 3:
            chnSel = CHNL_3;
            break;
    } 
    
    //turn channel on
    if(val == 1){ 
        data[0] = GPIO;  //register address
        GPIO_Pin_Status = GPIO_Pin_Status | chnSel;
        data[1] = GPIO_Pin_Status;
    }
    
    //turn channel off
    else if(val == 0){
        data[0] = GPIO;  //register address
        GPIO_Pin_Status = GPIO_Pin_Status & (0xFF^chnSel);
        data[1] = GPIO_Pin_Status;//data to send to that address
    } 
    
    i2c.write((addrI2C<<1)|(I2C_WRITE), data, 2); 
    wait(2);
}

void MCP23008::init(){
    char io_setup[2];
    
    io_setup[0] = IODIR;
    io_setup[1] = 0x00; //turn all pins to outputs
    
    i2c.write((addrI2C<<1)|(I2C_WRITE), io_setup, 2);
    wait(2);
    
    //Set all outputs to off
    GPIO_Pin_Status = 0x00;
}