105 lines
1.8 KiB
C++
105 lines
1.8 KiB
C++
/*
|
|
* peripherals_spi.cpp
|
|
*
|
|
* Created on: Mar 5, 2021
|
|
* Author: erki
|
|
*/
|
|
|
|
#include "peripherals_spi.hpp"
|
|
|
|
#include "peripherals_utility.hpp"
|
|
|
|
#ifdef PERIPHERALS_USE_DELAY_US
|
|
# define CS_SET() do { cs.SetDelayUs(false, cs_set_delay); } while (0)
|
|
#else
|
|
# define CS_SET() do { cs.Set(false); } while (0)
|
|
#endif
|
|
|
|
#define CS_UNSET() do { cs.Set(true); } while (0)
|
|
|
|
namespace
|
|
{
|
|
|
|
struct _CsGuard
|
|
{
|
|
_CsGuard(Peripherals::Spi& spi)
|
|
: _spi(spi)
|
|
{
|
|
#ifdef PERIPHERALS_USE_DELAY_US
|
|
_spi.cs.SetDelayUs(false, _spi.cs_set_delay);
|
|
#else
|
|
_spi.cs.Set(false);
|
|
#endif
|
|
}
|
|
|
|
~_CsGuard()
|
|
{
|
|
_spi.cs.Set(true);
|
|
}
|
|
private:
|
|
Peripherals::Spi& _spi;
|
|
};
|
|
|
|
}
|
|
|
|
namespace Peripherals
|
|
{
|
|
|
|
Spi::Spi(SPI_HandleTypeDef* hspi, const IO& cs)
|
|
: hspi(hspi)
|
|
, cs(cs)
|
|
{ }
|
|
|
|
void Spi::WriteRegister(std::uint8_t reg, uint8_t data)
|
|
{
|
|
_CsGuard guard(*this);
|
|
|
|
HAL_SPI_Transmit(hspi, ®, 1, timeout);
|
|
HAL_SPI_Transmit(hspi, &data, 1, timeout);
|
|
}
|
|
|
|
void Spi::WriteRegisterMultibyte(std::uint8_t reg, std::uint8_t* data, const std::uint32_t len)
|
|
{
|
|
_CsGuard guard(*this);
|
|
|
|
HAL_SPI_Transmit(hspi, ®, 1, timeout);
|
|
HAL_SPI_Transmit(hspi, data, len, timeout);
|
|
}
|
|
|
|
std::uint8_t Spi::ReadRegister(std::uint8_t reg, const std::uint32_t read_delay)
|
|
{
|
|
_CsGuard guard(*this);
|
|
|
|
HAL_SPI_Transmit(hspi, ®, 1, timeout);
|
|
|
|
#ifdef PERIPHERALS_USE_DELAY_US
|
|
if (read_delay)
|
|
DelayUs(read_delay);
|
|
#else
|
|
(void)read_delay;
|
|
#endif
|
|
|
|
std::uint8_t output = 0;
|
|
HAL_SPI_Receive(hspi, &output, 1, timeout);
|
|
|
|
return output;
|
|
}
|
|
|
|
void Spi::ReadRegisterMultibyte(std::uint8_t reg, std::uint8_t* data, const std::uint32_t len, const std::uint32_t read_delay)
|
|
{
|
|
_CsGuard guard(*this);
|
|
|
|
HAL_SPI_Transmit(hspi, ®, 1, timeout);
|
|
|
|
#ifdef PERIPHERALS_USE_DELAY_US
|
|
if (read_delay)
|
|
DelayUs(read_delay);
|
|
#else
|
|
(void)read_delay;
|
|
#endif
|
|
|
|
HAL_SPI_Receive(hspi, data, len, timeout);
|
|
}
|
|
|
|
}
|