test

Dependencies:   mbed BufferedSerial LS7366LIB2 FastPWM

MCP23S17.h

Committer:
lsh2205
Date:
2020-04-23
Revision:
0:e12eb40b9fef

File content as of revision 0:e12eb40b9fef:

#ifndef _MCP23S17_H_
#define _MCP23S17_H_

#include "spi_setup.h"

#define MCP_GPPUA      0x0C // PULL_UP Port A
#define MCP_GPPUB      0x0D // PULL_UP Port B

#define MCP_IODIRA      0x00 // DIR Port A
#define MCP_IODIRB      0x01 // DIR Port B
#define MCP_GPPUA       0x0C // Pull up Port A
#define MCP_GPPUB       0x0D // Pull up Port B
#define MCP_GPIOA       0x12 // Address Port A
#define MCP_GPIOB       0x13 // Address Port B
#define MCP_WRITE_BYTE  0x40
#define MCP_READ_BYTE   0x41

#define MCP_SEG_CS      (uint8_t)0
#define MCP_BTN1_CS     (uint8_t)1
#define MCP_BTN2_CS     (uint8_t)2

void MCP23S17_Init();
void MCP_Write(uint8_t cs_select, uint8_t reg_addr, uint8_t data);
uint8_t MCP_Read(uint8_t cs_select, uint8_t reg_addr);

void MCP23S17_Init()
{
    MCP_Write(MCP_SEG_CS, MCP_IODIRA, 0x00); //GPIOA as output A
    MCP_Write(MCP_SEG_CS, MCP_IODIRB, 0x00); //GPIOB as output B
    
    MCP_Write(MCP_BTN1_CS, MCP_IODIRA, 0xff); //GPIOA as input A
    MCP_Write(MCP_BTN1_CS, MCP_IODIRB, 0xff); //GPIOB as input B
    
    MCP_Write(MCP_BTN2_CS, MCP_IODIRA, 0xff); //GPIOA as input A
    MCP_Write(MCP_BTN2_CS, MCP_IODIRB, 0xff); //GPIOB as input B
    
    MCP_Write(MCP_BTN2_CS, MCP_GPPUB, 0xff); //GPIOB as input B
}

void MCP_Write(uint8_t cs_select, uint8_t reg_addr, uint8_t data)
{
        if(cs_select == MCP_SEG_CS) seg_cs = 1;
        else if(cs_select == MCP_BTN1_CS) btn1_cs = 1;
        else if(cs_select == MCP_BTN2_CS) btn2_cs = 1;
        
        spi1.write(MCP_WRITE_BYTE);
        spi1.write(reg_addr);
        spi1.write(data);
        
        if(cs_select == MCP_SEG_CS) seg_cs = 0;
        else if(cs_select == MCP_BTN1_CS) btn1_cs = 0;
        else if(cs_select == MCP_BTN2_CS) btn2_cs = 0;
}

uint8_t MCP_Read(uint8_t cs_select, uint8_t reg_addr)
{
        uint8_t receive_data = 0;
        
        if(cs_select == MCP_SEG_CS) seg_cs = 1;
        else if(cs_select == MCP_BTN1_CS) btn1_cs = 1;
        else if(cs_select == MCP_BTN2_CS) btn2_cs = 1;
        
        spi1.write(MCP_READ_BYTE);
        spi1.write(reg_addr);
        receive_data = spi1.write(0x00);
        
        if(cs_select == MCP_SEG_CS) seg_cs = 0;
        else if(cs_select == MCP_BTN1_CS) btn1_cs = 0;
        else if(cs_select == MCP_BTN2_CS) btn2_cs = 0;
        
        return receive_data;
}


#endif