Skip to content
Snippets Groups Projects
Commit 4e00be53 authored by Luca Erbetta's avatar Luca Erbetta :rocket:
Browse files

[SPIDriver] Added assertion to prevent multiple simultaneous transactions

parent 41d2e893
Branches
Tags
No related merge requests found
......@@ -99,7 +99,7 @@ public:
*/
void configure(SPIBusConfig config) override;
private:
protected:
/**
* Writes a single byte on the SPI bus.
*
......@@ -124,7 +124,7 @@ private:
SPI_TypeDef* spi;
SPIBusConfig config;
SPIBusConfig config{};
bool config_enabled = true;
bool first_config_applied = false;
};
......
......@@ -31,6 +31,8 @@
using miosix::delayUs;
using miosix::GpioPin;
class SPITransaction;
/**
* @brief SPI Clock divider.
* SPI clock frequency will be equal to the SPI peripheral bus clock speed (see
......@@ -116,6 +118,7 @@ struct SPIBusConfig
*/
class SPIBusInterface
{
friend class SPITransaction;
public:
SPIBusInterface() {}
......@@ -198,6 +201,9 @@ public:
* @return
*/
virtual void configure(SPIBusConfig config) = 0;
private:
bool locked = false; // For use by SPITransaction
};
/**
......
......@@ -23,17 +23,29 @@
#include "SPITransaction.h"
#include <cassert>
SPITransaction::SPITransaction(SPISlave slave)
: SPITransaction(slave.bus, slave.cs, slave.config)
{
}
SPITransaction::SPITransaction(SPIBusInterface& bus, GpioPin cs,
SPIBusConfig config)
: bus(bus), cs(cs)
{
// Only one SPITransaction may be active at any given time.
// Do not store an instance of SPITransaction for a long time! Create one,
// use it, and destroy it as soon as you are done operating on the bus!
// (just like mutexes)
#ifdef DEBUG
assert(bus.locked == false);
#endif
bus.locked = true;
bus.configure(config);
}
SPITransaction::SPITransaction(SPISlave slave)
: SPITransaction(slave.bus, slave.cs, slave.config)
{
}
SPITransaction::~SPITransaction() { bus.locked = false; }
void SPITransaction::write(uint8_t cmd)
{
......
......@@ -41,14 +41,15 @@
* {
* // Transaction begin:
* SPITransaction spi(bus, cs, config); // Configures the bus with the
* // provided parameters
* // provided parameters.
*
* spi.write(REG_EX, 0x56); // writes data to REG_EX
* uint8_t reg2 = spi.read(REG_EX_2); // reads from REG_EX_2
*
* // ...As many read/writes as you wish...
*
* // transaction end. SPITransaction object is destructed
* // transaction end. SPITransaction object is destructed and the bus is
* // freed for use by someone else
* }
*/
class SPITransaction
......@@ -72,6 +73,8 @@ public:
*/
SPITransaction(SPIBusInterface& bus, GpioPin cs, SPIBusConfig config);
~SPITransaction();
// Delete copy/move contructors/operators
SPITransaction(const SPITransaction&) = delete;
SPITransaction& operator=(const SPITransaction&) = delete;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment