2.2 硬件支持
MT6825编码器电路
驱动板电路
2.3 Cubemax配置及使用
2.4 项目代码实现
SPI外设初始化:
/* SPI1 init function */
void MX_SPI1_Init(void)
{
/* USER CODE BEGIN SPI1_Init 0 */
/* USER CODE END SPI1_Init 0 */
/* USER CODE BEGIN SPI1_Init 1 */
/* USER CODE END SPI1_Init 1 */
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_16BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH;
hspi1.Init.CLKPhase = SPI_PHASE_2EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; //8 10.5Mbit/s 64 1.3125Mbits 16 5.25Mbit/s
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI1_Init 2 */
/* USER CODE END SPI1_Init 2 */
}
结构体及初始化:
typedef struct{
uint16_t cmd[3];
uint16_t rec_data[3];
uint8_t no_mag_warning_flag;
uint8_t over_speed_flag;
uint8_t pc1_flag;
uint8_t pc2_flag;
uint8_t pc1_count;
uint8_t pc2_count;
uint8_t err;
uint32_t sample_data;
uint32_t angle_data;
uint32_t pre_angle_data;
}mag_enc_t;
extern mag_enc_t mag_enc;
/**********************************************************/
mag_enc_t mag_enc = {
.cmd = {0x8300, 0x8400, 0x8500},
.rec_data = {0, 0, 0},
.no_mag_warning_flag = 0,
.over_speed_flag = 0,
.pc1_flag = 0,
.pc2_flag = 0,
.pc1_count = 0,
.pc2_count = 0,
.err = 0,
.sample_data = 0,
.angle_data =0,
.pre_angle_data =0
};
SPI读取绝对值位置:
uint32_t SPI1_MT6825_fast_ReadData(void)
{
short timeOut=1000;
SPI1_CS_LOW;
// HAL_SPI_Transmit(&hspi1 ,(unsigned char *)&mag_enc.cmd[0] ,1,200);
// HAL_SPI_Receive(&hspi1 ,(unsigned char *)&mag_enc.rec_data[0] ,3,200);
HAL_SPI_TransmitReceive(&hspi1 ,(unsigned char *)&mag_enc.cmd[0] ,(unsigned char *)&mag_enc.rec_data[0] ,3,200 );
while( hspi1.State == HAL_SPI_STATE_BUSY )
{
if (timeOut-- ==0) return 0;
} // wait for transmission complete
SPI1_CS_HIGH;
mag_enc.angle_data=((mag_enc.rec_data[0]&0x00FF)<<10)+((mag_enc.rec_data[1]&0xFC00)>>6)+((mag_enc.rec_data[1]&0x00F0)>>4);
return mag_enc.angle_data;
}