1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
10 * Copyright (C) 2008 by Rob Purchase
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
25 #include "i2c-target.h"
27 /* Delay loop based on CPU frequency (FREQ>>22 is 7..45 for 32MHz..192MHz) */
28 static inline void delay_loop(void)
31 for (x
= (unsigned)(FREQ
>>22); x
; x
--);
33 #define DELAY delay_loop()
35 static struct mutex i2c_mtx
;
69 void i2c_outb(unsigned char byte
)
75 for (bit
= 0; bit
< 8; bit
++)
77 if ((byte
<<bit
) & 0x80)
91 unsigned char i2c_inb(int ack
)
94 unsigned char byte
= 0;
98 /* clock in each bit, MSB first */
99 for ( i
=0x80; i
; i
>>=1 )
104 if ( SDA
) byte
|= i
;
114 void i2c_ack(int bit
)
147 /* device = 8 bit slave address */
148 int i2c_write(int device
, const unsigned char* buf
, int count
)
151 mutex_lock(&i2c_mtx
);
154 i2c_outb(device
& 0xfe);
156 while (!i2c_getack() && i
< count
)
162 mutex_unlock(&i2c_mtx
);
167 /* device = 8 bit slave address */
168 int i2c_readmem(int device
, int address
, unsigned char* buf
, int count
)
171 mutex_lock(&i2c_mtx
);
174 i2c_outb(device
& 0xfe);
175 if (i2c_getack()) goto exit
;
178 if (i2c_getack()) goto exit
;
181 i2c_outb(device
| 1);
182 if (i2c_getack()) goto exit
;
186 buf
[i
] = i2c_inb(i
== (count
-1));
192 mutex_unlock(&i2c_mtx
);