STM32:简单SPI传输



我正在使用STM32F3ISCOVERY板,我正试图更深入地研究HAL的抽象。我制作了一个简单版本的函数,通过SPI传输数据,但遗憾的是,它不起作用(至少我发送它的DAC不会改变状态(,我不确定我在那里缺少了什么。也许初始化代码中也有一些东西不适用于我的简单版本。我很乐意为您提供任何指导或参考资料。非常感谢。

#include <stm32f3xx_hal.h>
#define PINS_SPI GPIO_PIN_5 | GPIO_PIN_7
#define GPIO_PORT GPIOA
/* This is the simplest function I could come up with to do the transfer but I'm clearly missing something here */
uint8_t SPI_SendReceive(SPI_HandleTypeDef *hspi, uint8_t data) {
/* Loop while DR register in not empty */
while ((hspi->Instance->SR & SPI_FLAG_TXE) == RESET) {
}
/* Send data through the SPI1 peripheral */
hspi->Instance->DR = data;
/* Wait to receive data */
while ((hspi->Instance->SR & SPI_FLAG_RXNE) == RESET) {
}
return hspi->Instance->DR;
}
int main() {
HAL_Init();

__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_SPI1_CLK_ENABLE();
static SPI_HandleTypeDef spi = {.Instance = SPI1};
spi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256;
spi.Init.Direction = SPI_DIRECTION_2LINES;
spi.Init.CLKPhase = SPI_PHASE_1EDGE;
spi.Init.CLKPolarity = SPI_POLARITY_LOW;
spi.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
spi.Init.DataSize = SPI_DATASIZE_8BIT;
spi.Init.FirstBit = SPI_FIRSTBIT_MSB;
spi.Init.NSS = SPI_NSS_HARD_OUTPUT;
spi.Init.TIMode = SPI_TIMODE_DISABLE;
spi.Init.Mode = SPI_MODE_MASTER;
HAL_SPI_Init(&spi);
__HAL_SPI_ENABLE(&spi);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = PINS_SPI;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI1;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

/* TI 8564 DAC Settings */
uint8_t cmd1 = 0b00010000;
/* DAC output value (16-bit) */
uint16_t cmd23 = 0;
uint8_t cmd2 = cmd23 >> 8;
uint8_t cmd3 = cmd23 & 0xff;
uint8_t command[3] = {cmd1, cmd2, cmd3};
while (true) {
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
/* This does not work :( */
SPI_SendReceive(&spi, command[0]);
SPI_SendReceive(&spi, command[1]);
SPI_SendReceive(&spi, command[2]);

/* This works! When commenting in the lines above and commenting this out */
/* HAL_SPI_Transmit(&spi, command, 3, HAL_MAX_DELAY); */
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
HAL_Delay(1000);
}
}

检查HAL_SPI_Init的内容。这个函数很可能会调用另一个函数,该函数应该进行低级初始化,并且您自己负责提供这个函数。为了使其更加复杂,这个所谓的第二函数已经具有";伪";定义了弱别名,所以工具链不会返回任何错误,只是构建了一个无法执行任何操作的代码。

最新更新