22
22
#include "cmsis.h"
23
23
#include "pinmap.h"
24
24
25
+ // Change to 1 to enable debug prints.
26
+ #define LPC1768_I2C_DEBUG 0
27
+
28
+ #if LPC1768_I2C_DEBUG
29
+ #include <stdio.h>
30
+ #include <inttypes.h>
31
+ #endif
32
+
25
33
static const PinMap PinMap_I2C_SDA [] = {
26
34
{P0_0 , I2C_1 , 3 },
27
35
{P0_10 , I2C_2 , 2 },
@@ -83,6 +91,10 @@ static int i2c_wait_SI(i2c_t *obj) {
83
91
return 0 ;
84
92
}
85
93
94
+ static inline void i2c_interface_disable (i2c_t * obj ) {
95
+ I2C_CONCLR (obj ) = 0x40 ;
96
+ }
97
+
86
98
static inline void i2c_interface_enable (i2c_t * obj ) {
87
99
I2C_CONSET (obj ) = 0x40 ;
88
100
}
@@ -107,17 +119,30 @@ void i2c_init(i2c_t *obj, PinName sda, PinName scl) {
107
119
108
120
// set default frequency at 100k
109
121
i2c_frequency (obj , 100000 );
122
+
123
+ // Reset the I2C peripheral by clearing all flags, including I2EN.
124
+ // This does a software reset of sorts, which is important because the I2C::recover()
125
+ // function, which is called before initializing the bus, seems to put the I2C
126
+ // peripheral in a weird state where the next transaction will fail.
127
+ i2c_interface_disable (obj );
110
128
i2c_conclr (obj , 1 , 1 , 1 , 1 );
129
+
111
130
i2c_interface_enable (obj );
112
131
113
132
pinmap_pinout (sda , PinMap_I2C_SDA );
133
+ pin_mode (sda , OpenDrain );
114
134
pinmap_pinout (scl , PinMap_I2C_SCL );
135
+ pin_mode (scl , OpenDrain );
115
136
}
116
137
117
138
inline int i2c_start (i2c_t * obj ) {
118
139
int status = 0 ;
119
140
int isInterrupted = I2C_CONSET (obj ) & (1 << 3 );
120
141
142
+ #if LPC1768_I2C_DEBUG
143
+ printf ("i2c_start(): status was originally 0x%x\n" , i2c_status (obj ));
144
+ #endif
145
+
121
146
// 8.1 Before master mode can be entered, I2CON must be initialised to:
122
147
// - I2EN STA STO SI AA - -
123
148
// - 1 0 0 x x - -
@@ -135,6 +160,10 @@ inline int i2c_start(i2c_t *obj) {
135
160
i2c_wait_SI (obj );
136
161
status = i2c_status (obj );
137
162
163
+ #if LPC1768_I2C_DEBUG
164
+ printf ("i2c_start(): status is now 0x%x\n" , status );
165
+ #endif
166
+
138
167
// Clear start bit now that it's transmitted
139
168
i2c_conclr (obj , 1 , 0 , 0 , 0 );
140
169
return status ;
@@ -303,6 +332,10 @@ int i2c_byte_read(i2c_t *obj, int last) {
303
332
int i2c_byte_write (i2c_t * obj , int data ) {
304
333
int ack ;
305
334
int status = i2c_do_write (obj , (data & 0xFF ), 0 );
335
+
336
+ #if LPC1768_I2C_DEBUG
337
+ printf ("i2c_do_write(0x%hhx) returned 0x%x\n" , data & 0xFF , status );
338
+ #endif
306
339
307
340
switch (status ) {
308
341
case 0x18 : case 0x28 : // Master transmit ACKs
0 commit comments