Subversion Repositories group.electronics

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
123 pfowler 1
#include <avr/io.h>
2
#include <stdlib.h>
3
#include "wire.h"
4
#include "avrutil.h"
5
#include <util/delay.h>
6
 
7
#include "mio.h"
8
 
9
#define IODIR	0x00	// I/O Direction, 1 = Input, 0 = Output
10
#define IPOL	0x01	// Polarity, 1 = Invert
11
#define	GPINTEN	0x02	// Interrupt on change, 1 = Enable
12
#define	DEFVAL	0x03	// Default compare value
13
#define INTCON	0x04
14
#define	IOCON	0x05	// Config
15
#define	GPPU	0x06	// Pullups for input, 1 = Enable
16
#define	INTF	0x07	// Interrupt flag (pin mask)
17
#define	INTCAP	0x08	// GPIO value at interrupt (RO)
18
#define	GPIO	0x09	// Read value of pins
19
#define OLAT	0x0a	// Latch pins (write)
20
 
21
void mio_init() {
124 pfowler 22
  mio_init_addr(0x20);
123 pfowler 23
}
24
 
25
void mio_init_addr(uint8_t i2c_addr) {
26
  mio.i2c_addr = i2c_addr;
124 pfowler 27
  i2c_beginTransmission(mio.i2c_addr);
28
  i2c_writeByte(IODIR);		// Start at 0x00
29
  i2c_writeByte(0xFF);		// Set IODIR to all inputs
30
  i2c_writeByte(0x00);		// Everything else default 0x00
31
  i2c_writeByte(0x00);
32
  i2c_writeByte(0x00);
33
  i2c_writeByte(0x00);
34
  i2c_writeByte(0x00);
35
  i2c_writeByte(0x00);
36
  i2c_writeByte(0x00);
37
  i2c_writeByte(0x00);
38
  i2c_writeByte(0x00);
39
  i2c_endTransmission(1);
40
 
123 pfowler 41
}
42
 
43
inline uint8_t mio_readPin(uint8_t pin) {
44
    return rbi(mio_read(), pin);
45
}
46
 
47
inline uint8_t mio_read() {
48
  return mio_readReg(GPIO);
49
}
50
 
51
inline void mio_latch(uint8_t data) {
52
  mio_writeReg(OLAT, data);
53
}
54
 
55
void mio_latchPin(uint8_t pin, uint8_t value) {
56
  uint8_t val = mio_read();
57
  if (value)
58
    sbi(val, pin);
59
  else
60
    cbi(val, pin);
61
  mio_latch(val);
62
}
63
 
64
inline void mio_iodir(uint8_t dir) {
65
  mio_writeReg(IODIR, dir);
66
}
67
 
68
inline void mio_pullups(uint8_t pu) {
69
  mio_writeReg(GPPU, pu);
70
}
71
 
72
 
73
 
74
 
75
uint8_t mio_readReg(uint8_t address) {
76
  if (!mio.i2c_addr) return 0xFF;
77
 
78
  uint8_t reg = 0xFF;
79
 
80
  i2c_beginTransmission(mio.i2c_addr);
81
  i2c_writeByte((int) address);
82
  i2c_endTransmission(0);
83
 
84
  i2c_requestFrom(mio.i2c_addr, 1, 1);
85
  if (i2c_available()) reg = i2c_read();  
86
 
87
  return reg;
88
}
89
 
90
void mio_writeReg(uint8_t address, uint8_t reg) {
91
    if (!mio.i2c_addr) return;
92
    i2c_beginTransmission(mio.i2c_addr);
93
    i2c_writeByte((int) address);
94
    i2c_writeByte(reg);
95
    i2c_endTransmission(1);
96
}
97