电路设计如下,注意一定要将13脚接地才能使能SPI通讯方式。我之后进行通讯测试发现怎么都读不到想要的值,后面发现,跳线帽P1都没接,当场就要吐血。
根据数据手册的要求对spi参数进行配置,注意CPHA在数据手册中显示要配置为1,但STM32Cube_Mx要配置为2 Edge,表示偶数边沿采样,小心不要掉进坑里,跟我一样也傻傻地配置个1 Edge。
另外PCAP04的最大允许时钟频率是由电源电压决定的,这里我的MCU主频是480MHz,32分频后得到15M<17M。
void MX_SPI1_Init(void)
{
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_2EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 0x0;
hspi1.Init.NSSPMode = SPI_NSS_PULSE_ENABLE;
hspi1.Init.NSSPolarity = SPI_NSS_POLARITY_LOW;
hspi1.Init.FifoThreshold = SPI_FIFO_THRESHOLD_01DATA;
hspi1.Init.TxCRCInitializationPattern = SPI_CRC_INITIALIZATION_ALL_ZERO_PATTERN;
hspi1.Init.RxCRCInitializationPattern = SPI_CRC_INITIALIZATION_ALL_ZERO_PATTERN;
hspi1.Init.MasterSSIdleness = SPI_MASTER_SS_IDLENESS_00CYCLE;
hspi1.Init.MasterInterDataIdleness = SPI_MASTER_INTERDATA_IDLENESS_00CYCLE;
hspi1.Init.MasterReceiverAutoSusp = SPI_MASTER_RX_AUTOSUSP_DISABLE;
hspi1.Init.MasterKeepIOState = SPI_MASTER_KEEP_IO_STATE_DISABLE;
hspi1.Init.IOSwap = SPI_IO_SWAP_DISABLE;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
}
在前面的准备工作都完成后,就可以开始通讯测试了。
根据数据手册,写入0x7e,紧接着再读取一个数据,若读取的值为0x11,则表示通讯测试成功。为此编写如下所示代码:
void pcap04_text(void)
{
uint8_t text_data=0x7e;
uint8_t text_receive=0x11;//不一定要写入0x11,任何值都可以
printf("text_receive=0x%hX\n",text_receive);
HAL_GPIO_WritePin(SPI1_NSS_GPIO_Port, SPI1_NSS_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(&hspi1,&text_data,1,1000);
HAL_GPIO_WritePin(SPI1_NSS_GPIO_Port, SPI1_NSS_Pin, GPIO_PIN_SET);
HAL_GPIO_WritePin(SPI1_NSS_GPIO_Port, SPI1_NSS_Pin, GPIO_PIN_RESET);
HAL_SPI_TransmitReceive(&hspi1,&text_receive,&text_receive,1,1000);
HAL_GPIO_WritePin(SPI1_NSS_GPIO_Port, SPI1_NSS_Pin, GPIO_PIN_SET);
printf("text_receive=0x%hX\n",text_receive);
}
但死活都读不到正确的返回值,试了各种方法发现将代码注释掉两行就可以了:
void pcap04_text(void)
{
uint8_t text_data=0x7e;
uint8_t text_receive=0x00;
printf("text_receive=0x%hX\n",text_receive);
HAL_GPIO_WritePin(SPI1_NSS_GPIO_Port, SPI1_NSS_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(&hspi1,&text_data,1,1000);
// HAL_GPIO_WritePin(SPI1_NSS_GPIO_Port, SPI1_NSS_Pin, GPIO_PIN_SET);
//
// HAL_GPIO_WritePin(SPI1_NSS_GPIO_Port, SPI1_NSS_Pin, GPIO_PIN_RESET);
HAL_SPI_TransmitReceive(&hspi1,&text_receive,&text_receive,1,1000);
HAL_GPIO_WritePin(SPI1_NSS_GPIO_Port, SPI1_NSS_Pin, GPIO_PIN_SET);
printf("text_receive=0x%hX\n",text_receive);
}