RogiStandard-hal
STM32 向けサークル共通ライブラリ
読み取り中…
検索中…
一致する文字列を見つけられません
DCMotor.cpp
[詳解]
1#include "DCMotor.hpp"
2
3DCMotor::DCMotor(TIM_HandleTypeDef *htim, uint16_t channel,
4 GPIO_TypeDef *GPIO_Port, uint16_t GPIO_Pin, bool direction,
5 float max_duty) {
6 this->htim = htim;
7 this->channel = channel;
8 this->direction = direction;
9 this->GPIO_Port = GPIO_Port;
10 this->GPIO_Pin = GPIO_Pin;
11 this->max_duty = max_duty < 1.0f ? max_duty : 1.0f;
12 this->pwm_resolution = 0;
13 this->current_duty = 0.0f;
14}
15
17 if (htim == nullptr) {
18 return;
19 }
20 HAL_TIM_PWM_Start(htim, channel);
21 pwm_resolution = htim->Init.Period;
22}
23
24__RAM_FUNC void DCMotor::setDuty(float duty) {
25 if (htim == nullptr || pwm_resolution == 0) {
26 return;
27 }
28
29 // まず上下限を確認
30 if (duty > max_duty) {
31 duty = max_duty;
32 } else if (duty < -max_duty) {
33 duty = -max_duty;
34 }
35
36 current_duty = duty; // オーバーしない値を保存
37
38 // 方向とPWM値を設定
39 const bool dir = (duty >= 0.0f);
40 const float abs_duty = dir ? duty : -duty;
41
42 setDirection(dir);
43
44 // 通常のPWM
45 uint32_t value = static_cast<uint32_t>(pwm_resolution * (abs_duty));
46 __HAL_TIM_SET_COMPARE(htim, channel, value);
47}
48
49void DCMotor::setDirection(bool dir) {
50 if (GPIO_Port == nullptr) {
51 return;
52 }
53 // directionフラグでXORして反転可能に
54 bool pin_state = (dir == this->direction);
55 HAL_GPIO_WritePin(GPIO_Port, GPIO_Pin,
56 pin_state ? GPIO_PIN_SET : GPIO_PIN_RESET);
57}
PWM + DIR ピンでモータードライバを駆動する DC モーターライブラリ
void start()
PWM の出力を開始する
Definition DCMotor.cpp:16
DCMotor(TIM_HandleTypeDef *htim, uint16_t channel, GPIO_TypeDef *GPIO_Port, uint16_t GPIO_Pin, bool direction=1, float max_duty=1.0f)
モーターを設定する (PWM はまだ出力しない)
Definition DCMotor.cpp:3
void setDuty(float duty)
Duty を指令する
Definition DCMotor.cpp:24