Subversion Repositories group.electronics

Rev

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

#include <avr/io.h>
#include <stdlib.h>
#include "wire.h"
#include "avrutil.h"
#include <util/delay.h>

#include "mio.h"

#define IODIR   0x00    // I/O Direction, 1 = Input, 0 = Output
#define IPOL    0x01    // Polarity, 1 = Invert
#define GPINTEN 0x02    // Interrupt on change, 1 = Enable
#define DEFVAL  0x03    // Default compare value
#define INTCON  0x04
#define IOCON   0x05    // Config
#define GPPU    0x06    // Pullups for input, 1 = Enable
#define INTF    0x07    // Interrupt flag (pin mask)
#define INTCAP  0x08    // GPIO value at interrupt (RO)
#define GPIO    0x09    // Read value of pins
#define OLAT    0x0a    // Latch pins (write)

void mio_init() {
  mio_init_addr(0x20);
}

void mio_init_addr(uint8_t i2c_addr) {
  mio.i2c_addr = i2c_addr;
  i2c_beginTransmission(mio.i2c_addr);
  i2c_writeByte(IODIR);         // Start at 0x00
  i2c_writeByte(0xFF);          // Set IODIR to all inputs
  i2c_writeByte(0x00);          // Everything else default 0x00
  i2c_writeByte(0x00);
  i2c_writeByte(0x00);
  i2c_writeByte(0x00);
  i2c_writeByte(0x00);
  i2c_writeByte(0x00);
  i2c_writeByte(0x00);
  i2c_writeByte(0x00);
  i2c_writeByte(0x00);
  i2c_endTransmission(1);

}

inline uint8_t mio_readPin(uint8_t pin) {
    return rbi(mio_read(), pin);
}

inline uint8_t mio_read() {
  return mio_readReg(GPIO);
}

inline void mio_latch(uint8_t data) {
  mio_writeReg(OLAT, data);
}

void mio_latchPin(uint8_t pin, uint8_t value) {
  uint8_t val = mio_read();
  if (value)
    sbi(val, pin);
  else
    cbi(val, pin);
  mio_latch(val);
}

inline void mio_iodir(uint8_t dir) {
  mio_writeReg(IODIR, dir);
}

inline void mio_pullups(uint8_t pu) {
  mio_writeReg(GPPU, pu);
}
  



uint8_t mio_readReg(uint8_t address) {
  if (!mio.i2c_addr) return 0xFF;
  
  uint8_t reg = 0xFF;
  
  i2c_beginTransmission(mio.i2c_addr);
  i2c_writeByte((int) address);
  i2c_endTransmission(0);

  i2c_requestFrom(mio.i2c_addr, 1, 1);
  if (i2c_available()) reg = i2c_read();  
  
  return reg;
}

void mio_writeReg(uint8_t address, uint8_t reg) {
    if (!mio.i2c_addr) return;
    i2c_beginTransmission(mio.i2c_addr);
    i2c_writeByte((int) address);
    i2c_writeByte(reg);
    i2c_endTransmission(1);
}