]> git.gir.st - tmk_keyboard.git/blob - tool/mbed/mbed-sdk/libraries/tests/peripherals/SRF08/SRF08.cpp
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[tmk_keyboard.git] / tool / mbed / mbed-sdk / libraries / tests / peripherals / SRF08 / SRF08.cpp
1
2 /*
3 Copyright (c) 2010 Chris Styles ( chris dot styles at mbed dot org )
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in
13 all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 THE SOFTWARE.
22 */
23
24 #include "SRF08.h"
25
26
27 SRF08::SRF08(PinName sda, PinName scl, int addr) : m_i2c(sda, scl), m_addr(addr) {
28 char cmd[2];
29
30 // Set up SRF08 max range and receiver sensitivity over I2C bus
31 cmd[0] = 0x02; // Range register
32 cmd[1] = 0x1C; // Set max range about 100cm
33 m_i2c.write(m_addr, cmd, 2);
34 cmd[0] = 0x01; // Receiver gain register
35 cmd[1] = 0x1B; // Set max receiver gain
36 m_i2c.write(m_addr, cmd, 2);
37
38 }
39
40 SRF08::~SRF08() {
41
42 }
43
44 float SRF08::read() {
45
46 char cmd[2];
47 char echo[2];
48
49
50 // Get range data from SRF08
51 // Send Tx burst command over I2C bus
52 cmd[0] = 0x00; // Command register
53 cmd[1] = 0x51; // Ranging results in cm
54 m_i2c.write(m_addr, cmd, 2); // Send ranging burst
55
56 wait(0.07); // Wait for return echo
57
58 // Read back range over I2C bus
59 cmd[0] = 0x02; // Address of first echo
60 m_i2c.write(m_addr, cmd, 1, 1); // Send address of first echo
61 m_i2c.read(m_addr, echo, 2); // Read two-byte echo result
62
63 // Generate PWM mark/space ratio from range data
64 float range = (echo[0]<<8)+echo[1];
65
66 return range;
67 }
Imprint / Impressum