CUBEMX基本配置:
调试方式:SW
系统时钟配置:
CS引脚配置:
SPI参数配置:
串口配置:
生成代码:
然后点右上角生成代码。
代码:
源文件:
#include "mt6816.h"
#include "stdio.h"
MT6816_SPI_Signal_Typedef mt6816_spi;
void REIN_MT6816_SPI_Signal_Init(void)
{
mt6816_spi.sample_data = 0;
mt6816_spi.angle = 0;
}
void RINE_MT6816_SPI_Get_AngleData(void)
{
uint16_t data_t[2];
uint16_t data_r[2];
uint8_t h_count;
data_t[0] = (0x80 | 0x03) << 8;
data_t[1] = (0x80 | 0x04) << 8;
for(uint8_t i=0; i<3; i++){
//读取SPI数据
MT6816_SPI_CS_L();
HAL_SPI_TransmitReceive(&MT6816_SPI_Get_HSPI, (uint8_t*)&data_t[0], (uint8_t*)&data_r[0], 1, HAL_MAX_DELAY);
MT6816_SPI_CS_H();
MT6816_SPI_CS_L();
HAL_SPI_TransmitReceive(&MT6816_SPI_Get_HSPI, (uint8_t*)&data_t[1], (uint8_t*)&data_r[1], 1, HAL_MAX_DELAY);
MT6816_SPI_CS_H();
mt6816_spi.sample_data = ((data_r[0] & 0x00FF) << 8) | (data_r[1] & 0x00FF);
//奇偶校验
h_count = 0;
for(uint8_t j=0; j<16; j++){
if(mt6816_spi.sample_data & (0x0001 << j))
h_count++;
}
if(h_count & 0x01){
mt6816_spi.pc_flag = false;
}
else{
mt6816_spi.pc_flag = true;
break;
}
}
if(mt6816_spi.pc_flag){
mt6816_spi.angle = mt6816_spi.sample_data >> 2;
mt6816_spi.no_mag_flag = (bool)(mt6816_spi.sample_data & (0x0001 << 1));
}
}
MT6816_Typedef mt6816;
float REIN_MT6816_Get_AngleData()
{
RINE_MT6816_SPI_Get_AngleData();
mt6816.angle_data = mt6816_spi.angle;
}
头文件:
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <spi.h>
#include <main.h>
#define MT6816_SPI_CS_H() HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,1)
#define MT6816_SPI_CS_L() HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,0)
#define MT6816_SPI_Get_HSPI (hspi1)
#define MT6816_Mode_SPI (0x03)
typedef struct{
uint16_t sample_data;
uint16_t angle;
bool no_mag_flag;
bool pc_flag;
}MT6816_SPI_Signal_Typedef;
void REIN_MT6816_SPI_Signal_Init(void);
void RINE_MT6816_SPI_Get_AngleData(void);
typedef struct{
uint16_t angle_data;
uint16_t rectify_angle;
bool rectify_valid;
}MT6816_Typedef;
extern MT6816_Typedef mt6816;
float REIN_MT6816_Get_AngleData();
#endif
重定向printf,添加到main.c即可
#include "mt6816.h"
#include "stdio.h"
int fputc(int ch, FILE *File)
{
while((USART1->SR & 0X40) == 0);
USART1->DR = (uint8_t)ch;
return ch;
}
编译记得勾选Use Micro LIB
文章来源:https://www.toymoban.com/news/detail-682846.html
循环中放入以下代码即可:
printf("%.2f\r\n", 360/4096*REIN_MT6816_Get_AngleData());
HAL_Delay(1000);
最后就完成了对MT6816绝对位置的读取。文章来源地址https://www.toymoban.com/news/detail-682846.html
到了这里,关于STM32通过SPI方式读取MT6816磁编码器绝对位置的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!