UdonLibrary
1.0.0
機械システム研究部 C++ ライブラリ
Toggle main menu visibility
読み取り中…
検索中…
一致する文字列を見つけられません
Motor.hpp
[詳解]
1
//
2
// モータードライバ制御クラス
3
//
4
// Copyright (c) 2022 udonrobo
5
//
6
7
#pragma once
8
9
#ifdef ARDUINO
10
11
# include <Arduino.h>
12
# include <
Udon/Algorithm/MovingAverage.hpp
>
13
# include <
Udon/Types/Direction.hpp
>
14
15
namespace
Udon
16
{
17
20
template
<
size_t
SmoothLevel>
21
class
SmoothlyMotor2
22
{
23
const
uint8_t pinA;
24
const
uint8_t pinP;
25
26
Udon::Direction
direction;
27
28
Udon::MovingAverage<SmoothLevel> ma;
29
30
public
:
31
35
SmoothlyMotor2(
const
uint8_t pinA,
const
uint8_t pinP,
Udon::Direction
direction =
Udon::Direction::Forward
)
36
: pinA(pinA)
37
, pinP(pinP)
38
, direction(direction)
39
, ma{}
40
{
41
}
42
44
void
begin()
45
{
46
pinMode(pinA, OUTPUT);
47
}
48
51
void
move(
const
int16_t power)
52
{
53
const
int16_t p = ma(constrain(power, -250, 250)) *
Udon::DirectionToSign
(direction);
54
digitalWrite(pinA, p >= 0 ? HIGH : LOW);
55
analogWrite(pinP, abs(p));
56
}
57
59
void
stop()
60
{
61
move(0);
62
}
63
65
void
show()
const
66
{
67
Serial.print(ma.
getValue
());
68
Serial.print(
'\t'
);
69
}
70
};
71
74
template
<
size_t
SmoothLevel>
75
class
SmoothlyMotor3
76
{
77
const
uint8_t pinA;
78
const
uint8_t pinB;
79
const
uint8_t pinP;
80
81
Udon::Direction
direction;
82
83
Udon::MovingAverage<SmoothLevel> ma;
84
85
public
:
86
92
SmoothlyMotor3(
const
uint8_t pinA,
const
uint8_t pinB,
const
uint8_t pinP,
Udon::Direction
direction =
Udon::Direction::Forward
)
93
: pinA(pinA)
94
, pinB(pinB)
95
, pinP(pinP)
96
, direction(direction)
97
, ma{}
98
{
99
}
100
102
void
begin()
103
{
104
pinMode(pinA, OUTPUT);
105
pinMode(pinB, OUTPUT);
106
}
107
110
void
move(
const
int16_t power)
111
{
112
const
int16_t p = ma(constrain(power, -250, 250)) *
Udon::DirectionToSign
(direction);
113
digitalWrite(pinA, p >= 0 ? HIGH : LOW);
114
digitalWrite(pinB, p <= 0 ? HIGH : LOW);
115
analogWrite(pinP, abs(p));
116
}
117
119
void
stop()
120
{
121
move(0);
122
}
123
125
void
show()
const
126
{
127
Serial.print(ma.
getValue
());
128
Serial.print(
'\t'
);
129
}
130
};
131
132
using
Motor2 = SmoothlyMotor2<50>;
133
using
Motor3 = SmoothlyMotor3<50>;
134
135
#ifdef __AVR_ATmega328P__
136
138
inline
void
ChangePwmPeriod()
139
{
140
TCCR1B &= B11111000;
141
TCCR1B |= B00000001;
142
TCCR2B &= B11111000;
143
TCCR2B |= B00000001;
144
}
145
146
#endif
147
148
}
// namespace Udon
149
150
#endif
Direction.hpp
MovingAverage.hpp
Udon::MovingAverage::getValue
double getValue() const noexcept
平均値の取得
Definition
MovingAverage.hpp:49
Udon
Definition
Bit.hpp:12
Udon::DirectionToSign
int DirectionToSign(Direction direction)
Definition
Direction.hpp:14
Udon::Direction
Direction
方向
Definition
Direction.hpp:9
Udon::Direction::Forward
@ Forward
Definition
Direction.hpp:10