> For the complete documentation index, see [llms.txt](https://mwx.twelite.info/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mwx.twelite.info/v0.1.7/act_samples/scratch.md).

# Scratch

テンプレートコードです。

act0は中身が空でしたがScratchには以下のコードが含まれます。

## setup()

```cpp
void setup() {
	/*** SETUP section */
	txreq_stat = MWX_APIRET(false, 0);

	// the twelite main class
	the_twelite
		<< TWENET::appid(APP_ID)    // アプリケーションID
		<< TWENET::channel(CHANNEL) // チャネル
		<< TWENET::rx_when_idle();  // 受信有

	// Register Network
	auto&& nwk = the_twelite.network.use<NWK_SIMPLE>();
	nwk	<< NWK_SIMPLE::logical_id(0xFE); // 子機、特定アドレス指定なし(0xFE)

	/*** BEGIN section */
	Buttons.begin(pack_bits(PIN_BTN), 5, 10); // ボタン処理初期化

	the_twelite.begin(); // start twelite!

	/*** INIT message */
	Serial << "--- Scratch act ---" << mwx::crlf;
}
```

アプリケーションID `APP_ID`, 無線チャネル`CHANNEL`、受信有、子機アドレス`0xFE`として始動します。

## begin()

```cpp
void begin() {
	Serial << "..begin (run once at boot)" << mwx::crlf;
}
```

始動時`setup()`の後に１回だけ呼び出されます。メッセージの表示のみ。

## loop()

### ボタン（スイッチ）の入力検出

```cpp
if (Buttons.available()) {
	uint32_t bm, cm;
	Buttons.read(bm, cm);

	if (cm & 0x80000000) {
		// the first capture.
	}

	Serial << int(millis()) << ":BTN" << format("%b") << mwx::crlf;
}
```

[Buttons](/v0.1.7/api-reference/predefined_objs/buttons.md)による連続参照により状態を確定します。ボタン状態が変化したらシリアルに出力します。

### シリアルからの入力

```cpp
while(Serial.available())  {
  int c = Serial.read();

	Serial << '[' << char(c) << ']';

  switch(c) {
  case 'p': ... // millis() を表示
  case 't': ... // 無線パケットを送信 (vTransmit)
  case 's': ... // スリープする
  }
}
```

シリアルから１文字読み込んで、入力文字に応じた処理をします。

### パケットの受信

```cpp
if (the_twelite.receiver.available()) {

		auto&& rx = the_twelite.receiver.read();

		// just dump a packet.
		Serial << format("rx from %08x/%d",
		   rx.get_addr_src_long(), rx.get_addr_src_lid()) << crlf;
}
```

パケットを受信したら、送信元のアドレス情報を表示します。

## wakeup()

```cpp
void wakeup() {
	Serial << int(millis()) << ":wake up!" << mwx::crlf;
}
```

スリープ起床時に最初に呼び出されます。メッセージの表示のみ。

## vTransmit()

```cpp
MWX_APIRET vTransmit() {
	Serial << int(millis()) << ":vTransmit()" << mwx::crlf;

	if (auto&& pkt = the_twelite.network.use<NWK_SIMPLE>().prepare_tx_packet()) {
		// set tx packet behavior
		pkt << tx_addr(0xFF)  // 同報通信＝ブロードキャスト
			<< tx_retry(0x1)    // 再送１回
			<< tx_packet_delay(100,200,20); // 送信時遅延100-200msの間に送信、再送間隔20ms

		// 送信データの指定（アプリケーションごとに決める）
		pack_bytes(pkt.get_payload()
			, make_pair("SCRT", 4) // ４文字識別子
			, uint32_t(millis())   // タイムスタンプ
		);
		
		// 送信要求を行う
		return pkt.transmit(); 
	}

  // .prepare_tx_packet() 時点で失敗している
	return MWX_APIRET(false, 0);
}
```

送信要求を行う最小限の手続きです。

この関数を抜けた時点では、まだ要求は実行されていません。しばらく待つ必要があります。この例では100-200msの送信開始の遅延があるため、送信が開始されるのは早くて100ms後です。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://mwx.twelite.info/v0.1.7/act_samples/scratch.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
