md10c_uno
Toggle main menu visibility
読み取り中…
検索中…
一致する文字列を見つけられません
main.cpp
[詳解]
1
#include <Arduino.h>
2
#include <stdlib.h>
3
#include <string.h>
4
5
namespace
{
6
constexpr
uint8_t kPwmPin = 3;
7
constexpr
uint8_t kDirPin = 2;
8
constexpr
unsigned
long
kCommandTimeoutMs = 500;
9
constexpr
size_t
kMaxLineLength = 16;
10
11
char
line[kMaxLineLength + 1];
12
size_t
lineLength = 0;
13
bool
discardingLine =
false
;
14
unsigned
long
lastCommandMs = 0;
15
int
appliedCommand = 0;
16
17
void
applyCommand(
int
command) {
18
command = constrain(command, -255, 255);
19
if
(command == appliedCommand) {
20
return
;
21
}
22
23
// Prevent direction changes while the bridge is actively driving the motor.
24
if
((command < 0) != (appliedCommand < 0) && appliedCommand != 0) {
25
analogWrite(kPwmPin, 0);
26
}
27
28
digitalWrite(kDirPin, command < 0 ? HIGH : LOW);
29
analogWrite(kPwmPin, abs(command));
30
appliedCommand = command;
31
}
32
33
bool
parseCommand(
const
char
* text,
int
& value) {
34
if
(*text ==
'\0'
) {
35
return
false
;
36
}
37
38
char
* end =
nullptr
;
39
const
long
parsed = strtol(text, &end, 10);
40
if
(end == text || *end !=
'\0'
) {
41
return
false
;
42
}
43
44
if
(parsed < -255) {
45
value = -255;
46
}
else
if
(parsed > 255) {
47
value = 255;
48
}
else
{
49
value =
static_cast<
int
>
(parsed);
50
}
51
return
true
;
52
}
53
54
void
consumeByte(
char
incoming) {
55
if
(incoming ==
'\r'
) {
56
return
;
57
}
58
59
if
(incoming ==
'\n'
) {
60
if
(!discardingLine) {
61
line[lineLength] =
'\0'
;
62
int
command = 0;
63
if
(parseCommand(line, command)) {
64
lastCommandMs = millis();
65
applyCommand(command);
66
}
67
}
68
lineLength = 0;
69
discardingLine =
false
;
70
return
;
71
}
72
73
if
(discardingLine) {
74
return
;
75
}
76
if
(lineLength >= kMaxLineLength) {
77
lineLength = 0;
78
discardingLine =
true
;
79
return
;
80
}
81
line[lineLength++] = incoming;
82
}
83
}
// namespace
84
85
void
setup
() {
86
pinMode(kPwmPin, OUTPUT);
87
pinMode(kDirPin, OUTPUT);
88
digitalWrite(kDirPin, LOW);
89
analogWrite(kPwmPin, 0);
90
Serial.begin(115200);
91
lastCommandMs = millis();
92
}
93
94
void
loop
() {
95
while
(Serial.available() > 0) {
96
consumeByte(
static_cast<
char
>
(Serial.read()));
97
}
98
99
if
(appliedCommand != 0 && millis() - lastCommandMs >= kCommandTimeoutMs) {
100
applyCommand(0);
101
}
102
}
setup
void setup()
定義
main.cpp:85
loop
void loop()
定義
main.cpp:94
src
main.cpp
構築:
1.18.0