Tool Libs
UMIT-TIROL Institute of Automation and Control Engineering library collection
 
Loading...
Searching...
No Matches
encoder.h
Go to the documentation of this file.
1
5#pragma once
6
7#include "gpio.h"
8#include "hal.h"
9#include "timer.h"
10
11namespace TIMER {
13 class Encoder {
14 public:
35 struct Conf {
36 TIM_TypeDef *tim;
37 AFIO a, b;
38 double factor = 1;
39 uint8_t filter = 0;
40 };
41
42 Encoder(Conf conf) :
43 tim(TIMER::HW(conf.tim, 0, 0xffff)),
44 dFactor(conf.factor) {
45
46 TIM_HandleTypeDef *htim = &tim.handle;
47 TIM_Encoder_InitTypeDef sConfig = {
48 .EncoderMode = TIM_ENCODERMODE_TI12,
49 .IC1Polarity = TIM_ICPOLARITY_RISING,
50 .IC1Selection = TIM_ICSELECTION_DIRECTTI,
51 .IC1Prescaler = TIM_ICPSC_DIV1,
52 .IC1Filter = conf.filter,
53 .IC2Polarity = TIM_ICPOLARITY_RISING,
54 .IC2Selection = TIM_ICSELECTION_DIRECTTI,
55 .IC2Prescaler = TIM_ICPSC_DIV1,
56 .IC2Filter = conf.filter,
57 };
58 while (HAL_TIM_Encoder_Init(htim, &sConfig) != HAL_OK);
59 while (HAL_TIM_Encoder_Start(htim, TIM_CHANNEL_ALL) != HAL_OK);
60 }
61
67 void measure() {
68 int16_t iCurrEnc = __HAL_TIM_GET_COUNTER(&tim.handle);
69 double dDiff = (int16_t) (iCurrEnc - iLastVal) * dFactor;
70 dPosition += dDiff;
71 iLastVal = iCurrEnc;
72 }
73
78 int16_t getValue() {
79 return iLastVal;
80 }
81
87 double getPosition() {
88 return dPosition;
89 }
90
94 void zero() {
95 __HAL_TIM_SET_COUNTER(&tim.handle, 0);
96 iLastVal = 0;
97 dPosition = 0;
98 }
99
100 private:
101 TIMER::HW tim;
102 double dFactor;
103 int16_t iLastVal = 0;
104
105 double dPosition = 0;
106 };
107}
Wrapper class for pins in alternate configuration mode.
Definition gpio.h:60
Quadrature Encoder support.
Definition encoder.h:13
double getPosition()
return current value of encoder with overflow correction
Definition encoder.h:87
void zero()
reset encoder position
Definition encoder.h:94
void measure()
measure the sensor
Definition encoder.h:67
int16_t getValue()
return the counter value of the timer connected to the encoder
Definition encoder.h:78
Encoder constructor.
Definition encoder.h:35
wrapper for timer peripheral
Definition timer.h:11
TIM_HandleTypeDef handle
HAL handle, for use with unwrapped Timer capabilities.
Definition timer.h:59
Copyright (c) 2020 IACE.
Copyright (c) 2020 IACE.
Copyright (c) 2023 IACE.