1、STM32CubeMX工程设置
管脚定义
硬件SPI 参数设置
2、软件编写
//TMC5160 takes 40 bit data: 8 address and 32 data void sendData(unsigned long address,long datagram) { unsigned char i; cmd[0]=address; cmd[1]=(datagram >> 24) & 0xff; cmd[2]=(datagram >> 16) & 0xff; cmd[3]=(datagram >> 8) & 0xff; cmd[4]=datagram & 0xff; HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_RESET); //SPI_CS片选拉低 // SPI_SendByte(address); // SPI_SendByte((datagram >> 24) & 0xff); // SPI_SendByte((datagram >> 16) & 0xff); // SPI_SendByte((datagram >> 8) & 0xff); // SPI_SendByte(datagram & 0xff); for(i=0;i<5;i++) { if(HAL_SPI_Transmit(&hspi1,&cmd[i],1,100) == HAL_OK) { } else; } HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_SET); //SPI_CS片选拉高 } unsigned long ReadData(long address) { char data[4] = {0, 0, 0, 0}; unsigned long datagram = 0; HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_RESET); //SPI_CS片选拉低 SPI_SendByte(address); data[0] = SPI_ReceiveByte();//SPI_ReceiveByte((datagram >> 24) & 0xff); data[1] = SPI_ReceiveByte();//SPI_ReceiveByte((datagram >> 16) & 0xff); data[2] = SPI_ReceiveByte();//SPI_ReceiveByte((datagram >> 8) & 0xff); data[3] = SPI_ReceiveByte();//SPI_ReceiveByte(datagram & 0xff); HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_SET); //SPI_CS片选拉高 datagram = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; return datagram; }