Fully featured I2C and SPI driver for CEVA (Hilcrest)'s BNO080 and FSM300 Inertial Measurement Units.
Dependents: BNO080-Examples BNO080-Examples
BNO080 Driver
by Jamie Smith / USC Rocket Propulsion Lab
After lots of development, we are proud to present our driver for the Hilcrest BNO080 IMU! This driver is inspired by SparkFun and Nathan Seidle's Arduino driver for this chip, but has been substantially rewritten and adapted.
It supports the main features of the chip, such as reading rotation and acceleration data, as well as some of its more esoteric functionality, such as counting steps and detecting whether the device is being hand-held.
Features
- Support for 15 different data reports from the IMU, from acceleration to rotation to tap detection
- Support for reading of sensor data, and automatic checking of update rate against allowed values in metadata
BNO_DEBUG
switch enabling verbose, detailed output about communications with the chip for ease of debugging- Ability to tare sensor rotation and set mounting orientation
- Can operate in several execution modes: polling I2C, polling SPI, and threaded SPI (which handles timing-critical functions in a dedicated thread, and automatically activates when the IMU has data available)
- Also has experimental support for using asynchronous SPI transactions, allowing other threads to execute while communication with the BNO is occurring. Note that this functionality requires a patch to Mbed OS source code due to Mbed bug #13941
- Calibration function
- Reasonable code size for what you get: the library uses about 4K of flash and one instance of the object uses about 1700 bytes of RAM.
Documentation
Full Doxygen documentation is available online here
Example Code
Here's a simple example:
BNO080 Rotation Vector and Acceleration
#include <mbed.h> #include <BNO080.h> int main() { Serial pc(USBTX, USBRX); // Create IMU, passing in output stream, pins, I2C address, and I2C frequency // These pin assignments are specific to my dev setup -- you'll need to change them BNO080I2C imu(&pc, p28, p27, p16, p30, 0x4a, 100000); pc.baud(115200); pc.printf("============================================================\n"); // Tell the IMU to report rotation every 100ms and acceleration every 200ms imu.enableReport(BNO080::ROTATION, 100); imu.enableReport(BNO080::TOTAL_ACCELERATION, 200); while (true) { wait(.001f); // poll the IMU for new data -- this returns true if any packets were received if(imu.updateData()) { // now check for the specific type of data that was received (can be multiple at once) if (imu.hasNewData(BNO080::ROTATION)) { // convert quaternion to Euler degrees and print pc.printf("IMU Rotation Euler: "); TVector3 eulerRadians = imu.rotationVector.euler(); TVector3 eulerDegrees = eulerRadians * (180.0 / M_PI); eulerDegrees.print(pc, true); pc.printf("\n"); } if (imu.hasNewData(BNO080::TOTAL_ACCELERATION)) { // print the acceleration vector using its builtin print() method pc.printf("IMU Total Acceleration: "); imu.totalAcceleration.print(pc, true); pc.printf("\n"); } } } }
If you want more, a comprehensive, ready-to-run set of examples is available on my BNO080-Examples repository.
Credits
This driver makes use of a lightweight, public-domain library for vectors and quaternions available here.
Changelog
Version 2.1 (Nov 24 2020)
- Added BNO080Async, which provides a threaded implementation of the SPI driver. This should help get the best performance and remove annoying timing requirements on the code calling the driver
- Added experimental
USE_ASYNC_SPI
option - Fixed bug in v2.0 causing calibrations to fail
Version 2.0 (Nov 18 2020)
- Added SPI support
- Refactored buffer system so that SPI could be implemented as a subclass. Unfortunately this does substantially increase the memory usage of the driver, but I believe that the benefits are worth it.
Version 1.3 (Jul 21 2020)
- Fix deprecation warnings and compile errors in Mbed 6
- Fix compile errors in Arm Compiler (why doesn't it have M_PI????)
Version 1.2 (Jan 30 2020)
- Removed accidental IRQ change
- Fixed hard iron offset reading incorrectly due to missing cast
Version 1.1 (Jun 14 2019)
- Added support for changing permanent orientation
- Add FRS writing functions
- Removed some errant printfs
Version 1.0 (Dec 29 2018)
- Initial Mbed OS release
Diff: BNO080.h
- Revision:
- 9:430f5302f9e1
- Parent:
- 8:199c7fad233d
diff -r 199c7fad233d -r 430f5302f9e1 BNO080.h --- a/BNO080.h Wed Nov 18 18:07:27 2020 -0800 +++ b/BNO080.h Tue Nov 24 15:06:05 2020 -0800 @@ -30,6 +30,17 @@ // useful define when working with orientation quaternions #define SQRT_2 1.414213562f +// Enable this to enable experimental support for Mbed's asynchronous SPI transfer API. +// This will allow your processor to do other things while long SPI transfers are taking place +// (and this IMU can end up transferring hundreds of bytes per packet, so this is useful). +// To get this to work, you may need to use a slower clock rate (<1MHz on the STM32F429ZI I tested). +// You also will need to edit Mbed OS code in order to use 0x00 as the SPI fill character for +// asynchronous transfers (the API currently only allows changing this for synchronous transfers) +// (I had to edit the SPI_FILL_CHAR constant in stm_spi_api.c). +#define USE_ASYNC_SPI 0 + +// Note: I filed a bug about the SPI fill char issue: https://github.com/ARMmbed/mbed-os/issues/13941 + /** Class to drive the BNO080 9-axis IMU. @@ -44,7 +55,9 @@ Stream * _debugPort; /// Interrupt pin -- signals to the host that the IMU has data to send - DigitalIn _int; + // Note: only ever used as a digital input by BNO080. + // Used for interrupts by BNO080Async. + InterruptIn _int; // Reset pin -- resets IMU when held low. DigitalOut _rst; @@ -393,9 +406,11 @@ * * If this function is failing, it would be a good idea to turn on BNO_DEBUG in the cpp file to get detailed output. * + * Note: this function takes several hundred ms to execute, mainly due to waiting for the BNO to boot. + * * @return whether or not initialization was successful */ - bool begin(); + virtual bool begin(); /** * Tells the IMU to use its current rotation vector as the "zero" rotation vector and to reorient @@ -466,6 +481,18 @@ * @return true if the operation succeeded, false if it failed. */ bool setPermanentOrientation(Quaternion orientation); + + /** + * No-op on synchronous driver. For compatibility with BNO080Async + */ + virtual void lockMutex() + {} + + /** + * No-op on synchronous driver. For compatibility with BNO080Async + */ + virtual void unlockMutex() + {} // Report functions //----------------------------------------------------------------------------------------------------------------- @@ -482,7 +509,7 @@ * @return True iff new data packets of any kind were received. If you need more fine-grained data change reporting, * check out hasNewData(). */ - bool updateData(); + virtual bool updateData(); /** * Gets the status of a report as a 2 bit number. @@ -623,12 +650,16 @@ /** * Call to wait for a packet with the given parameters to come in. * + * Note: on BNO080Async, the received packet data will stay in the RX buffer + * until either the public IMU function that was called returns, or you + * call sendPacket() or waitForPacket() again. + * * @param channel Channel of the packet * @param reportID Report ID (first data byte) of the packet * @param timeout how long to wait for the packet * @return true if the packet has been received, false if it timed out */ - bool waitForPacket(int channel, uint8_t reportID, std::chrono::milliseconds timeout = 125ms); + virtual bool waitForPacket(int channel, uint8_t reportID, std::chrono::milliseconds timeout = 125ms); /** * Given a Q value, converts fixed point floating to regular floating point number. @@ -737,9 +768,10 @@ void printPacket(uint8_t * buffer); /** - * Erases the current SHTP TX packet buffer + * Erases the current SHTP TX packet buffer. + * In BNO080Async, this blocks until the buffer is available. */ - void zeroBuffer(); + virtual void clearSendBuffer(); /** * Loads the metadata for this report into the metadata buffer. @@ -750,11 +782,6 @@ }; -// TODO list: -// - Better handling of continued packets (discard as an error) -// - Unified TX/RX SPI comms function - - /** * Version of the BNO080 driver which uses the I2C interface */ @@ -819,6 +846,7 @@ */ class BNO080SPI : public BNO080Base { +protected: /** * I2C port object. Provides physical layer communications with the chip. */ @@ -851,7 +879,7 @@ */ BNO080SPI(Stream *debugPort, PinName rstPin, PinName intPin, PinName wakePin, PinName misoPin, PinName mosiPin, PinName sclkPin, PinName csPin, int spiSpeed=3000000); -private: +protected: bool receivePacket(std::chrono::milliseconds timeout=200ms) override; @@ -863,8 +891,38 @@ * @return */ bool receiveCompletePacket(size_t bytesRead, std::chrono::milliseconds timeout=200ms); + +#if USE_ASYNC_SPI + + /** + * Start an SPI transfer and suspend the current thread until it is complete. + * Used by functions in BNO080SPI. + * Note: should only be called by one thread at a time. + * @param tx_buffer + * @param tx_length + * @param rx_buffer + * @param rx_length + */ + void spiTransferAndWait(const uint8_t *tx_buffer, int tx_length, uint8_t *rx_buffer, int rx_length); + + // callback for finished SPI transfers + void onSPITransferComplete(int event); + + // Signal whan an SPI transfer is complete. + EventFlags spiCompleteFlag; + +#else + + /** + * Start an SPI transfer and wait for it to complete. + * BNO080Async swaps in a threaded implementation here. + * API same as SPI::write(). + */ + void spiTransferAndWait(const uint8_t *tx_buffer, int tx_length, uint8_t *rx_buffer, int rx_length) + { + _spiPort.write(reinterpret_cast<const char *>(tx_buffer), tx_length, reinterpret_cast<char *>(rx_buffer), rx_length); + } +#endif }; - - #endif //HAMSTER_BNO080_H