/********************************************************************\ Name: gpio.c Created by: Stefan Ritt Contents: Driver for MCP23S17 General Purpose IO Chip \********************************************************************/ #include #include #include #include #include "mscbemb.h" #include "spi.h" // register addresses for non-banked layout (bank=0) #define GPIO_IODIRA 0x00 #define GPIO_IODIRB 0x01 #define GPIO_IPOLA 0x02 #define GPIO_IPOLB 0x03 #define GPIO_GPINTENA 0x04 #define GPIO_GPINTENB 0x05 #define GPIO_DEFVALA 0x06 #define GPIO_DEFVALB 0x07 #define GPIO_INTCONA 0x08 #define GPIO_INTCONB 0x09 #define GPIO_IOCON 0x0A #define GPIO_GPPUA 0x0C #define GPIO_GPPUB 0x0D #define GPIO_INTFA 0x0E #define GPIO_INTFB 0x0F #define GPIO_INTCAPA 0x10 #define GPIO_INTCAPB 0x11 #define GPIO_GPIOA 0x12 #define GPIO_GPIOB 0x13 #define GPIO_OLATA 0x14 #define GPIO_OLATB 0x15 /*------------------------------------------------------------------*/ sbit RST_SR = P1 ^ 2; void gpio_write(unsigned char device, unsigned char adr, unsigned char d); void spi_write_msb(unsigned char d); void gpio_init() { // remove RST_SR SFRPAGE = LEGACY_PAGE; RST_SR = 1; gpio_write(0, GPIO_IOCON, 1<<3); // HAEN = 1, addresses all four devices gpio_write(0, GPIO_IODIRA, 0); // all output gpio_write(0, GPIO_IODIRB, 0); gpio_write(1, GPIO_IOCON, 1<<3); // HAEN = 1, addresses all four devices gpio_write(1, GPIO_IODIRA, 0xFF); // all input gpio_write(1, GPIO_IODIRB, 0xFF); } /*------------------------------------------------------------------*/ void gpio_write(unsigned char device, unsigned char adr, unsigned char d) { spi_adr(); // Device opcode 0x40 combined with 3-bit hardware address, R/W = 0 (=write) spi_write_msb(0x40 | ((device & 0x07) << 1)); spi_write_msb(adr); spi_write_msb(d); spi_deadr(); } /*------------------------------------------------------------------*/ void gpio_out(unsigned short d) { gpio_write(0, GPIO_OLATA, d & 0xff); gpio_write(0, GPIO_OLATB, d >> 8); } /*------------------------------------------------------------------*/ unsigned char gpio_read(unsigned char device, unsigned char adr) { unsigned char d; // Device opcode 0x40 combined 3-bit hardware address, R/W = 1 (=read) spi_adr(); spi_write_msb(0x40 | ((device & 0x07) << 1) | 0x01); spi_write_msb(adr); d = spi_read_msb(); spi_deadr(); return d; } /*------------------------------------------------------------------*/ unsigned short gpio_in() { unsigned short d; d = gpio_read(1, GPIO_GPIOA) | (gpio_read(1, GPIO_GPIOB) << 8); return d; }