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
#[cfg(test)]
mod tests {
use super::Mcp3208;
use std::path::Path;
use std::env;
use crate::Channel;
use std::convert::TryFrom;
#[test]
fn mcp3208_read_adc_single() {
let spi_dev_path = "/dev/spidev0.0";
if cfg!(target_os = "linux") {
if Path::new(&spi_dev_path).exists() {
let mut mcp3208 = Mcp3208::new(spi_dev_path).unwrap();
mcp3208.read_adc_single(Channel::Ch0).unwrap();
if let Ok(_) = Channel::try_from(8) {
panic!("read from adc > 7");
}
} else {
if let Ok(_) = env::var("TRAVIS_RUST_VERSION") {
println!("can't mock spi interface on travis, passing test...");
} else {
panic!("can not test on current setup (no spi interface)");
}
}
} else {
panic!("can not test on current setup (unsupported os)");
}
}
}
#[cfg(target_os = "linux")]
extern crate spidev;
use std::io;
use std::fmt;
use std::error::Error;
const FRAME_BIT_COUNT: u8 = 32;
const START_BIT_COUNT: u8 = 1;
const START_BIT_INDEX: u8 = FRAME_BIT_COUNT - START_BIT_COUNT;
const MODE_BIT_COUNT: u8 = 1;
const MODE_BIT_INDEX: u8 = START_BIT_INDEX - MODE_BIT_COUNT;
const CHANNEL_BIT_COUNT: u8 = 3;
const CHANNEL_BITS_INDEX: u8 = MODE_BIT_INDEX - CHANNEL_BIT_COUNT;
const CHANNEL_COUNT: u8 = 1 << CHANNEL_BIT_COUNT;
const WAIT_BIT_COUNT: u8 = 1;
const WAIT_BIT_INDEX: u8 = CHANNEL_BITS_INDEX - WAIT_BIT_COUNT;
const ZERO_BIT_COUNT: u8 = 1;
const ZERO_BIT_INDEX: u8 = WAIT_BIT_INDEX - ZERO_BIT_COUNT;
const SAMPLE_BIT_COUNT: u8 = 12;
const SAMPLE_BITS_INDEX: u8 = ZERO_BIT_INDEX - SAMPLE_BIT_COUNT;
const CHECKSUM_BIT_COUNT: u8 = SAMPLE_BIT_COUNT - 1;
const CHECKSUM_BITS_INDEX: u8 = SAMPLE_BITS_INDEX - CHECKSUM_BIT_COUNT;
const PADDING_BIT_COUNT: u8 = CHECKSUM_BITS_INDEX;
const PADDING_BITS_INDEX: u8 = 0;
const SAMPLE_LSB_INDEX: i8 = SAMPLE_BITS_INDEX as i8;
const SAMPLE_LSB_MIRRORED_INDEX: i8 = (FRAME_BIT_COUNT - 1) as i8 - SAMPLE_LSB_INDEX;
const SAMPLE_LSB_SHR: i8 = (FRAME_BIT_COUNT - 1) as i8 - 2 * SAMPLE_BITS_INDEX as i8;
const ZERO_VALIDATION_MASK: u32 =
mask(START_BIT_COUNT) << START_BIT_INDEX |
mask(MODE_BIT_COUNT) << MODE_BIT_INDEX |
mask(CHANNEL_BIT_COUNT) << CHANNEL_BITS_INDEX |
mask(WAIT_BIT_COUNT) << WAIT_BIT_INDEX |
mask(ZERO_BIT_COUNT) << ZERO_BIT_INDEX |
mask(PADDING_BIT_COUNT) << PADDING_BITS_INDEX;
const fn mask(length: u8) -> u32 {
(0x0000_0000_ffff_ffff_u64 >> (32 - length)) as u32
}
#[cfg(target_os = "linux")]
use spidev::{Spidev, SpidevOptions, SpidevTransfer, SpiModeFlags};
use std::cmp::Ordering;
use std::convert::TryFrom;
#[derive(Debug, Copy, Clone)]
#[repr(u8)]
pub enum Channel {
Ch0 = 0x0, Ch1, Ch2, Ch3, Ch4, Ch5, Ch6, Ch7
}
impl Channel {
pub const VALUES: [Channel; 8] = [
Channel::Ch0, Channel::Ch1, Channel::Ch2, Channel::Ch3,
Channel::Ch4, Channel::Ch5, Channel::Ch6, Channel::Ch7
];
pub fn partner(self) -> Self {
Self::VALUES[(self as u8 ^ 0b001) as usize]
}
}
impl TryFrom<u8> for Channel {
type Error = Mcp3208Error;
fn try_from(channel_index: u8) -> Result<Self, Self::Error> {
if channel_index < CHANNEL_COUNT {
Ok(Channel::VALUES[channel_index as usize])
} else {
Err(Mcp3208Error::AdcOutOfRangeError(channel_index))
}
}
}
#[derive(Debug)]
pub enum Mcp3208Error {
SpidevError(io::Error),
AdcOutOfRangeError(u8),
UnsupportedOSError,
DataError(String),
}
impl fmt::Display for Mcp3208Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Mcp3208Error::SpidevError(ref err) => err.fmt(f),
Mcp3208Error::AdcOutOfRangeError(adc_number) => {
write!(f, "invalid adc number ({})", adc_number)
}
Mcp3208Error::UnsupportedOSError => write!(f, "unsupported os"),
Mcp3208Error::DataError(ref message) => f.write_str(message),
}
}
}
impl Error for Mcp3208Error {
fn cause(&self) -> Option<&dyn Error> {
match *self {
Mcp3208Error::SpidevError(ref err) => Some(err),
Mcp3208Error::AdcOutOfRangeError(_) => None,
Mcp3208Error::UnsupportedOSError => None,
Mcp3208Error::DataError(_) => None,
}
}
}
impl From<io::Error> for Mcp3208Error {
fn from(err: io::Error) -> Mcp3208Error {
Mcp3208Error::SpidevError(err)
}
}
pub struct Mcp3208 {
#[cfg(target_os = "linux")]
spi: Spidev,
}
impl Mcp3208 {
#[cfg(target_os = "linux")]
pub fn new(spi_dev_path: &str) -> Result<Mcp3208, Mcp3208Error> {
let options = SpidevOptions::new()
.max_speed_hz(1_000_000)
.mode(SpiModeFlags::SPI_MODE_0)
.lsb_first(false)
.build();
let mut spi = Spidev::open(spi_dev_path.to_string())?;
match spi.configure(&options) {
Ok(_) => Ok(Mcp3208 { spi }),
Err(err) => Err(Mcp3208Error::SpidevError(err)),
}
}
#[cfg(not(target_os = "linux"))]
pub fn new(_spi_dev_path: &str) -> Result<Mcp3208, Mcp3208Error> {
Err(Mcp3208Error::UnsupportedOSError)
}
#[cfg(target_os = "linux")]
pub fn read_adc_single(&mut self, channel: Channel) -> Result<u16, Mcp3208Error> {
let request = Self::build_request(false, channel);
let response = self.send_request(request)?;
Self::parse_response(response)
}
#[cfg(target_os = "linux")]
pub fn read_adc_diff(&mut self, channel: Channel) -> Result<u16, Mcp3208Error> {
let request = Self::build_request(true, channel);
let response = self.send_request(request)?;
Self::parse_response(response)
}
#[inline]
fn build_request(is_differential: bool, channel: Channel) -> u32 {
let start_bits = 1u32 << START_BIT_INDEX;
let mode_bits = if is_differential { 0u32 } else { 1u32 } << MODE_BIT_INDEX;
let channel_selection_bits = (channel as u32) << CHANNEL_BITS_INDEX;
start_bits | mode_bits | channel_selection_bits
}
#[inline]
fn send_request(&self, request: u32) -> Result<u32, Mcp3208Error> {
let tx_buf = request.to_be_bytes();
let mut rx_buf = [0_u8; 4];
let mut transfer = SpidevTransfer::read_write(&tx_buf, &mut rx_buf);
self.spi.transfer(&mut transfer)?;
Ok(u32::from_be_bytes(rx_buf))
}
#[cfg(not(target_os = "linux"))]
fn send_request(&self, command: u32) -> Result<u32, Mcp3208Error> {
Err(Mcp3208Error::UnsupportedOSError)
}
#[inline]
fn parse_response(response_bits: u32) -> Result<u16, Mcp3208Error> {
if response_bits & ZERO_VALIDATION_MASK != 0 {
return Err(Mcp3208Error::DataError(format!("invalid response: 0x{:04x}", response_bits)));
}
let reversed = response_bits.reverse_bits();
let checksum = match i8::cmp(&SAMPLE_LSB_INDEX, &SAMPLE_LSB_MIRRORED_INDEX) {
Ordering::Less => reversed >> SAMPLE_LSB_SHR.abs(),
Ordering::Equal => reversed,
Ordering::Greater => reversed >> SAMPLE_LSB_SHR.abs(),
};
if response_bits != checksum {
return Err(Mcp3208Error::DataError(format!("invalid checksum: 0x{:04x}", response_bits)));
}
Ok((response_bits >> SAMPLE_BITS_INDEX) as u16)
}
}