Tool Libs
UMIT-TIROL Institute of Automation and Control Engineering library collection
 
Loading...
Searching...
No Matches
pwm.h
Go to the documentation of this file.
1
5#pragma once
6
7#include "hal.h"
8#include "gpio.h"
9#include "timer.h"
10
11namespace TIMER {
15 class PWM {
16 public:
21 void pwm(double perc) {
22 _perc = perc;
23 _ticks = perc * _period;
24 __HAL_TIM_SET_COMPARE(&hTim, chan, _ticks);
25 }
26
31 void ticks(uint32_t ticks) {
32 _perc = ticks / _period;
33 _ticks = ticks;
34 __HAL_TIM_SET_COMPARE(&hTim, chan, _ticks);
35 }
36
43 void period(uint16_t period) {
44 if (period == _period) return;
45 bool needupdate = _period == 0;
46 _period = period;
47 hTim.Instance->CR1 |= TIM_CR1_UDIS;
48 hTim.Instance->ARR = _period;
49 pwm(_perc);
50 hTim.Instance->CR1 &= ~TIM_CR1_UDIS;
51 if (needupdate || hTim.Instance->CNT >= _period)
52 hTim.Instance->EGR |= TIM_EGR_UG;
53 }
54
55 uint16_t period() {
56 return _period;
57 }
58
60 struct Config {
62 uint32_t chan;
64 };
65
69 PWM(const Config &conf)
70 : hTim(conf.tim->handle), chan(conf.chan), _period(hTim.Init.Period) {
71 // pwm config of timer
72 while (HAL_TIM_PWM_Init(&hTim) != HAL_OK);
73
74 // channel config
75 TIM_OC_InitTypeDef sConfigOC = {};
76 sConfigOC.OCMode = TIM_OCMODE_PWM1;
77 sConfigOC.Pulse = 0;
78 sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
79 sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
80 while (HAL_TIM_PWM_ConfigChannel(&hTim, &sConfigOC, chan) != HAL_OK);
81
82 __HAL_TIM_SET_COMPARE(&hTim, chan, 0);
83 while (HAL_TIM_PWM_Start(&hTim, chan) != HAL_OK);
84 }
85
87 double pwm(){
88 return _perc;
89 }
90 double getpwm(){
91 return pwm();
92 }
94 uint32_t ticks(){
95 return _ticks;
96 }
97 uint32_t getticks(){
98 return ticks();
99 }
100
101 private:
102 TIM_HandleTypeDef &hTim;
103 uint32_t chan = 0;
104 uint32_t &_period;
105 double _perc = 0.0;
106 uint32_t _ticks = 0;
107 };
108}
Wrapper class for pins in alternate configuration mode.
Definition gpio.h:60
wrapper for timer peripheral
Definition timer.h:11
Template class for hardware based PWM outputs.
Definition pwm.h:15
double pwm()
get currently set pwm value in percent
Definition pwm.h:87
TIMER::HW * tim
TIMER::HW peripheral.
Definition pwm.h:61
AFIO pin
pin in alternate function mode
Definition pwm.h:63
uint32_t chan
Timer channel.
Definition pwm.h:62
void pwm(double perc)
set pwm in percent
Definition pwm.h:21
uint32_t ticks()
get currently set pwm value in timer ticks
Definition pwm.h:94
PWM(const Config &conf)
Initialize Timer Channel.
Definition pwm.h:69
void period(uint16_t period)
change frequency by setting period of timer freq = base / period counter is blocked while period = 0
Definition pwm.h:43
void ticks(uint32_t ticks)
set pwm as value of timer ticks
Definition pwm.h:31
PWM configuration.
Definition pwm.h:60
Copyright (c) 2020 IACE.
Copyright (c) 2020 IACE.
Copyright (c) 2023 IACE.