Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SRF08.cpp 2.3KB

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