Smart Knob Controller
encoder.h
1/*
2 * encoder.h
3 *
4 * Author: nickl
5 *
6 */
7
8#ifndef INC_ENCODER_H_
9#define INC_ENCODER_H_
10
11#include "stm32f4xx_hal.h"
12#include "stdint.h"
13#include "math.h"
14
15#include "gpio.h"
16
20class Encoder {
21public:
28 Encoder(SPI_HandleTypeDef* hspi, TIM_HandleTypeDef* htim, GPIO& CSn);
29
30 uint16_t rawAngle; // angle [int bits]
31
33 void update();
38 int32_t getCommutationAngle();
43 float getAngle();
48 float getPosition();
53 float getVelocity();
57 void zero();
59 void resetPosition();
64 uint16_t readRawAngle();
65
66private:
67 SPI_HandleTypeDef* hspi;
68 TIM_HandleTypeDef* htim;
69 GPIO& CSn;
70
71 static constexpr uint16_t resolution = 16384; // 14-bit encoder
72 static constexpr int32_t commutationZeroAngle = (1722 - (16384/44)); //233 locked rotor angle + 90deg electric (16384/44)
73 uint16_t zeroAngle; // zero reference angle
74 uint16_t resetAngle; // position where accumulation was zeroed to eliminate offset
75
76 uint32_t prevT; // last update time [us]
77 uint16_t prevAngle; // last update angle [int bits]
78 int32_t rawPosition; // rotational position [int bits]
79 int32_t rawVelocity; // velocity [int bits]
80 int32_t dPos;
81 uint32_t dt;
82
84 * @return Timestamp in microseconds from timer.
85 uint32_t micros() const; // us timing helper function
86};
87
88#endif /* INC_ENCODER_H_ */
void zero()
Sets current angle as new zero reference.
Definition encoder.cpp:85
float getAngle()
Returns current angle in radians [0, 2π).
Definition encoder.cpp:65
void resetPosition()
Resets the multi-turn position to zero.
Definition encoder.cpp:94
float getPosition()
Returns accumulated position in radians.
Definition encoder.cpp:74
void update()
Updates angle, position, and velocity.
Definition encoder.cpp:28
Encoder(SPI_HandleTypeDef *hspi, TIM_HandleTypeDef *htim, GPIO &CSn)
Constructs an Encoder object.
Definition encoder.cpp:11
int32_t getCommutationAngle()
Returns angle adjusted for motor commutation.
Definition encoder.cpp:55
uint16_t readRawAngle()
Performs an SPI read to get raw encoder angle.
Definition encoder.cpp:102
float getVelocity()
Returns estimated angular velocity in rad/s.
Definition encoder.cpp:80
Wrapper class for STM32 GPIO pin control.
Definition gpio.h:17