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
#![deny(warnings)]
#![feature(pattern_parentheses)]
#![feature(unsize)]
#![no_std]
extern crate embedded_hal as hal;
extern crate cast;
use hal::blocking::i2c::{Write, WriteRead};
use core::mem;
use cast::u8;
pub const ADDRESS: u8 = 0x4c;
pub const SENSITIVITY: f32 = 21.33;
#[allow(dead_code)]
#[derive(Copy, Clone)]
pub enum Register {
XOUT = 0x00,
YOUT = 0x01,
ZOUT = 0x02,
TILT = 0x03,
SRST = 0x04,
SPCNT = 0x05,
INTSU = 0x06,
MODE = 0x07,
SR = 0x08,
PDET = 0x09,
PD = 0x0A
}
impl Register {
fn addr(&self) -> u8 {
*self as u8
}
}
#[derive(Debug)]
pub struct I8x3 {
pub x: i8,
pub y: i8,
pub z: i8,
}
#[derive(Debug)]
pub struct Ax3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
#[allow(dead_code)]
#[derive(Copy, Clone)]
pub enum Mode {
STANDBY = 0x00,
ACTIVE =0x01
}
impl Mode {
fn bits(&self) -> u8 {
*self as u8
}
}
pub struct Mma7660fc<I2C> {
pub i2c: I2C
}
impl <I2C, E> Mma7660fc <I2C>
where I2C : WriteRead<Error = E> + Write<Error = E>,
{
pub fn new(i2c: I2C) -> Result<Self, E> {
let mut mma7660fc = Mma7660fc { i2c };
mma7660fc.write_register(Register::MODE,Mode::ACTIVE.bits())?;
mma7660fc.write_register(Register::SR,0x04)?;
Ok(mma7660fc)
}
pub fn write_register(&mut self,reg:Register,data:u8)->Result<(), E>{
self.i2c.write(ADDRESS,&[reg.addr(),data])
}
pub fn set_mode(&mut self, mode:Mode) -> Result<(), E>{
self.write_register(Register::MODE,mode.bits())
}
pub fn get_xyz(&mut self) -> Result<I8x3,E>{
let mut buffer: [u8; 3] = unsafe { mem::uninitialized() };
self.i2c.write_read(ADDRESS,&[Register::XOUT.addr()],& mut buffer)?;
let mut raw_x = u8( (buffer[0]) & 0x3F) as i8;
let mut raw_y= u8( (buffer[1]) & 0x3F) as i8;
let mut raw_z = u8( (buffer[2]) & 0x3F) as i8;
if raw_x > 31{
raw_x -= 64;
}
if raw_y > 31{
raw_y -= 64;
}
if raw_z > 31{
raw_z -= 64;
}
Ok(I8x3 {
x: raw_x,
y: raw_y,
z: raw_z,
})
}
pub fn get_acceleration(&mut self) ->Result<Ax3,E>{
let raw = self.get_xyz()?;
Ok(Ax3{
x: (raw.x as f32 )/ SENSITIVITY,
y: (raw.y as f32 ) / SENSITIVITY,
z: (raw.z as f32)/ SENSITIVITY
})
}
}