-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathtwi.rs
309 lines (252 loc) · 8.75 KB
/
twi.rs
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
//! HAL interface to the TWI peripheral.
use core::ops::Deref;
use crate::{
gpio::{Floating, Input, Pin},
pac::{twi0, GPIO, TWI0, TWI1},
};
pub use twi0::frequency::FREQUENCY_A as Frequency;
pub struct Twi<T>(T);
impl<T> Twi<T>
where
T: Instance,
{
pub fn new(twi: T, pins: Pins, frequency: Frequency) -> Self {
// The TWIM peripheral requires the pins to be in a mode that is not
// exposed through the GPIO API, and might it might not make sense to
// expose it there.
//
// Until we've figured out what to do about this, let's just configure
// the pins through the raw peripheral API. All of the following is
// safe, as we own the pins now and have exclusive access to their
// registers.
for &pin in &[pins.scl.pin(), pins.sda.pin()] {
unsafe { &*GPIO::ptr() }.pin_cnf[pin as usize].write(|w| {
w.dir()
.input()
.input()
.connect()
.pull()
.pullup()
.drive()
.s0d1()
.sense()
.disabled()
});
}
// Set pins.
twi.pselscl
.write(|w| unsafe { w.bits(pins.scl.pin().into()) });
twi.pselsda
.write(|w| unsafe { w.bits(pins.sda.pin().into()) });
// Set frequency.
twi.frequency.write(|w| w.frequency().variant(frequency));
twi.enable.write(|w| w.enable().enabled());
Self(twi)
}
fn send_byte(&self, byte: u8) -> Result<(), Error> {
// Clear sent event.
self.0.events_txdsent.write(|w| unsafe { w.bits(0) });
// Copy data into the send buffer.
self.0.txd.write(|w| unsafe { w.bits(u32::from(byte)) });
// Wait until transmission was confirmed.
while self.0.events_txdsent.read().bits() == 0 {
// Bail out if we get an error instead.
if self.0.events_error.read().bits() != 0 {
self.0.events_error.write(|w| unsafe { w.bits(0) });
return Err(Error::Transmit);
}
}
// Clear sent event.
self.0.events_txdsent.write(|w| unsafe { w.bits(0) });
Ok(())
}
fn recv_byte(&self) -> Result<u8, Error> {
// Wait until something ended up in the buffer.
while self.0.events_rxdready.read().bits() == 0 {
// Bail out if it's an error instead of data.
if self.0.events_error.read().bits() != 0 {
self.0.events_error.write(|w| unsafe { w.bits(0) });
return Err(Error::Receive);
}
}
// Read out data.
let out = self.0.rxd.read().bits() as u8;
// Clear reception event.
self.0.events_rxdready.write(|w| unsafe { w.bits(0) });
Ok(out)
}
fn send_stop(&self) -> Result<(), Error> {
// Clear stopped event.
self.0.events_stopped.write(|w| unsafe { w.bits(0) });
// Start stop condition.
self.0.tasks_stop.write(|w| unsafe { w.bits(1) });
// Wait until stop was sent.
while self.0.events_stopped.read().bits() == 0 {
// Bail out if we get an error instead.
if self.0.events_error.read().bits() != 0 {
self.0.events_error.write(|w| unsafe { w.bits(0) });
return Err(Error::Transmit);
}
}
Ok(())
}
/// Write to an I2C slave.
pub fn write(&mut self, address: u8, buffer: &[u8]) -> Result<(), Error> {
// Make sure all previously used shortcuts are disabled.
self.0
.shorts
.write(|w| w.bb_stop().disabled().bb_suspend().disabled());
// Set Slave I2C address.
self.0
.address
.write(|w| unsafe { w.address().bits(address.into()) });
// Start data transmission.
self.0.tasks_starttx.write(|w| unsafe { w.bits(1) });
// Clock out all bytes.
for byte in buffer {
self.send_byte(*byte)?;
}
// Send stop.
self.send_stop()?;
Ok(())
}
/// Read from an I2C slave.
pub fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error> {
// Make sure all previously used shortcuts are disabled.
self.0
.shorts
.write(|w| w.bb_stop().disabled().bb_suspend().disabled());
// Set Slave I2C address.
self.0
.address
.write(|w| unsafe { w.address().bits(address.into()) });
// Read into buffer.
if let Some((last, before)) = buffer.split_last_mut() {
// If we want to read multiple bytes we need to use the suspend mode.
if !before.is_empty() {
self.0.shorts.write(|w| w.bb_suspend().enabled());
} else {
self.0.shorts.write(|w| w.bb_stop().enabled());
}
// Clear reception event.
self.0.events_rxdready.write(|w| unsafe { w.bits(0) });
// Start data reception.
self.0.tasks_startrx.write(|w| unsafe { w.bits(1) });
for byte in &mut before.into_iter() {
self.0.tasks_resume.write(|w| unsafe { w.bits(1) });
*byte = self.recv_byte()?;
}
self.0.shorts.write(|w| w.bb_stop().enabled());
self.0.tasks_resume.write(|w| unsafe { w.bits(1) });
*last = self.recv_byte()?;
} 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: u8,
wr_buffer: &[u8],
rd_buffer: &mut [u8],
) -> Result<(), Error> {
// Make sure all previously used shortcuts are disabled.
self.0
.shorts
.write(|w| w.bb_stop().disabled().bb_suspend().disabled());
// Set Slave I2C address.
self.0
.address
.write(|w| unsafe { w.address().bits(address.into()) });
// Start data transmission.
self.0.tasks_starttx.write(|w| unsafe { w.bits(1) });
// Send out all bytes in the outgoing buffer.
for byte in wr_buffer {
self.send_byte(*byte)?;
}
// Turn around to read data.
if let Some((last, before)) = rd_buffer.split_last_mut() {
// If we want to read multiple bytes we need to use the suspend mode.
if !before.is_empty() {
self.0.shorts.write(|w| w.bb_suspend().enabled());
} else {
self.0.shorts.write(|w| w.bb_stop().enabled());
}
// Clear reception event.
self.0.events_rxdready.write(|w| unsafe { w.bits(0) });
// Start data reception.
self.0.tasks_startrx.write(|w| unsafe { w.bits(1) });
for byte in &mut before.into_iter() {
self.0.tasks_resume.write(|w| unsafe { w.bits(1) });
*byte = self.recv_byte()?;
}
self.0.shorts.write(|w| w.bb_stop().enabled());
self.0.tasks_resume.write(|w| unsafe { w.bits(1) });
*last = self.recv_byte()?;
} else {
self.send_stop()?;
}
Ok(())
}
/// Return the raw interface to the underlying TWI peripheral.
pub fn free(self) -> T {
self.0
}
}
impl<T> embedded_hal::blocking::i2c::Write for Twi<T>
where
T: Instance,
{
type Error = Error;
fn write<'w>(&mut self, addr: u8, bytes: &'w [u8]) -> Result<(), Error> {
self.write(addr, bytes)
}
}
impl<T> embedded_hal::blocking::i2c::Read for Twi<T>
where
T: Instance,
{
type Error = Error;
fn read<'w>(&mut self, addr: u8, bytes: &'w mut [u8]) -> Result<(), Error> {
self.read(addr, bytes)
}
}
impl<T> embedded_hal::blocking::i2c::WriteRead for Twi<T>
where
T: Instance,
{
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, bytes, buffer)
}
}
/// The pins used by the TWI peripheral.
///
/// Currently, only P0 pins are supported.
pub struct Pins {
// Serial Clock Line.
pub scl: Pin<Input<Floating>>,
// Serial Data Line.
pub sda: Pin<Input<Floating>>,
}
#[derive(Debug)]
pub enum Error {
Transmit,
Receive,
}
/// Implemented by all TWIM instances.
pub trait Instance: Deref<Target = twi0::RegisterBlock> + sealed::Sealed {}
mod sealed {
pub trait Sealed {}
}
impl sealed::Sealed for TWI0 {}
impl Instance for TWI0 {}
impl sealed::Sealed for TWI1 {}
impl Instance for TWI1 {}