Subversion Repositories group.electronics

Rev

Rev 163 | Rev 171 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nitdcscore {
    public interface i2cmaster {
        int WriteI2cData(byte address, byte[] data, uint count);
        int ReadI2CData(byte address, ref byte[] data, uint count);
    }

    public class mcp23017 {
        public byte address { get; set; }
        private i2cmaster dev;

        public mcp23017(i2cmaster dev, byte address) {
            this.dev = dev;
            this.address = address;
        }

        public int SetIODirection(byte gpioa, byte gpiob) {
            byte[] data = new byte[] { 0x00, gpioa, gpiob };
            int rslt = dev.WriteI2cData(this.addressToWrite(), data, 3);
            return rslt;
        }

        public int SetIOPolarity(byte gpioa, byte gpiob) {
            byte[] data = new byte[] { 0x02, gpioa, gpiob };
            int rslt = dev.WriteI2cData(this.addressToWrite(), data, 3);
            return rslt;
        }

        public int SetIOPullups(byte gpioa, byte gpiob) {
            byte[] data = new byte[] { 0x0c, gpioa, gpiob };
            int rslt = dev.WriteI2cData(this.addressToWrite(), data, 3);
            return rslt;
        }

        public int GetIO(out byte[] data) {
            int rslt = 0;
            byte[] cmd = new byte[] { 0x12 };
            rslt = dev.WriteI2cData(this.addressToWrite(), cmd, 1);

            data = new byte[] { 0xff, 0xff };
            rslt = dev.ReadI2CData(this.addressToRead(), ref data, 2);
            return 1;
        }

        public int SetIO(byte gpioa, byte gpiob) {
            int rslt = 0;
            byte[] cmd = new byte[] { 0x12, gpioa, gpiob };
            rslt = dev.WriteI2cData(this.addressToWrite(), cmd, 3);
            return rslt;
        }

        private byte addressToWrite() {
            byte write = (byte)(this.address << 1);
            return write;
        }

        private byte addressToRead() {
            byte read = (byte)((this.address << 1) | 0x01);
            return read;
        }
    }
}