1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! HAL interface to the I2C peripheral.
use core::ops::Deref;
use crate::{
crg_top::CrgTop,
gpio::{AfI2cScl, AfI2cSda, Pin},
pac::{i2c, I2C},
};
/// Extension trait that constrains the `SYS_WDOG` peripheral
pub trait I2cExt {
/// Constrains the `SYS_WDOG` peripheral so it plays nicely with the other abstractions
fn constrain(self) -> I2c;
}
impl I2cExt for I2C {
fn constrain(self) -> I2c {
I2c {
i2c: self,
pins: None,
speed: Default::default(),
addressing_mode: Default::default(),
}
}
}
pub enum Speed {
/// 100 kbit/s
Standard,
/// 400 kbit/s
FullSpeed,
}
impl Default for Speed {
fn default() -> Self {
Speed::Standard
}
}
pub enum AddressingMode {
Bits7,
Bits10,
}
impl Default for AddressingMode {
fn default() -> Self {
AddressingMode::Bits7
}
}
struct Pins {
_sda: Pin<AfI2cSda>,
_scl: Pin<AfI2cScl>,
}
impl Pins {
fn new(sda: Pin<AfI2cSda>, scl: Pin<AfI2cScl>) -> Self {
Self {
_scl: scl,
_sda: sda,
}
}
}
pub struct I2c {
i2c: I2C,
pins: Option<Pins>,
speed: Speed,
addressing_mode: AddressingMode,
}
impl I2c {
pub fn set_pins(mut self, sda: Pin<AfI2cSda>, scl: Pin<AfI2cScl>) -> Self {
self.pins = Some(Pins::new(sda, scl));
self
}
pub fn set_speed(mut self, speed: Speed) -> Self {
self.speed = speed;
self
}
pub fn set_addressing_mode(mut self, addressing_mode: AddressingMode) -> Self {
self.addressing_mode = addressing_mode;
self
}
pub fn start(&self, crg_top: &CrgTop) {
assert!(self.pins.is_some());
// Enable peripheral clock
CrgTop::enable_peripheral::<I2C>(&crg_top);
// Disable the I2C Controller
self.i2c
.i2c_enable_reg
.write(|w| w.ctrl_enable().clear_bit());
// There is a two ic_clk delay when enabling or disabling the controller
while self.i2c.i2c_enable_reg.read().ctrl_enable().bit() {}
// Enable all interrupts
self.i2c.i2c_intr_mask_reg.write(|w| unsafe { w.bits(0) });
self.i2c
.i2c_ss_scl_hcnt_reg
.write(|w| unsafe { w.bits(0x00000048) });
self.i2c
.i2c_ss_scl_lcnt_reg
.write(|w| unsafe { w.bits(0x0000004F) });
self.i2c.i2c_con_reg.write(|w| {
// Configure the speed mode
unsafe {
w.i2c_speed().bits(match self.speed {
Speed::Standard => 1,
Speed::FullSpeed => 2,
});
}
// Setup as I2C master
w.i2c_master_mode().set_bit();
w.i2c_slave_disable().set_bit();
// Configure addressing mode
match self.addressing_mode {
AddressingMode::Bits7 => {
w.i2c_10bitaddr_master().clear_bit();
}
AddressingMode::Bits10 => {
w.i2c_10bitaddr_master().set_bit();
}
}
w
});
// Set threshold for RX/TX FIFO
self.i2c
.i2c_rx_tl_reg
.write(|w| unsafe { w.rx_tl().bits(0) });
self.i2c
.i2c_tx_tl_reg
.write(|w| unsafe { w.rx_tl().bits(0) });
// Enable the I2C Controller
self.i2c.i2c_enable_reg.write(|w| w.ctrl_enable().set_bit());
// There is a two ic_clk delay when enabling or disabling the controller
while !self.i2c.i2c_enable_reg.read().ctrl_enable().bit() {}
}
fn send_byte(&self, byte: u8) -> Result<(), Error> {
crate::cm::interrupt::free(|_| {
// Prepare to transmit the write command byte
self.i2c.i2c_data_cmd_reg.write(|w| {
w.i2c_cmd().clear_bit();
unsafe {
w.dat().bits(byte);
}
w
});
});
// Wait until TX FIFO is empty
while self.i2c.i2c_status_reg.read().tfe().bit_is_clear() {}
// Wait until master has finished reading the response byte from slave device
while self.i2c.i2c_status_reg.read().mst_activity().bit_is_set() {}
// Read the I2C_TX_ABRT_SOURCE_REG register
let abort_source = self.i2c.i2c_tx_abrt_source_reg.read().bits();
if abort_source != 0 {
self.i2c.i2c_clr_tx_abrt_reg.read().bits();
Err(Error::Transmit)
} else {
Ok(())
}
}
fn recv_byte(&self) -> Result<u8, Error> {
crate::cm::interrupt::free(|_| {
// Prepare to transmit the read command byte
self.i2c.i2c_data_cmd_reg.write(|w| w.i2c_cmd().set_bit());
});
// Wait for received data
while self.i2c.i2c_rxflr_reg.read().rxflr().bits() == 0 {}
let out = self.i2c.i2c_data_cmd_reg.read().dat().bits();
// Wait until TX FIFO is empty
while self.i2c.i2c_status_reg.read().tfe().bit_is_clear() {}
// Wait until master has finished reading the byte from slave device
while self.i2c.i2c_status_reg.read().mst_activity().bit_is_set() {}
Ok(out)
}
fn recv_byte_stop(&self) -> Result<u8, Error> {
crate::cm::interrupt::free(|_| {
// Prepare to transmit the read command byte
self.i2c.i2c_data_cmd_reg.write(|w| {
w.i2c_stop().set_bit();
w.i2c_cmd().set_bit();
w
});
});
// Wait for received data
while self.i2c.i2c_rxflr_reg.read().rxflr().bits() == 0 {}
let out = self.i2c.i2c_data_cmd_reg.read().dat().bits();
// Wait until TX FIFO is empty
while self.i2c.i2c_status_reg.read().tfe().bit_is_clear() {}
// Wait until master has finished reading the byte from slave device
while self.i2c.i2c_status_reg.read().mst_activity().bit_is_set() {}
Ok(out)
}
// TODO: Implement section
fn send_byte_stop(&self, byte: u8) -> Result<(), Error> {
// // Clear stopped event.
// self.i2c.events_stopped.write(|w| unsafe { w.bits(0) });
// // Start stop condition.
// self.i2c.tasks_stop.write(|w| unsafe { w.bits(1) });
// // Wait until stop was sent.
// while self.i2c.events_stopped.read().bits() == 0 {
// // Bail out if we get an error instead.
// if self.i2c.events_error.read().bits() != 0 {
// self.i2c.events_error.write(|w| unsafe { w.bits(0) });
// return Err(Error::Transmit);
// }
// }
crate::cm::interrupt::free(|_| {
// Prepare to transmit the write command byte
self.i2c.i2c_data_cmd_reg.write(|w| {
w.i2c_cmd().clear_bit();
w.i2c_stop().set_bit();
unsafe {
w.dat().bits(byte);
}
w
});
});
// Wait until TX FIFO is empty
while self.i2c.i2c_status_reg.read().tfe().bit_is_clear() {}
// Wait until master has finished reading the response byte from slave device
while self.i2c.i2c_status_reg.read().mst_activity().bit_is_set() {}
// Read the I2C_TX_ABRT_SOURCE_REG register
let abort_source = self.i2c.i2c_tx_abrt_source_reg.read().bits();
if abort_source != 0 {
self.i2c.i2c_clr_tx_abrt_reg.read().bits();
Err(Error::Transmit)
} else {
Ok(())
}
}
/// Write to an I2C slave.
pub fn write(&mut self, address: u16, buffer: &[u8]) -> Result<(), Error> {
self.set_slave_address(address);
// Clock out all bytes.
if let Some((last, before)) = buffer.split_last() {
for byte in &mut before.into_iter() {
self.send_byte(*byte)?;
}
self.send_byte_stop(*last)?;
}
Ok(())
}
/// Read from an I2C slave.
pub fn read(&mut self, address: u16, buffer: &mut [u8]) -> Result<(), Error> {
self.set_slave_address(address);
// Read into buffer.
if let Some((last, before)) = buffer.split_last_mut() {
for byte in &mut before.into_iter() {
*byte = self.recv_byte()?;
}
*last = self.recv_byte_stop()?;
}
// else {
// self.send_stop()?;
// }
Ok(())
}
/// Write data to an I2C slave, then read data from the slave without
/// triggering a stop condition between the two.
pub fn write_then_read(
&mut self,
address: u16,
wr_buffer: &[u8],
rd_buffer: &mut [u8],
) -> Result<(), Error> {
self.set_slave_address(address);
// Send out all bytes in the outgoing buffer.
if let Some((last, before)) = wr_buffer.split_last() {
for byte in before {
self.send_byte(*byte)?;
}
self.send_byte_stop(*last)?;
}
// Turn around to read data.
if let Some((last, before)) = rd_buffer.split_last_mut() {
for byte in &mut before.into_iter() {
*byte = self.recv_byte()?;
}
*last = self.recv_byte_stop()?;
}
// else {
// self.send_stop()?;
// }
Ok(())
}
fn set_slave_address(&mut self, address: u16) {
self.i2c
.i2c_enable_reg
.modify(|_, w| w.ctrl_enable().clear_bit());
while self.i2c.i2c_enable_reg.read().ctrl_enable().bit() {}
// Set Slave I2C address.
self.i2c
.i2c_tar_reg
.modify(|_, w| unsafe { w.ic_tar().bits(address) });
self.i2c
.i2c_enable_reg
.modify(|_, w| w.ctrl_enable().set_bit());
while !self.i2c.i2c_enable_reg.read().ctrl_enable().bit() {}
}
// TODO: port this section!
// /// Return the raw interface to the underlying TWI peripheral.
// pub fn free(self) -> (T, Pins) {
// let scl = self.i2c.pselscl.read();
// let sda = self.i2c.pselsda.read();
// self.i2c.pselscl.reset();
// self.i2c.pselsda.reset();
// (
// self.i2c,
// Pins {
// scl: unsafe { Pin::from_psel_bits(scl.bits()) },
// sda: unsafe { Pin::from_psel_bits(sda.bits()) },
// },
// )
// }
}
impl embedded_hal::blocking::i2c::Write for I2c {
type Error = Error;
fn write<'w>(&mut self, addr: u8, bytes: &'w [u8]) -> Result<(), Error> {
self.write(addr as u16, bytes)
}
}
impl embedded_hal::blocking::i2c::Read for I2c {
type Error = Error;
fn read<'w>(&mut self, addr: u8, bytes: &'w mut [u8]) -> Result<(), Error> {
self.read(addr as u16, bytes)
}
}
impl embedded_hal::blocking::i2c::WriteRead for I2c {
type Error = Error;
fn write_read<'w>(
&mut self,
addr: u8,
bytes: &'w [u8],
buffer: &'w mut [u8],
) -> Result<(), Error> {
self.write_then_read(addr as u16, bytes, buffer)
}
}
#[derive(Debug)]
pub enum Error {
Transmit,
Receive,
}
pub trait Instance: Deref<Target = i2c::RegisterBlock> + sealed::Sealed {}
mod sealed {
pub trait Sealed {}
}
impl sealed::Sealed for I2C {}
impl Instance for I2C {}