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)
30 asm volatile (" mov %[freq], %[freq], asr#22 \n\t"
31 "1: subs %[freq], %[freq], #1 \n\t"
33 : : [freq
] "r" (cpu_frequency
) : "memory");
36 #define DELAY delay_loop()
38 static struct mutex i2c_mtx
;
72 void i2c_outb(unsigned char byte
)
78 for (bit
= 0; bit
< 8; bit
++)
80 if ((byte
<<bit
) & 0x80)
94 unsigned char i2c_inb(int ack
)
97 unsigned char byte
= 0;
101 /* clock in each bit, MSB first */
102 for ( i
=0x80; i
; i
>>=1 )
107 if ( SDA
) byte
|= i
;
117 void i2c_ack(int bit
)
150 /* device = 8 bit slave address */
151 int i2c_write(int device
, const unsigned char* buf
, int count
)
154 mutex_lock(&i2c_mtx
);
157 i2c_outb(device
& 0xfe);
159 while (!i2c_getack() && i
< count
)
165 mutex_unlock(&i2c_mtx
);
170 /* device = 8 bit slave address */
171 int i2c_readmem(int device
, int address
, unsigned char* buf
, int count
)
174 mutex_lock(&i2c_mtx
);
177 i2c_outb(device
& 0xfe);
178 if (i2c_getack()) goto exit
;
181 if (i2c_getack()) goto exit
;
184 i2c_outb(device
| 1);
185 if (i2c_getack()) goto exit
;
189 buf
[i
] = i2c_inb(i
== (count
-1));
195 mutex_unlock(&i2c_mtx
);