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
--)
35 #define DELAY delay_loop()
37 static struct mutex i2c_mtx
;
71 void i2c_outb(unsigned char byte
)
77 for (bit
= 0; bit
< 8; bit
++)
79 if ((byte
<<bit
) & 0x80)
93 unsigned char i2c_inb(int ack
)
96 unsigned char byte
= 0;
100 /* clock in each bit, MSB first */
101 for ( i
=0x80; i
; i
>>=1 )
106 if ( SDA
) byte
|= i
;
116 void i2c_ack(int bit
)
149 /* device = 8 bit slave address */
150 int i2c_write(int device
, const unsigned char* buf
, int count
)
153 mutex_lock(&i2c_mtx
);
156 i2c_outb(device
& 0xfe);
158 while (!i2c_getack() && i
< count
)
164 mutex_unlock(&i2c_mtx
);
169 /* device = 8 bit slave address */
170 int i2c_readmem(int device
, int address
, unsigned char* buf
, int count
)
173 mutex_lock(&i2c_mtx
);
176 i2c_outb(device
& 0xfe);
177 if (i2c_getack()) goto exit
;
180 if (i2c_getack()) goto exit
;
183 i2c_outb(device
| 1);
184 if (i2c_getack()) goto exit
;
188 buf
[i
] = i2c_inb(i
== (count
-1));
194 mutex_unlock(&i2c_mtx
);