UdonLibrary 1.0.0
機械システム研究部 C++ ライブラリ
読み取り中…
検索中…
一致する文字列を見つけられません
Motor.hpp
[詳解]
1//
2// モータードライバ制御クラス
3//
4// Copyright (c) 2022-2024 udonrobo
5//
6
7#pragma once
8
9#ifdef ARDUINO
10
11# include <Arduino.h>
13
14namespace Udon
15{
16
19 template <size_t SmoothLevel>
20 class SmoothlyMotor2
21 {
22 const uint8_t pinA;
23 const uint8_t pinP;
24
26
27 public:
28
32 SmoothlyMotor2(const uint8_t pinA, const uint8_t pinP)
33 : pinA(pinA)
34 , pinP(pinP)
35 , movingAverage{}
36 {
37 }
38
40 void begin()
41 {
42 pinMode(pinA, OUTPUT);
43 }
44
47 void move(const int16_t power)
48 {
49 const int16_t p = movingAverage(constrain(power, -250, 250));
50 digitalWrite(pinA, p >= 0 ? HIGH : LOW);
51 analogWrite(pinP, abs(p));
52 }
53
55 void stop()
56 {
57 move(0);
58 }
59
61 void show() const
62 {
63 Serial.print(movingAverage.getValue());
64 Serial.print('\t');
65 }
66 };
67
70 template <size_t SmoothLevel>
71 class SmoothlyMotor3
72 {
73 const uint8_t pinA;
74 const uint8_t pinB;
75 const uint8_t pinP;
76
78
79 public:
80
85 SmoothlyMotor3(const uint8_t pinA, const uint8_t pinB, const uint8_t pinP)
86 : pinA(pinA)
87 , pinB(pinB)
88 , pinP(pinP)
89 , movingAverage{}
90 {
91 }
92
94 void begin()
95 {
96 pinMode(pinA, OUTPUT);
97 pinMode(pinB, OUTPUT);
98 }
99
102 void move(const int16_t power)
103 {
104 movingAverage.update(constrain(power, -250, 250));
105 const int16_t p = movingAverage.getValue();
106 digitalWrite(pinA, p >= 0 ? HIGH : LOW);
107 digitalWrite(pinB, p <= 0 ? HIGH : LOW);
108 analogWrite(pinP, abs(p));
109 }
110
112 void stop()
113 {
114 move(0);
115 }
116
118 void show() const
119 {
120 Serial.print(movingAverage.getValue());
121 Serial.print('\t');
122 }
123 };
124
125 using Motor2 = SmoothlyMotor2<50>;
126 using Motor3 = SmoothlyMotor3<50>;
127
128#ifdef __AVR_ATmega328P__
129
131 inline void ChangePwmPeriod()
132 {
133 TCCR1B &= B11111000;
134 TCCR1B |= B00000001;
135 TCCR2B &= B11111000;
136 TCCR2B |= B00000001;
137 }
138
139#endif
140
141} // namespace Udon
142
143#endif
移動平均クラス
Definition MovingAverage.hpp:17
double getValue() const noexcept
平均値の取得
Definition MovingAverage.hpp:49
void update(int value) noexcept
値の更新
Definition MovingAverage.hpp:37
Definition Bit.hpp:12