使用L432的SPI3接AD7792,AD7792的/CS接地。
工程使用CUBE生成
SPI配置如下
static void MX_SPI3_Init(void)
{
hspi3.Instance = SPI3;
hspi3.Init.Mode = SPI_MODE_MASTER;
hspi3.Init.Direction = SPI_DIRECTION_2LINES;
hspi3.Init.DataSize = SPI_DATASIZE_8BIT;
hspi3.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi3.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi3.Init.NSS = SPI_NSS_SOFT;
hspi3.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256;
hspi3.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi3.Init.TIMode = SPI_TIMODE_DISABLE;
hspi3.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi3.Init.CRCPolynomial = 7;
hspi3.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
hspi3.Init.NSSPMode = SPI_NSS_PULSE_ENABLE;
if (HAL_SPI_Init(&hspi3) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
}
void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{
GPIO_InitTypeDef GPIO_InitStruct;
if(hspi->Instance==SPI3)
{
/* USER CODE BEGIN SPI3_MspInit 0 */
/* USER CODE END SPI3_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_SPI3_CLK_ENABLE();
/**SPI3 GPIO Configuration
PB3 (JTDO-TRACESWO) ------> SPI3_SCK
PB4 (NJTRST) ------> SPI3_MISO
PB5 ------> SPI3_MOSI
*/
GPIO_InitStruct.Pin = GPIO_PIN_3|GPIO_PIN_4|GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF6_SPI3;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* USER CODE BEGIN SPI3_MspInit 1 */
/* USER CODE END SPI3_MspInit 1 */
}
}
自己写的:
读写:
void USER_SPI3_Write(uint8_t Tx_Len)
{
// HAL_SPI_Transmit_IT(&hspi3, gSPI3WriteBuff, Tx_Len);
HAL_SPI_Transmit(&hspi3, gSPI3WriteBuff, Tx_Len,1000);
}
void USER_SPI3_Read(uint8_t Rx_Len)
{
uint8_t i = 0;
uint8_t m_SPI3ReadWriteBuff[Rx_Len];
for(i = 0; i < Rx_Len;i++)
{
m_SPI3ReadWriteBuff = 0x00;
}
HAL_SPI_TransmitReceive(&hspi3, m_SPI3ReadWriteBuff, gSPI3ReadBuff, Rx_Len,1000);
}
初始化
void USER_InitAD7792(void)
{
gSPI3WriteBuff[0] = 0xFF;
gSPI3WriteBuff[1] = 0xFF;
gSPI3WriteBuff[2] = 0xFF;
gSPI3WriteBuff[3] = 0xFF;
USER_SPI3_Write(4);
USER_SPI3_Write(4);
while(1)
{
gSPI3WriteBuff[0] = 0x40;
gSPI3ReadBuff[0] = 0;
gSPI3ReadBuff[1] = 0;
USER_SPI3_Write(1);
USER_SPI3_Read(1);
if(gSPI3ReadBuff[0] == 0x80)
break;
}
}
uint8_t USER_ReadDataFromAD7792(void)
{
uint8_t i = 0;
for(i = 0; i < 8; i++)
gADData = 0;
/*****************************************/
gSPI3WriteBuff[0] = 0x28;
gSPI3WriteBuff[1] = 0x01;
USER_SPI3_Write(2);
gSPI3WriteBuff[0] = 0x10;
gSPI3WriteBuff[1] = 0x10;
gSPI3WriteBuff[2] = 0x86;//这里应该是AD7792片上的温度传感器
USER_SPI3_Write(3);
gSPI3WriteBuff[0] = 0x08;
gSPI3WriteBuff[1] = 0x20;
gSPI3WriteBuff[2] = 0x01;
USER_SPI3_Write(3);
while(1)
{
gSPI3WriteBuff[0] = 0x40;
gSPI3ReadBuff[0] = 0;
gSPI3ReadBuff[1] = 0;
USER_SPI3_Write(1);
USER_SPI3_Read(1);
if(gSPI3ReadBuff[0] == 0x06)
break;
}
HAL_Delay(20);
gSPI3WriteBuff[0] = 0x58;
gSPI3ReadBuff[0] = 0;
gSPI3ReadBuff[1] = 0;
USER_SPI3_Write(1);
USER_SPI3_Read(2); //这里始终是0
gADData[0] = gSPI3ReadBuff[0];
gADData[1] = gSPI3ReadBuff[1];
}
|