8#include "STM32SPIDevice.hpp"
12 : _hspi(hspi), _csPort(csPort), _csPin(csPin), _timeoutMs(timeoutMs) {
16 HAL_GPIO_WritePin(_csPort, _csPin, GPIO_PIN_SET);
20 HAL_GPIO_WritePin(_csPort, _csPin, GPIO_PIN_RESET);
24 HAL_GPIO_WritePin(_csPort, _csPin, GPIO_PIN_SET);
28 uint8_t received = 0xFF;
29 HAL_SPI_TransmitReceive(_hspi, &send, &received, 1, _timeoutMs);
38 HAL_SPI_TransmitReceive(_hspi, buffer, buffer, len, _timeoutMs);
42 memset(buffer, sendValue, len);
45 HAL_StatusTypeDef status = HAL_SPI_TransmitReceive(_hspi, buffer, buffer, len, _timeoutMs);
48 return status == HAL_OK;
54 HAL_StatusTypeDef status = HAL_OK;
56 status = HAL_SPI_Transmit(_hspi,
const_cast<uint8_t *
>(prefixBuffer), prefixLen, _timeoutMs);
58 if (status == HAL_OK && len > 0) {
59 status = HAL_SPI_Transmit(_hspi,
const_cast<uint8_t *
>(buffer), len, _timeoutMs);
63 return status == HAL_OK;
67 if (writeLen + readLen > kMaxCombinedBytes) {
71 uint8_t txBuffer[kMaxCombinedBytes];
72 uint8_t rxBuffer[kMaxCombinedBytes];
74 memcpy(txBuffer, writeBuffer, writeLen);
75 memset(txBuffer + writeLen, sendValue, readLen);
78 HAL_StatusTypeDef status = HAL_SPI_TransmitReceive(_hspi, txBuffer, rxBuffer, writeLen + readLen, _timeoutMs);
81 if (status != HAL_OK) {
85 memcpy(readBuffer, rxBuffer + writeLen, readLen);
bool write(const uint8_t *buffer, size_t len, const uint8_t *prefixBuffer=nullptr, size_t prefixLen=0)
Writes len bytes from buffer, optionally preceded by a separate prefix buffer (e.g....
void begin()
Deasserts chip-select (idle-high) so the bus starts in a known state. Call once before the first tran...
bool read(uint8_t *buffer, size_t len, uint8_t sendValue=0xFF)
Reads len bytes into buffer, clocking out sendValue for each byte read. Brackets the transfer with ch...
void endTransaction()
Deasserts chip-select (drives it high).
bool writeThenRead(const uint8_t *writeBuffer, size_t writeLen, uint8_t *readBuffer, size_t readLen, uint8_t sendValue=0xFF)
Writes writeLen bytes, then reads readLen bytes, all within a single chip-select assert/deassert brac...
void beginTransaction()
Asserts chip-select (drives it low). No SPI settings to apply.
STM32SPIDevice(SPI_HandleTypeDef *hspi, GPIO_TypeDef *csPort, uint16_t csPin, uint32_t timeoutMs=100)
Constructs the device wrapper. Does not touch hardware – HAL_GPIO_Init()/HAL_SPI_Init() for the under...
uint8_t transfer(uint8_t send)
Transfers (sends and receives simultaneously) one byte, without chip-select management – the caller m...