UdonLibrary 1.0.0
機械システム研究部 C++ ライブラリ
読み取り中…
検索中…
一致する文字列を見つけられません
StateMachineAllocator.hpp
[詳解]
1//
2// ステートマシン割り当て
3//
4// Copyright (c) 2022-2024 udonrobo
5//
6
7#pragma once
8
9#if defined(ARDUINO_ARCH_RP2040)
10
11# include <hardware/pio.h>
13# include <map>
14
15namespace Udon
16{
17 namespace Pio
18 {
19
20 namespace Impl
21 {
24 inline std::map<const pio_program_t*, int>* GetPioInstructionMemory()
25 {
26 static std::map<const pio_program_t*, int> memory[2];
27 return memory;
28 }
29
30 } // namespace Impl
31
45 struct StateMachine
46 {
47 PIO pio; // pio0 or pio1
48 int index; // state machine index 0~3
49 int offset; // offset of the program
50 };
51
56 inline Udon::Optional<StateMachine> AllocateStateMachine(const pio_program& program)
57 {
58 PIO pios[] = { pio0, pio1 };
59 auto memory = Impl::GetPioInstructionMemory();
60
61 // 既にプログラムメモリに同じプログラムがロードされている場合はそれを使用
62 for (int i = 0; i < 2; i++)
63 {
64 auto p = memory[i].find(&program);
65 if (p == memory[i].end())
66 {
67 continue;
68 }
69
70 const int index = pio_claim_unused_sm(pios[i], false);
71 if (index == -1)
72 {
73 continue;
74 }
75
76 return StateMachine{ pios[i], index, p->second };
77 }
78
79 // 新しいプログラムをプログラムメモリにロード
80 for (int i = 0; i < 2; i++)
81 {
82 if (pio_can_add_program(pios[i], &program))
83 {
84 const int index = pio_claim_unused_sm(pios[i], false);
85 if (index == -1)
86 {
87 continue;
88 }
89
90 const int offset = pio_add_program(pios[i], &program);
91 // 失敗するとパニック
92
93 memory[i].insert({ &program, offset });
94
95 return StateMachine{ pios[i], index, offset };
96 }
97 }
98
99 return Udon::nullopt;
100 }
101
104 inline void FreeStateMachine(const StateMachine& sm)
105 {
106 pio_sm_unclaim(sm.pio, sm.index);
107 }
108
111 inline void ShowStateMachineInfo(const StateMachine& sm)
112 {
113 if (sm.pio == pio0)
114 {
115 Serial.print("pio0");
116 }
117 else if (sm.pio == pio1)
118 {
119 Serial.print("pio1");
120 }
121 else
122 {
123 Serial.print("pio?");
124 return;
125 }
126
127 Serial.print(" sm = ");
128 Serial.print(sm.index);
129
130 Serial.print(" offset = ");
131 Serial.print(sm.offset);
132 }
133
134 } // namespace Pio
135} // namespace Udon
136
137#endif
オプショナル型
Definition Optional.hpp:62
Definition Bit.hpp:12
constexpr NulloptT nullopt
無効値
Definition Optional.hpp:52