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

BNO080Async.h

Committer:
Jamie Smith
Date:
2020-11-24
Revision:
9:430f5302f9e1

File content as of revision 9:430f5302f9e1:

#ifndef BNO080_BNO080ASYNC_H
#define BNO080_BNO080ASYNC_H

#if MBED_CONF_RTOS_PRESENT

#include <BNO080.h>
#include <Mutex.h>

/**
 * Asynchronous version of the SPI BNO080 driver.
 * Since the timing requirements of this driver are so different,
 * wouldn't it be great to have a dedicated thread to handle them?
 * This class provides exactly that, using an internal thread triggered
 * by interrupts to connect to the BNO.
 *
 * Note: the internal thread is started the first time begin() is called,
 * and is shut down when the class is destroyed.
 */
class BNO080Async : public BNO080SPI
{
public:
	// Mutex protecting all sensor data in the driver.
	// You must lock this while reading data and unlock it when done.
	// While this is locked, the background thread is prevented from running.
	Mutex bnoDataMutex;

private:
	// thread in charge of communicating with the BNO
	Thread commThread;

	// EventFlags to allow signalling the thread to wake up
	EventFlags wakeupFlags;

	// main function for the thread.
	// Handles starting the comm loop.
	void threadMain();

	// Code loop to communicate with the BNO.
	// Runs forever in normal operation.
	// Returns true to request a restart.
	// Returns false to request the thread to shutdown.
	bool commLoop();

	// flag to indicate that we have valid data to send queued in the TX buffer.
	// Protected by bnoDataMutex.
	bool dataToSend = false;

	// data for packet to send, if above flag is true
	uint8_t txPacketChannelNumber;
	uint8_t txPacketDataLength;

	// Condition variable signaled whenever a packet is sent.
	ConditionVariable dataSentCV;

	// flag used for updateData() return value.
	// True if any data packets have been received since the last update.
	bool dataReceived = false;

	// true iff the thread is currently in the middle of a TX/RX operation.
	// Causes _int interrupts (which get generated by the comms process) to be ignored.
	bool inTXRX = false;

	bool sendPacket(uint8_t channelNumber, uint8_t dataLength) override;

	void clearSendBuffer() override;

	// waiting for packet state info
	bool waitingForPacket = false;
	uint8_t waitingForChannel;
	uint8_t waitingForReportID;
	bool waitingPacketArrived = false;
	bool clearToRxNextPacket = false;

	ConditionVariable waitingPacketArrivedCV;
	ConditionVariable waitingPacketProcessedCV;

	bool waitForPacket(int channel, uint8_t reportID, std::chrono::milliseconds timeout = 125ms) override;

public:
	/**
	 * Construct a BNO080Async.
	 * This doesn't actually initialize the chip, you will need to call begin() for that.
	 *
	 * NOTE: while some schematics tell you to connect the BOOTN pin to the processor, this driver does not use or require it.
	 * Just tie it to VCC per the datasheet.
	 *
	 * @param debugPort Serial port to write output to.  Cannot be nullptr.
	 * @param rstPin Hardware reset pin, resets the IMU
	 * @param intPin Hardware interrupt pin, this is used for the IMU to signal the host that it has a message to send
	 * @param wakePin Hardware wake pin, this is used by the processor to signal the BNO to wake up and receive a message
	 * @param misoPin SPI MISO pin
	 * @param mosiPin SPI MOSI pin
	 * @param sclkPin SPI SCLK pin
	 * @param csPin SPI CS pin
	 * @param spiSpeed SPI frequency.  The BNO's max is 3MHz.
	 * @param threadPriority Priority to give the internal thread.  Defaults to AboveNormal so it will run whenever it can.
	 */
	BNO080Async(Stream *debugPort, PinName rstPin, PinName intPin, PinName wakePin, PinName misoPin, PinName mosiPin, PinName sclkPin, PinName csPin, int spiSpeed=3000000, osPriority threadPriority=osPriorityAboveNormal);

	/**
	 * Resets and connects to the IMU.  Verifies that it's connected, and reads out its version
	 * info into the class variables above.
	 *
	 * Async version also starts the internal communication thread, restarting it if it's
	 * already started.
	 *
	 * If this function is failing, it would be a good idea to turn on BNO_DEBUG in the cpp file to get detailed output.
	 *
	 * @return whether or not initialization was successful
	 */
	bool begin() override;

	/**
	 * In BNO080Async, there is no need to call updateData() in order to get new
	 * results, but this call is provided for compatibility.
	 *
	 * It maintains its behavior of returning true iff packets have been received since the last call.
	 * You must lock bnoDataMutex to call this.
	 * @return
	 */
	bool updateData() override;

	/**
	 * Locks the data mutex.
	 */
	void lockMutex() override
	{
		bnoDataMutex.lock();
	}

	/**
	 * Unlocks the data mutex.
	 */
	void unlockMutex() override
	{
		bnoDataMutex.unlock();
	}
};

#endif


#endif //MBED_CMAKE_TEST_PROJECT_BNO080ASYNC_H