A Library to control I2C SRF02 sensor
SRF02.cpp@1:6b978ea41787, 2011-12-16 (annotated)
- Committer:
- bobboteck
- Date:
- Fri Dec 16 14:09:37 2011 +0000
- Revision:
- 1:6b978ea41787
- Parent:
- 0:8ac34d529a3b
Modified Oxygen tag
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
bobboteck | 0:8ac34d529a3b | 1 | #include "SRF02.h" |
bobboteck | 0:8ac34d529a3b | 2 | |
bobboteck | 0:8ac34d529a3b | 3 | /* Creates an instance of class. Setting the pin used for I2C, the address of device and the measure range type. */ |
bobboteck | 0:8ac34d529a3b | 4 | SRF02::SRF02(PinName sda, PinName scl, int addr, char type) : _i2c(sda, scl), _addr(addr) |
bobboteck | 0:8ac34d529a3b | 5 | { |
bobboteck | 0:8ac34d529a3b | 6 | _typem = type; |
bobboteck | 0:8ac34d529a3b | 7 | } |
bobboteck | 0:8ac34d529a3b | 8 | |
bobboteck | 0:8ac34d529a3b | 9 | /* Destroyer of class instance. */ |
bobboteck | 0:8ac34d529a3b | 10 | SRF02::~SRF02() |
bobboteck | 0:8ac34d529a3b | 11 | { |
bobboteck | 0:8ac34d529a3b | 12 | |
bobboteck | 0:8ac34d529a3b | 13 | } |
bobboteck | 0:8ac34d529a3b | 14 | |
bobboteck | 0:8ac34d529a3b | 15 | /* Start and return the range measure. */ |
bobboteck | 0:8ac34d529a3b | 16 | float SRF02::read() |
bobboteck | 0:8ac34d529a3b | 17 | { |
bobboteck | 0:8ac34d529a3b | 18 | char command[2]; |
bobboteck | 0:8ac34d529a3b | 19 | char result[2]; |
bobboteck | 0:8ac34d529a3b | 20 | |
bobboteck | 0:8ac34d529a3b | 21 | command[0] = 0x00; // Set the command register |
bobboteck | 0:8ac34d529a3b | 22 | command[1] = _typem; // Ranging results in type indicated in a costructor |
bobboteck | 0:8ac34d529a3b | 23 | _i2c.write(_addr, command, 2); // Send the command to start a ranging burst |
bobboteck | 0:8ac34d529a3b | 24 | |
bobboteck | 0:8ac34d529a3b | 25 | wait_ms(70); // Wait 70mS for complete the measure |
bobboteck | 0:8ac34d529a3b | 26 | |
bobboteck | 0:8ac34d529a3b | 27 | command[0] = 0x02; // The start address of measure result |
bobboteck | 0:8ac34d529a3b | 28 | _i2c.write(_addr, command, 1, 1); // Send address to read a measure |
bobboteck | 0:8ac34d529a3b | 29 | _i2c.read(_addr, result, 2); // Read two byte of measure |
bobboteck | 0:8ac34d529a3b | 30 | |
bobboteck | 0:8ac34d529a3b | 31 | float range = (result[0]<<8)+result[1]; // Convert the two byte in a float value |
bobboteck | 0:8ac34d529a3b | 32 | |
bobboteck | 0:8ac34d529a3b | 33 | return range; |
bobboteck | 0:8ac34d529a3b | 34 | } |