2 \author Travis Goodspeed
7 //Higher level left to client application.
9 //Based upon a neighborly example at
10 //http://codinglab.blogspot.com/2008/10/i2c-on-avr-using-bit-banging.html
16 #ifndef _GNU_ASSEMBLER_
23 //! Handles an i2c command.
24 void i2c_handle_fn( uint8_t const app,
28 // define the i2c app's app_t
29 app_t const i2c_app = {
41 "\tThe I2C app implements the i2c bus protocol thus\n"
42 "\tturning your GoodFET into a USB-to-i2c adapter.\n"
45 #define I2CDELAY(x) delay(x<<4)
48 //2xx only, need 1xx compat code
52 #define SDAINPUT SPIDIR&=~SDA
53 #define SDAOUTPUT SPIDIR|=SDA
54 #define SCLINPUT SPIDIR&=~SCL
55 #define SCLOUTPUT SPIDIR|=SCL
57 #define PULLON SPIREN|=(SDA|SCL)
58 #define PULLOFF SPIREN&=~(SDA|SCL)
60 #define CLRSDA SPIOUT&=~SDA
61 #define SETSDA SPIOUT|=SDA
62 #define CLRSCL SPIOUT&=~SCL
63 #define SETSCL SPIOUT|=SCL
65 #define READSDA (SPIIN&SDA?1:0)
66 #define SETBOTH SPIOUT|=(SDA|SCL)
68 #define I2C_DATA_HI() SETSDA
69 #define I2C_DATA_LO() CLRSDA
71 #define I2C_CLOCK_HI() SETSCL
72 #define I2C_CLOCK_LO() CLRSCL
74 //#warning "Using internal resistors. Won't work on 161x devices."
76 //! Inits bitbanging port, must be called before using the functions below
81 //Direction, not value, is used to set the value.
93 // This is never called...
101 //! Write an I2C bit.
102 void I2C_WriteBit( unsigned char c )
123 unsigned char I2C_ReadBit()
128 unsigned char c = READSDA;
141 unsigned char I2C_ReadBit_Wait()
147 unsigned char c = READSDA;
168 //! Send a START Condition
171 // set both to high at the same time
182 //! Send a STOP Condition
195 //! write a byte to the I2C slave device
196 unsigned char I2C_Write( unsigned char c )
200 I2C_WriteBit( c & 0x80 );
204 return I2C_ReadBit_Wait();
208 //! read a byte from the I2C slave device
209 unsigned char I2C_Read( unsigned char ack )
211 unsigned char res = 0;
216 res |= I2C_ReadBit();
229 //! Handles an i2c command.
230 void i2c_handle_fn( uint8_t const app,
240 if(l > 0) //optional parameter of length
242 if(!l) //default value of 1
246 cmddata[i]=I2C_Read(i<l?1:0);
253 cmddata[0]+=I2C_Write(cmddata[i]);
260 unsigned char address = cmddata[1]<<1;
262 for(i=2; i < len; i++){
263 I2C_Write(cmddata[i]);
266 I2C_Write(address|1); // spit out the target address again and flip the read bit
267 I2CDELAY(1); // XXX We should wait for clock to go high here XXX
269 cmddata[i]=I2C_Read(i+1<l?1:0); // If the next i is still less than l, then ACK