<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ESP32 | ばすにっきTips</title>
	<atom:link href="https://takabus.com/tips/category/esp32/feed/" rel="self" type="application/rss+xml" />
	<link>https://takabus.com/tips</link>
	<description>プログラミングやサーバー、日々のTipsをメモしています。</description>
	<lastBuildDate>Sun, 27 Nov 2022 05:38:48 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.4.3</generator>

<image>
	<url>https://takabus.com/tips/wp-content/uploads/2022/12/cropped-tips-1-32x32.png</url>
	<title>ESP32 | ばすにっきTips</title>
	<link>https://takabus.com/tips</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>ESP32でSlackにメッセージを送信するには？</title>
		<link>https://takabus.com/tips/1864/</link>
					<comments>https://takabus.com/tips/1864/#respond</comments>
		
		<dc:creator><![CDATA[ばすにっきTips]]></dc:creator>
		<pubDate>Mon, 12 Sep 2022 10:38:56 +0000</pubDate>
				<category><![CDATA[ESP32]]></category>
		<guid isPermaLink="false">https://takabus.com/tips/?p=1864</guid>

					<description><![CDATA[ESP32やM5シリーズからSlackへメッセージを送信する方法を紹介します。]]></description>
										<content:encoded><![CDATA[
<p>ESP32やM5シリーズからSlackへメッセージを送信する方法を紹介します。</p>



<div class="wp-block-cocoon-blocks-balloon-ex-box-1 speech-wrap sb-id-1 sbs-stn sbp-l sbis-cb cf block-box"><div class="speech-person"><figure class="speech-icon"><img decoding="async" src="https://takabus.com/tips/wp-content/uploads/2021/09/man.png" alt="" class="speech-icon-image"/></figure><div class="speech-name"></div></div><div class="speech-balloon">
<p>サンプルコードも掲載していますので、コピペで実現できますよ～</p>
</div></div>



<h2 class="wp-block-heading">Slackにメッセージを送信するには？</h2>



<p>SlackにESP32からメッセージを送信するには、Slackの<strong>Incoming Webhook API</strong>を作成しておく必要があります。</p>



<p>Webhook APIの作成手順については次の記事の中で紹介していますので、あらかじめ作成しておきましょう。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-ばすにっきtips wp-block-embed-ばすにっきtips"><div class="wp-block-embed__wrapper">

<a href="https://takabus.com/tips/903/" title="【Slack】Curlコマンドでメッセージを送信するには？API有効化からPOSTでメッセージを送信するまでの手順" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img decoding="async" width="160" height="90" src="https://takabus.com/tips/wp-content/uploads/2022/01/slack-160x90.png" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://takabus.com/tips/wp-content/uploads/2022/01/slack-160x90.png 160w, https://takabus.com/tips/wp-content/uploads/2022/01/slack-300x169.png 300w, https://takabus.com/tips/wp-content/uploads/2022/01/slack-1024x576.png 1024w, https://takabus.com/tips/wp-content/uploads/2022/01/slack-768x432.png 768w, https://takabus.com/tips/wp-content/uploads/2022/01/slack-1536x864.png 1536w, https://takabus.com/tips/wp-content/uploads/2022/01/slack-120x68.png 120w, https://takabus.com/tips/wp-content/uploads/2022/01/slack-320x180.png 320w, https://takabus.com/tips/wp-content/uploads/2022/01/slack-374x210.png 374w, https://takabus.com/tips/wp-content/uploads/2022/01/slack.png 1920w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Slack】Curlコマンドでメッセージを送信するには？API有効化からPOSTでメッセージを送信するまでの手順</div><div class="blogcard-snippet internal-blogcard-snippet">curlコマンドを使用し、Slackへメッセージを送信する方法を紹介します。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img decoding="async" src="https://www.google.com/s2/favicons?domain=https://takabus.com/tips" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">takabus.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2022.01.23</div></div></div></div></a>
</div></figure>



<p>APIを作成すると、専用のURLが作成されます。作成されたURLに対し、メッセージ本文を含めたJSONをPOSTすると、任意のSlackチャンネルにメッセージを送信することができます。</p>



<h2 class="wp-block-heading">サンプルコード</h2>



<p>APIを作成したら、さっそくソースコードを作成していきましょう。</p>



<p>ESP32からJSONを送信するには、ArduinoJsonとHttpClientを使用していきます。</p>



<div class="wp-block-cocoon-blocks-balloon-ex-box-1 speech-wrap sb-id-1 sbs-stn sbp-l sbis-cb cf block-box"><div class="speech-person"><figure class="speech-icon"><img decoding="async" src="https://takabus.com/tips/wp-content/uploads/2021/09/man.png" alt="" class="speech-icon-image"/></figure><div class="speech-name"></div></div><div class="speech-balloon">
<p>もちろんHttpClientだけで送信することもできますが、ここでは将来的な拡張も容易に行えるようにJSONをオブジェクト的で扱えるArduinoJsonも組み合わせてみたいと思います。</p>
</div></div>



<p>main.cppの先頭で使用するライブラリのヘッダファイルをインクルードします。</p>



<pre class="wp-block-code"><code>#include &lt;ArduinoJson.h>
#include &lt;HTTPClient.h></code></pre>



<p>メッセージを送信する部分はこのようになります。</p>



<pre class="wp-block-code"><code>#include &lt;ArduinoJson.h>
#include &lt;HTTPClient.h>
 
///
/// Slackにメッセージを送信する
///

void SendSlackMessage(){
    // JSONを作成する
    StaticJsonDocument&lt;JSON_OBJECT_SIZE(1)> json_array;
    char json_string&#91;255];
<strong>    // 送信したいメッセージを指定する
    json_array&#91;"text"] = "こんにちは";</strong>
    // JSONフォーマットの文字列に変換する
    serializeJson(json_array, json_string, sizeof(json_string));
<strong>    // POSTするURLを指定する</strong>
<strong>    httpClient.begin("ここにWebhook URLを指定する");</strong>
    // postするのはjsonなので、Content-Typeをapplication/jsonにする
    httpClient.addHeader("Content-Type", "application/json");
    // POSTしてステータスコードを取得する
    int status_code = httpClient.POST((uint8_t *)json_string, strlen(json_string));
    if (status_code == 200)
    {
    Serial.printf("&#91;POST]Send to server (URL:%s)", postUrl);
    }
    else
    {
    Serial.printf("&#91;POST]failed to send to server (URL:%s)", postUrl);
    }
    // HTTPClinetを終了する
    httpClient.end();
}</code></pre>



<p>SendSlackMessageという名前の関数にしてみました。あとはこの関数を呼び出せば、Slackにメッセージを送信することができます。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>ESP32からSlackにメッセージを送信するサンプルを紹介しました。</p>



<p>なお、ESP32から単に通知を送りたいケースでは、LINE Notifyのほうが簡単です。あわせて確認しておくことをおすすめします。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-ばすにっきtips wp-block-embed-ばすにっきtips"><div class="wp-block-embed__wrapper">

<a href="https://takabus.com/tips/1855/" title="ESP32からLINEを送るには？サンプルコードを紹介（LINE Notify）" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img decoding="async" width="160" height="90" src="https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-160x90.png" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-160x90.png 160w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-300x169.png 300w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-1024x576.png 1024w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-768x432.png 768w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-1536x864.png 1536w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-120x68.png 120w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-320x180.png 320w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-374x210.png 374w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ.png 1920w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">ESP32からLINEを送るには？サンプルコードを紹介（LINE Notify）</div><div class="blogcard-snippet internal-blogcard-snippet">ESP32やM5StickからLINEメッセージを送信する方法を紹介します。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img decoding="async" src="https://www.google.com/s2/favicons?domain=https://takabus.com/tips" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">takabus.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2022.09.12</div></div></div></div></a>
</div></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://takabus.com/tips/1864/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>ESP32からLINEを送るには？サンプルコードを紹介（LINE Notify）</title>
		<link>https://takabus.com/tips/1855/</link>
					<comments>https://takabus.com/tips/1855/#respond</comments>
		
		<dc:creator><![CDATA[ばすにっきTips]]></dc:creator>
		<pubDate>Mon, 12 Sep 2022 03:09:50 +0000</pubDate>
				<category><![CDATA[ESP32]]></category>
		<guid isPermaLink="false">https://takabus.com/tips/?p=1855</guid>

					<description><![CDATA[ESP32やM5StickからLINEメッセージを送信する方法を紹介します。]]></description>
										<content:encoded><![CDATA[
<p>ESP32やM5StickからLINEメッセージ（LINE Notify）を送信する方法を紹介します。</p>



<div class="wp-block-cocoon-blocks-balloon-ex-box-1 speech-wrap sb-id-1 sbs-stn sbp-l sbis-cb cf block-box"><div class="speech-person"><figure class="speech-icon"><img decoding="async" src="https://takabus.com/tips/wp-content/uploads/2021/09/man.png" alt="" class="speech-icon-image"/></figure><div class="speech-name"></div></div><div class="speech-balloon">
<p>あらかじめLINE Notifyへの登録を済ませ、トークンを取得しておいてください。</p>




<a rel="noopener" href="https://notify-bot.line.me/ja/" title="LINE Notify" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img loading="lazy" decoding="async" src="https://s.wordpress.com/mshots/v1/https%3A%2F%2Fnotify-bot.line.me%2Fja%2F?w=160&#038;h=90" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">LINE Notify</div><div class="blogcard-snippet external-blogcard-snippet"></div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://notify-bot.line.me/ja/" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">notify-bot.line.me</div></div></div></div></a>
</div></div>



<h2 class="wp-block-heading">サンプルコード</h2>



<p>まずはサンプルをご覧ください。LINE NotifyのAPIにメッセージをPOSTしているだけです。</p>



<pre class="wp-block-code"><code>#include &lt;HTTPClient.h>
HTTPClient httpClient;
String LINE_NOTIFY_TOKEN = "<strong>トークンをここに入力</strong>";

void sendLine(String body)
{ 
  // HTTPClinetでPOSTする
  String postUrl = "https://notify-api.line.me/api/notify";
  httpClient.begin(postUrl);
  httpClient.addHeader("Content-Type", "application/x-www-form-urlencoded");
  httpClient.addHeader("Authorization", "Bearer " + LINE_NOTIFY_TOKEN);
  // POSTしてステータスコードを取得する
  int status_code = httpClient.POST("message=" + body);
  Serial.println(httpClient.getString());
  if (status_code == 200)
  {
    Serial.printf("&#91;SUCCESS]LINE Notify (URL:%s)", postUrl.c_str());
  }
  else
  {
    Serial.printf("&#91;SUCCESS]LINE Notify (URL:%s) Code:%d", postUrl.c_str(), status_code);
  }
  // HTTPClinetを終了する
  httpClient.end();
}</code></pre>



<p>これだけでLINEを送ることができます。</p>



<p>ESP32でPOSTする方法については、こちらの記事にまとめてあります。LINE NotifyにPOSTする際はJSONではなく<code>application/x-www-form-urlencoded</code>でエンコードする必要がありますが、以前の記事で紹介した手順をほぼ踏襲していますので、参考にしてみてください。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-ばすにっきtips wp-block-embed-ばすにっきtips"><div class="wp-block-embed__wrapper">

<a href="https://takabus.com/tips/759/" title="【ESP32】JSONをPOSTするには？HTTPClientがおすすめ！" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-160x90.png" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-160x90.png 160w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-300x169.png 300w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-1024x576.png 1024w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-768x432.png 768w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-1536x864.png 1536w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-120x68.png 120w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-320x180.png 320w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ-374x210.png 374w, https://takabus.com/tips/wp-content/uploads/2021/09/esp32ロゴ.png 1920w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【ESP32】JSONをPOSTするには？HTTPClientがおすすめ！</div><div class="blogcard-snippet internal-blogcard-snippet">ESP32でサーバーにJSONをPOSTする方法を紹介します。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://takabus.com/tips" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">takabus.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2021.12.28</div></div></div></div></a>
</div></figure>



<p></p>



<h2 class="wp-block-heading">メッセージを送信する</h2>



<p>sendLineを実行すると、LINE Notifyでメッセージが送信されます。</p>



<pre class="wp-block-code"><code>sendLine("こんにちは");</code></pre>



<p>引数に送信したいメッセージを指定してください。LINEが届きます。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://takabus.com/tips/1855/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【ESP32】GPIOピンの初期値に注意しよう！赤外線LEDやセンサを破損します！</title>
		<link>https://takabus.com/tips/997/</link>
					<comments>https://takabus.com/tips/997/#respond</comments>
		
		<dc:creator><![CDATA[ばすにっきTips]]></dc:creator>
		<pubDate>Tue, 01 Mar 2022 02:59:49 +0000</pubDate>
				<category><![CDATA[ESP32]]></category>
		<guid isPermaLink="false">https://takabus.com/tips/?p=997</guid>

					<description><![CDATA[GPIOの初期モードを考慮していないと、起動時に電圧が印加されてしまい、部品が故障することがあります。]]></description>
										<content:encoded><![CDATA[
<p>最近、ESP32を使って赤外線スマートリモコンを制作しています。</p>



<p>トランジスタを使用したスイッチング回路を作成し、赤外線LEDに十分なパルス電流を流せるように設計してみたのですが、なぜかテストを重ねていくうちにLEDの出力が落ちていく現象が見られました。赤外線LEDを交換してみると復活しますが、またしばらくすると出力が低下し使い物にならなくなります。パルス(&lt;10μs)では1Aまで流せるはずのLEDで、設計上は200mAのパルスを流すようにしてあるので、電流値は問題ないはずなのですが、<strong>どこかのタイミングで過電流が発生してしまい、故障しているようです。</strong></p>



<p><span class="bold"><span class="marker-under">原因はGPIOピンの初期モードを考慮していなかったため起こった、<span class="bold-red"><span class="fz-20px">ESP32が起動する</span></span></span></span><span class="bold"><span class="marker-under"><span class="bold-red"><span class="fz-20px">際</span></span></span></span><span class="bold"><span class="marker-under"><span class="bold-red"><span class="fz-20px">の意図しない出力</span></span>でした。</span></span></p>



<h2 class="wp-block-heading" id="デフォルトのgpioモードに注意しよう">デフォルトのGPIOモードに注意しよう！</h2>



<p>ESP32のGPIOピンのモードはプログラムから変更することができます。</p>



<pre class="wp-block-code"><code>pinMode(PIN,MODE)</code></pre>



<p>入力モードとする場合はINPUT、出力とする場合はOUTPUTとします。</p>



<p>しかし、ここで重要なのが、<span class="marker-under"><strong><span class="bold-red">pinMode関数が実行されるまでは、GPIOごとに決まっているデフォルトのモードで動作する</span>ということです。</strong></span></p>



<p>ESP32のGPIOにはそれぞれ既定のモードが決められています。プログラムから任意のモードに切り替えることはできますが、ESP32が起動し、モードを切り替えるプログラムが実行されるまでは、各GPIOは既定のモードで動作します。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="715" height="130" src="https://takabus.com/tips/wp-content/uploads/2022/02/image-11.png" alt="" class="wp-image-1000" srcset="https://takabus.com/tips/wp-content/uploads/2022/02/image-11.png 715w, https://takabus.com/tips/wp-content/uploads/2022/02/image-11-300x55.png 300w" sizes="(max-width: 715px) 100vw, 715px" /><figcaption>各GPIOはそれぞれデフォルトのモードが設定されている。ESP32起動時は既定のモードで動作する。</figcaption></figure>



<p>たとえ、setup関数の先頭にpinModeをプログラムしていたとしても、ESP32が起動してから実行されるまでにはそれなりの時間がかかります。<span class="marker-under"><strong>このため、デフォルトで電圧が印加されるモード（INPUT_PULLUPなど）になっているGPIOに、パルス波を流す前提で設計された回路が接続されていたりすると、<span class="bold-red">ESP32が起動する過程で連続的にONになってしまい、部品が故障してしまいます。</span></strong></span></p>



<p>今回赤外線LEDが故障してしまった原因も同じでした。赤外線LEDをリモコンに使用する場合は、10μs以下のパルス波で使用することを前提に設計します。通電時間を小さくする代わりに電流値を大きくすることで実用的な出力を得るようにするのですが、デフォルトでINPUT_PULLUPが設定されているGPIO16ピンに赤外線LEDの回路を接続していたため、ESP32が起動する間に連続してONになってしまっていたようです。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="715" height="130" src="https://takabus.com/tips/wp-content/uploads/2022/02/image-11.png" alt="" class="wp-image-1000" srcset="https://takabus.com/tips/wp-content/uploads/2022/02/image-11.png 715w, https://takabus.com/tips/wp-content/uploads/2022/02/image-11-300x55.png 300w" sizes="(max-width: 715px) 100vw, 715px" /><figcaption>GPIO16なら助かっていたのに・・・</figcaption></figure>



<p>連続上限50mAのLEDに対し、パルス許容最大値の200mAが流れる回路を組んでいたので、赤外線LEDが故障してしまったのでしょう。</p>



<h2 class="wp-block-heading" id="起動時に出力モードとなっているピンは要注意">起動時に出力モードとなっているピンは要注意！</h2>



<p>ESP32のGPIOピンの大半は、プログラムから自由にモードを変更できるようになっています。</p>



<p>一方、ピンモードを変更するプログラムが走るまでは、各GPIOは初期値で動作してしまいます。これを忘れていると、EPS32が起動する過程で意図しない電圧が出力され、トラブルの原因となります。GPIOを使用する際はESP32のデータシートなどを確認し、必ず初期値を確認しておくことをおすすめします。</p>



<div class="wp-block-cocoon-blocks-balloon-ex-box-1 speech-wrap sb-id-1 sbs-stn sbp-l sbis-cb cf block-box"><div class="speech-person"><figure class="speech-icon"><img decoding="async" src="https://takabus.com/tips/wp-content/uploads/2021/09/man-150x150.png" alt="" class="speech-icon-image"/></figure><div class="speech-name"></div></div><div class="speech-balloon">
<p>こちらのサイトの方がすべてのGPIOピンの初期値をまとめてくれています。</p>




<a rel="noopener" href="https://lang-ship.com/blog/work/esp32-gpio/" title="ESP32のGPIO研究" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img loading="lazy" decoding="async" src="https://lang-ship.com/blog/wp-content/uploads/2021/02/box_1200.png" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">ESP32のGPIO研究</div><div class="blogcard-snippet external-blogcard-snippet">概要Arduino IDEでのGPIOまわりを調査しなおしてみました。pinMode()まわりやアナログ入力のときにはどんなGPIOかを意識して利用する必要があります。GPIO一覧GPIO種類アナログ入力タッチ入力RTCPULLpinMod...</div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://lang-ship.com/blog/work/esp32-gpio/" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">lang-ship.com</div></div></div></div></a>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://takabus.com/tips/997/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>ESP32でOLEDディスプレイを使うには？ESP32でSSD1306を使うサンプルコードをまとめてみました！</title>
		<link>https://takabus.com/tips/737/</link>
					<comments>https://takabus.com/tips/737/#respond</comments>
		
		<dc:creator><![CDATA[ばすにっきTips]]></dc:creator>
		<pubDate>Sun, 02 Jan 2022 10:21:43 +0000</pubDate>
				<category><![CDATA[ESP32]]></category>
		<category><![CDATA[OLED]]></category>
		<guid isPermaLink="false">https://takabus.com/tips/?p=737</guid>

					<description><![CDATA[ESP32でOLEDディスプレイ（SSD1306）を使用する方法を紹介していきます。基本からよくあるサンプルコードまで掲載しています。]]></description>
										<content:encoded><![CDATA[
<p>SSD1306は300～400円程度で入手できる安価なOLEDディスプレイです。I2Cで制御できるため、Arduinoなどのマイコンでかんたんに動作させることができます。</p>



<p>当記事では<span class="bold-red"><span class="marker-under">ESP32でOLEDディスプレイ（SSD1306）を使用する方法</span></span>を紹介していきます。基本からよくあるサンプルコードまで掲載していますので、ぜひご覧ください。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box has-border-color has-blue-border-color"><div class="label-box-label block-box-label box-label fab-pencil"><span class="label-box-label-text block-box-label-text box-label-text">私の開発環境はコレ</span></div><div class="label-box-content block-box-content box-content">
<ul><li>ESP32 Devkit</li><li>SSD1306（128&#215;64）</li><li>Visual Studio Code＋PlatformIO</li></ul>
</div></div>



<h2 class="wp-block-heading">【重要】ちゃんとしたライブラリを選ぼう！</h2>



<p>定番のOLEDディスプレイである「SSD1306」ですが、ESP32で正常に動作するライブラリを見つけるのに意外と苦労しましたので、詳しく解説しておきます。</p>



<p><strong>おすすめのライブラリは<span class="bold"><em><span class="bold-red"><span class="marker-under">thingpulse/ESP8266 and ESP32 OLED driver for SSD1306 displays</span></span></em></span>です。</strong></p>




<a rel="noopener" href="https://registry.platformio.org/packages/libraries/thingpulse/ESP8266%20and%20ESP32%20OLED%20driver%20for%20SSD1306%20displays/installation" title="PlatformIO Registry" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img loading="lazy" decoding="async" src="https://cdn.registry.platformio.org/apple-touch-icon.png" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">PlatformIO Registry</div><div class="blogcard-snippet external-blogcard-snippet">The world&#039;s first package and project dependency management solution for embedded development</div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://registry.platformio.org" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">registry.platformio.org</div></div></div></div></a>




<a rel="noopener" href="https://github.com/ThingPulse/esp8266-oled-ssd1306" title="GitHub - ThingPulse/esp8266-oled-ssd1306: Driver for the SSD1306 and SH1106 based 128x64, 128x32, 64x48 pixel OLED display running on ESP8266/ESP32" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img loading="lazy" decoding="async" src="https://opengraph.githubassets.com/b3968b236b9d051c8d4b26f8585b5477beea9bde80608852cca48c5a8bfb5e9b/ThingPulse/esp8266-oled-ssd1306" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">GitHub - ThingPulse/esp8266-oled-ssd1306: Driver for the SSD1306 and SH1106 based 128x64, 128x32, 64x48 pixel OLED display running on ESP8266/ESP32</div><div class="blogcard-snippet external-blogcard-snippet">Driver for the SSD1306 and SH1106 based 128x64, 128x32, 64x48 pixel OLED display running on ESP8266/ESP32 - ThingPulse/e...</div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://github.com/ThingPulse/esp8266-oled-ssd1306" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">github.com</div></div></div></div></a>



<p><strong><em>thingpulse/ESP8266 and ESP32 OLED driver for SSD1306 displays</em></strong>は、Platform IOが公式で提供しているライブラリの中でトップ100に入る人気のライブラリです。目立ったバグもなく安定して動作しますし、人気なだけあってネット上の情報が豊富なため、特段の理由がない限りこちらを使うのがよいでしょう。</p>



<p>SSD1306については、Google検索すると他のライブラリも多数ヒットします。<strong><span class="marker-under"><span class="bold-red">しかし、バグが入っており正常に動作しないライブラリも少なくないようですので、注意したほうが良さそうです。</span></span></strong></p>



<p>というのも、この記事を書いたのはバグだらけのライブラリを導入し、なかなかうまくいかなかったから。ヘッダーファイルの書き換えをしないと動作しないようなライブラリを選んでしまったがために、かなり時間をロスしてしまいました。<span class="marker-under"><strong>ヘッダーファイルなど、ライブラリ自体の編集を要求するようなものは信頼性に欠けますので、選ばないようにしましょう。</strong></span></p>



<h2 class="wp-block-heading">とりあえず動かしてみよう！</h2>



<p>まずはとにかく一度動かしてみましょう。GitHubに掲載されているコードを使用し、SSD1306でテスト表示してみます。</p>



<h3 class="wp-block-heading">【STEP1】PlatformIOでプロジェクト作成</h3>



<p>PlatformIOでプロジェクトを作成します。</p>



<figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" src="https://takabus.com/tips/wp-content/uploads/2021/12/image-30.png" alt="" class="wp-image-738" width="840" height="630" srcset="https://takabus.com/tips/wp-content/uploads/2021/12/image-30.png 1024w, https://takabus.com/tips/wp-content/uploads/2021/12/image-30-300x225.png 300w, https://takabus.com/tips/wp-content/uploads/2021/12/image-30-768x576.png 768w" sizes="(max-width: 840px) 100vw, 840px" /></figure>



<h3 class="wp-block-heading">【STEP2】ライブラリをインストールしよう</h3>



<p>PlatformIOのコマンドラインから<em><strong><span class="marker-under"><span class="red">thingpulse/ESP8266 and ESP32 OLED driver for SSD1306 displays</span></span></strong></em>をインストールします。</p>



<pre class="wp-block-code"><code>platformio lib install 2978</code></pre>



<p>GitHubにはIDを指定してインストールする方法が記載されていましたが、もちろんPlatformIOのページにある通り、ライブラリの名前を指定してインストールしてもOKです。</p>




<a rel="noopener" href="https://registry.platformio.org/packages/libraries/thingpulse/ESP8266%20and%20ESP32%20OLED%20driver%20for%20SSD1306%20displays/installation" title="PlatformIO Registry" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img loading="lazy" decoding="async" src="https://cdn.registry.platformio.org/apple-touch-icon.png" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">PlatformIO Registry</div><div class="blogcard-snippet external-blogcard-snippet">The world&#039;s first package and project dependency management solution for embedded development</div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://registry.platformio.org" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">registry.platformio.org</div></div></div></div></a>



<pre class="wp-block-code"><code>pio lib install "thingpulse/ESP8266 and ESP32 OLED driver for SSD1306 displays@^4.2.1"</code></pre>



<h3 class="wp-block-heading">【STEP3】ESP32とディスプレイを接続しよう</h3>



<p>OLEDディスプレイ（SSD1306）はESP32に接続しなければ動きません。<span class="fz-14px"><span class="red">当然なんだけど、たまに忘れる(^^;)</span></span></p>



<p>OLEDとの通信は<span class="bold-red">I<sub>2</sub>C通信</span>により行います。ESP32の21にSDA、22にSCLを接続、VCCには3.3V、GNDにはGNDを接続するだけでOKです。</p>



<figure class="wp-block-table aligncenter"><table><thead><tr><th class="has-text-align-center" data-align="center">ESP32(GPIO)</th><th class="has-text-align-center" data-align="center"> OLED(SSD1306) </th></tr></thead><tbody><tr><td class="has-text-align-center" data-align="center">21</td><td class="has-text-align-center" data-align="center">SDA</td></tr><tr><td class="has-text-align-center" data-align="center">22</td><td class="has-text-align-center" data-align="center">SCL</td></tr><tr><td class="has-text-align-center" data-align="center">3.3V</td><td class="has-text-align-center" data-align="center">VCC</td></tr><tr><td class="has-text-align-center" data-align="center">GND</td><td class="has-text-align-center" data-align="center">GND</td></tr></tbody></table><figcaption>ESP32とOLEDのピン接続</figcaption></figure>



<p>なお、<span class="bold-red"><span class="marker-under">プルアップは不要</span></span>です。抵抗と接続してプルアップするように推奨しているサイトが多いですが、ESP32はプルアップ回路まで内蔵していますので、自分で回路を組む必要はありません。I<sub>2</sub>Cに限らず、ボタン回路などを作るときのプルアップもESP32側でできてしまいます。</p>



<h3 class="wp-block-heading">【STEP4】サンプルを動かしてみよう！</h3>



<p><span class="marker-under"><strong>GitHubにサンプルが掲載されているので、試しに動かしてみましょう。</strong></span></p>




<a rel="noopener" href="https://github.com/ThingPulse/esp8266-oled-ssd1306" title="GitHub - ThingPulse/esp8266-oled-ssd1306: Driver for the SSD1306 and SH1106 based 128x64, 128x32, 64x48 pixel OLED display running on ESP8266/ESP32" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img loading="lazy" decoding="async" src="https://opengraph.githubassets.com/b3968b236b9d051c8d4b26f8585b5477beea9bde80608852cca48c5a8bfb5e9b/ThingPulse/esp8266-oled-ssd1306" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">GitHub - ThingPulse/esp8266-oled-ssd1306: Driver for the SSD1306 and SH1106 based 128x64, 128x32, 64x48 pixel OLED display running on ESP8266/ESP32</div><div class="blogcard-snippet external-blogcard-snippet">Driver for the SSD1306 and SH1106 based 128x64, 128x32, 64x48 pixel OLED display running on ESP8266/ESP32 - ThingPulse/e...</div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://github.com/ThingPulse/esp8266-oled-ssd1306" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">github.com</div></div></div></div></a>



<p>examplesフォルダにいくつかのサンプルが用意されていますが、今回は<strong><span class="bold-red">SSD1306DrawingDemo</span></strong>を動作させてみます。<em>examples/SSD1306DrawingDemo/SSD1306DrawingDemo.ino</em>をコピーして、PlatformIOのプロジェクトの<em>src/main.cpp</em>にすべてコピペします。</p>



<p>動作結果はこのあと動画で紹介していますので、お楽しみに！</p>



<div class="wp-block-cocoon-blocks-toggle-box-1 toggle-wrap toggle-box block-box"><input id="toggle-checkbox-20211224221404" class="toggle-checkbox" type="checkbox"/><label class="toggle-button" for="toggle-checkbox-20211224221404"><strong> SSD1306DrawingDemo のソースコードはここをクリック</strong><span class="fz-14px">（長いので折りたたんでいます）</span></label><div class="toggle-content">
<pre class="wp-block-code"><code>/**
   The MIT License (MIT)
   Copyright (c) 2018 by ThingPulse, Daniel Eichhorn
   Copyright (c) 2018 by Fabrice Weinberg
   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:
   The above copyright notice and this permission notice shall be included in all
   copies or substantial portions of the Software.
   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
   SOFTWARE.
   ThingPulse invests considerable time and money to develop these open source libraries.
   Please support us by buying our products (and not the clones) from
   https:&#47;&#47;thingpulse.com
*/

// Include the correct display library
// For a connection via I2C using Wire include
#include &lt;Wire.h&gt;        // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306Wire.h" // legacy include: `#include "SSD1306.h"`
// or #include "SH1106Wire.h", legacy include: `#include "SH1106.h"`
// For a connection via I2C using brzo_i2c (must be installed) include
// #include &lt;brzo_i2c.h&gt; // Only needed for Arduino 1.6.5 and earlier
// #include "SSD1306Brzo.h"
// #include "SH1106Brzo.h"
// For a connection via SPI include
// #include &lt;SPI.h&gt; // Only needed for Arduino 1.6.5 and earlier
// #include "SSD1306Spi.h"
// #include "SH1106SPi.h"

// Use the corresponding display class:

// Initialize the OLED display using SPI
// D5 -&gt; CLK
// D7 -&gt; MOSI (DOUT)
// D0 -&gt; RES
// D2 -&gt; DC
// D8 -&gt; CS
// SSD1306Spi        display(D0, D2, D8);
// or
// SH1106Spi         display(D0, D2);

// Initialize the OLED display using brzo_i2c
// D3 -&gt; SDA
// D5 -&gt; SCL
// SSD1306Brzo display(0x3c, D3, D5);
// or
// SH1106Brzo  display(0x3c, D3, D5);

// Initialize the OLED display using Wire library
SSD1306Wire display(0x3c, SDA, SCL); // ADDRESS, SDA, SCL  -  SDA and SCL usually populate automatically based on your board's pins_arduino.h e.g. https://github.com/esp8266/Arduino/blob/master/variants/nodemcu/pins_arduino.h
// SH1106Wire display(0x3c, SDA, SCL);

// Adapted from Adafruit_SSD1306
void drawLines()
{
  for (int16_t i = 0; i &lt; display.getWidth(); i += 4)
  {
    display.drawLine(0, 0, i, display.getHeight() - 1);
    display.display();
    delay(10);
  }
  for (int16_t i = 0; i &lt; display.getHeight(); i += 4)
  {
    display.drawLine(0, 0, display.getWidth() - 1, i);
    display.display();
    delay(10);
  }
  delay(250);

  display.clear();
  for (int16_t i = 0; i &lt; display.getWidth(); i += 4)
  {
    display.drawLine(0, display.getHeight() - 1, i, 0);
    display.display();
    delay(10);
  }
  for (int16_t i = display.getHeight() - 1; i &gt;= 0; i -= 4)
  {
    display.drawLine(0, display.getHeight() - 1, display.getWidth() - 1, i);
    display.display();
    delay(10);
  }
  delay(250);

  display.clear();
  for (int16_t i = display.getWidth() - 1; i &gt;= 0; i -= 4)
  {
    display.drawLine(display.getWidth() - 1, display.getHeight() - 1, i, 0);
    display.display();
    delay(10);
  }
  for (int16_t i = display.getHeight() - 1; i &gt;= 0; i -= 4)
  {
    display.drawLine(display.getWidth() - 1, display.getHeight() - 1, 0, i);
    display.display();
    delay(10);
  }
  delay(250);
  display.clear();
  for (int16_t i = 0; i &lt; display.getHeight(); i += 4)
  {
    display.drawLine(display.getWidth() - 1, 0, 0, i);
    display.display();
    delay(10);
  }
  for (int16_t i = 0; i &lt; display.getWidth(); i += 4)
  {
    display.drawLine(display.getWidth() - 1, 0, i, display.getHeight() - 1);
    display.display();
    delay(10);
  }
  delay(250);
}

// Adapted from Adafruit_SSD1306
void drawRect(void)
{
  for (int16_t i = 0; i &lt; display.getHeight() / 2; i += 2)
  {
    display.drawRect(i, i, display.getWidth() - 2 * i, display.getHeight() - 2 * i);
    display.display();
    delay(10);
  }
}

// Adapted from Adafruit_SSD1306
void fillRect(void)
{
  uint8_t color = 1;
  for (int16_t i = 0; i &lt; display.getHeight() / 2; i += 3)
  {
    display.setColor((color % 2 == 0) ? BLACK : WHITE); // alternate colors
    display.fillRect(i, i, display.getWidth() - i * 2, display.getHeight() - i * 2);
    display.display();
    delay(10);
    color++;
  }
  // Reset back to WHITE
  display.setColor(WHITE);
}

// Adapted from Adafruit_SSD1306
void drawCircle(void)
{
  for (int16_t i = 0; i &lt; display.getHeight(); i += 2)
  {
    display.drawCircle(display.getWidth() / 2, display.getHeight() / 2, i);
    display.display();
    delay(10);
  }
  delay(1000);
  display.clear();

  // This will draw the part of the circel in quadrant 1
  // Quadrants are numberd like this:
  //   0010 | 0001
  //  ------|-----
  //   0100 | 1000
  //
  display.drawCircleQuads(display.getWidth() / 2, display.getHeight() / 2, display.getHeight() / 4, 0b00000001);
  display.display();
  delay(200);
  display.drawCircleQuads(display.getWidth() / 2, display.getHeight() / 2, display.getHeight() / 4, 0b00000011);
  display.display();
  delay(200);
  display.drawCircleQuads(display.getWidth() / 2, display.getHeight() / 2, display.getHeight() / 4, 0b00000111);
  display.display();
  delay(200);
  display.drawCircleQuads(display.getWidth() / 2, display.getHeight() / 2, display.getHeight() / 4, 0b00001111);
  display.display();
}

void printBuffer(void)
{
  // Initialize the log buffer
  // allocate memory to store 8 lines of text and 30 chars per line.
  display.setLogBuffer(5, 30);

  // Some test data
  const char *test&#91;] = {
      "Hello",
      "World",
      "----",
      "Show off",
      "how",
      "the log buffer",
      "is",
      "working.",
      "Even",
      "scrolling is",
      "working"};

  for (uint8_t i = 0; i &lt; 11; i++)
  {
    display.clear();
    // Print to the screen
    display.println(test&#91;i]);
    // Draw it to the internal screen buffer
    display.drawLogBuffer(0, 0);
    // Display it on the screen
    display.display();
    delay(500);
  }
}

void setup()
{
  display.init();

  // display.flipScreenVertically();

  display.setContrast(255);

  drawLines();
  delay(1000);
  display.clear();

  drawRect();
  delay(1000);
  display.clear();

  fillRect();
  delay(1000);
  display.clear();

  drawCircle();
  delay(1000);
  display.clear();

  printBuffer();
  delay(1000);
  display.clear();
}

void loop() {}</code></pre>
</div></div>



<p><strong><span class="marker-under-red">↑ソースコードを貼っておきましたので、こちらをコピペしてもらってもOK</span></strong></p>



<h2 class="wp-block-heading">実行してみよう！</h2>



<p>ソースコードをコピペしたら、<strong>ビルド</strong>してESP32に<strong>アップロード</strong>します。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="101" height="59" src="https://takabus.com/tips/wp-content/uploads/2021/12/image-31.png" alt="" class="wp-image-739"/></figure>



<p><strong><span class="marker-under">さあ動いてくれますでしょうか！？</span></strong></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="ESP32 OLED SSD1306 Test" width="1256" height="707" src="https://www.youtube.com/embed/0E7Hit21r7k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p><span class="fz-20px"><span class="bold-red">しっかり動いてくれました！よかった！</span></span></p>



<h2 class="wp-block-heading">基本的な使いかた</h2>



<p>基本となるソースコードは次のようになります。</p>



<pre class="wp-block-code"><code>#include &lt;Wire.h&gt;        
#include "SSD1306Wire.h" 

SSD1306Wire display(0x3c, SDA, SCL);

void setup()
{
  //初期化する
  display.init();

  <strong>//ここで処理をする
  display.drawString(10,10,"Test!Hello!");</strong>

  //表示する
  display.display();
  //バッファをクリア
  display.clear();
}

void loop() {}</code></pre>



<p>はじめに<strong><span class="marker-under">SSD1306W</span></strong><span class="marker-under"><strong>ire型</strong>の変数<strong>display</strong></span>を定義します。コンストラクタにディスプレイの<strong>I<sub>2</sub>Cアドレス</strong>と<strong>SDA、SCLのGPIOピン番号</strong>を渡しておきます。</p>



<p>I<sub>2</sub>Cアドレスはほとんどのケースで<strong>0x3c</strong>となっています。SSD1306の基盤上にシルク印刷されていますので、万が一動作しないときは確認してみるとよいかもしれません。ピンについては特別な場合を除き、SDA、SCLと指定しておけばOKです。自動的にGPIO21と22がディスプレイとの接続に使用できるようになります。</p>



<p>あとはsetupでdisplay.initを呼び出し、初期化すれば表示できるようになります。変数<strong>display</strong>がバッファとして働き、<span class="bold-red"><span class="marker-under">display.display()を呼び出すとデータがOLEDに転送され、実際に表示がされます。</span></span>基本はこれだけで、非常にかんたんに表示を行うことが出来ます。</p>



<p>なお、表示後にdisplay.clear()はバッファ（display変数）をクリアするという意味です。表示を消去するには<strong><span class="bold-red">display.resetDisplay()</span></strong>を実行します。</p>



<h2 class="wp-block-heading">よく使うサンプルコード集</h2>



<p>よく使うサンプルコードをまとめておきます。</p>



<h3 class="wp-block-heading">文字を表示する</h3>



<p>指定した座標に文字を表示したいときのサンプルです。<span class="marker-under"><strong><span class="red">display.drawString</span></strong></span>を使用します。</p>



<pre class="wp-block-code"><code>display.drawString(10,10,"Test!Hello!");</code></pre>



<p>実行すると、(x,y)=(10,10)の座標に<strong>Test!Hello!</strong>と表示します。</p>



<p></p>



<p><strong><span class="marker-under">文字の寄せ方は<span class="red">display.setTextAlignment</span>で指定できます。</span></strong></p>



<pre class="wp-block-code"><code>display.setTextAlignment(TEXT_ALIGN_CENTER)</code></pre>



<p>アンカーポイントを文字列のどこにするか、以下から指定することができます。</p>



<ul><li>TEXT_ALIGN_LEFT</li><li>TEXT_ALIGN_RIGHT</li><li>TEXT_ALIGN_CENTER</li><li>TEXT_ALIGN_CENTER_BOTH</li></ul>



<h3 class="wp-block-heading">バックグラウンドを白色にする</h3>



<p>デフォルトでは黒の背景に白で描画が行われます。バックグラウンドを白色にしたいときは、<strong><span class="marker-under">display.invertDisplay</span></strong>を呼び出します。</p>



<pre class="wp-block-code"><code>display.invertDisplay();</code></pre>



<p>もとに戻すには、<strong><span class="marker-under">normalDisplay</span></strong>を呼び出します。</p>



<pre class="wp-block-code"><code>display.normalDisplay();</code></pre>



<p>なお、文字色は自動的に変化しないため、setColorを使って手動で変更する必要があります。</p>



<h3 class="wp-block-heading">フォント・フォントサイズを変える</h3>



<p>setFontを実行すると、テキスト描画に使用するフォントを変更することができます。なお、<strong><span class="marker-under-red">フォントサイズの変更もフォントの変更で行います。</span></strong></p>



<pre class="wp-block-code"><code>void setFont(const uint8_t* fontData);</code></pre>



<p>フォントは次のページで作成できますので、あわせて確認してみることをおすすめします。</p>




<a rel="noopener" href="http://oleddisplay.squix.ch/#/home" title="Angularclient" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img loading="lazy" decoding="async" src="https://s.wordpress.com/mshots/v1/http%3A%2F%2Foleddisplay.squix.ch%2F%23%2Fhome?w=160&#038;h=90" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">Angularclient</div><div class="blogcard-snippet external-blogcard-snippet"></div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=http://oleddisplay.squix.ch/#/home" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">oleddisplay.squix.ch</div></div></div></div></a>



<h3 class="wp-block-heading">画像を描画する</h3>



<p>画像を描画することもできます。あらかじめ画像ファイルをXBM形式に変換しておき、ソースコードなどに埋め込んでおけば、任意の画像をOLEDに表示させることができます。</p>



<pre class="wp-block-code"><code>void drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, const uint8_t *xbm);</code></pre>



<p>こちらのサイトでXBM形式への変換が行えます。</p>




<a rel="noopener" href="https://www.online-utility.org/image/convert/to/XBM" title="Convert Image to XBM" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img loading="lazy" decoding="async" src="https://s.wordpress.com/mshots/v1/https%3A%2F%2Fwww.online-utility.org%2Fimage%2Fconvert%2Fto%2FXBM?w=160&#038;h=90" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">Convert Image to XBM</div><div class="blogcard-snippet external-blogcard-snippet"></div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://www.online-utility.org/image/convert/to/XBM" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">www.online-utility.org</div></div></div></div></a>



<h3 class="wp-block-heading">画面を点滅させる</h3>



<p>loopでnormalDisplayとinvertDisplayを繰り返すことにより、画面を点滅させることが出来ます。</p>



<pre class="wp-block-code"><code>void loop()
{
  delay(800);
  display.normalDisplay();
  delay(800);
  display.invertDisplay();
}</code></pre>



<p>delayにより一定時間（ここでは800ms）待機させることで、ディスプレイを目立たせることが可能です。エラー表示などに使用できるかもしれません。</p>



<h3 class="wp-block-heading">描画色の変更</h3>



<p><strong>display.setColor</strong>を使用すると、文字などの描画に使用する色を変更できます。</p>



<pre class="wp-block-code"><code>display.setColor(BLACK);</code></pre>



<h3 class="wp-block-heading">すべての表示を消す</h3>



<p>一度すべての表示を消したいときは、<strong>display.resetDisplay</strong>を呼び出します。</p>



<pre class="wp-block-code"><code>display.resetDisplay();</code></pre>



<p>呼び出すだけですべての表示が消去されます。display.displayの呼び出しは不要です。</p>



<h3 class="wp-block-heading">ディスプレイを上下逆にする</h3>



<pre class="wp-block-code"><code>display.flipScreenVertically();</code></pre>



<h3 class="wp-block-heading">左右反転して表示する</h3>



<pre class="wp-block-code"><code>display.mirrorScreen();</code></pre>



<h2 class="wp-block-heading">まとめ</h2>



<p>いかがでしたか？ESP32を使って、かんたんにOLEDディスプレイへ表示することが出来ました。</p>



<p><strong><span class="marker-under">意外な落とし穴は<span class="bold-red">ライブラリの選定</span>でしょう。</span></strong>安価で広く普及しているSSD1306だからこそ、さまざまなメーカーがライブラリを開発しているようです。その反面、信頼性の低いライブラリやネット情報が氾濫しており、不確かな情報のためにバグに悩まされることがありえます。当記事の方法を使っていただければ、確実にディスプレイを動作させることができると思いますので、参考にしてみてください。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://takabus.com/tips/737/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【ESP32】JSONをPOSTするには？HTTPClientがおすすめ！</title>
		<link>https://takabus.com/tips/759/</link>
					<comments>https://takabus.com/tips/759/#respond</comments>
		
		<dc:creator><![CDATA[ばすにっきTips]]></dc:creator>
		<pubDate>Tue, 28 Dec 2021 06:18:16 +0000</pubDate>
				<category><![CDATA[ESP32]]></category>
		<guid isPermaLink="false">https://takabus.com/tips/?p=759</guid>

					<description><![CDATA[ESP32でサーバーにJSONをPOSTする方法を紹介します。]]></description>
										<content:encoded><![CDATA[
<p>ESP32でサーバーにJSONをPOSTする方法を紹介します。</p>



<h2 class="wp-block-heading">おすすめのライブラリ</h2>



<p>HTTP通信にはArduino Espressif32に含まれている<span class="bold-red"><span class="marker-under">HTTPClient</span></span>を使用します。</p>



<p>JSONの処理については<span class="bold-red"><span class="marker-under">ArudinoJson</span></span>がおすすめです。</p>




<a rel="noopener" href="https://platformio.org/lib/show/64/ArduinoJson" title="PlatformIO Registry" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img loading="lazy" decoding="async" src="https://cdn.registry.platformio.org/apple-touch-icon.png" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">PlatformIO Registry</div><div class="blogcard-snippet external-blogcard-snippet">The world&#039;s first package and project dependency management solution for embedded development</div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://registry.platformio.org" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">registry.platformio.org</div></div></div></div></a>



<h2 class="wp-block-heading">サンプル</h2>



<p>ライブラリを読み込むため、<strong><span class="marker-under">includeに次を記載します。</span></strong></p>



<pre class="wp-block-code"><code>#include &lt;ArduinoJson.h&gt;
#include &lt;HTTPClient.h&gt;
</code></pre>



<p><span class="marker-under"><strong>POSTするサンプルは次のようになります。</strong></span></p>



<pre class="wp-block-code"><code>  ///
  /// サーバーにPOSTする
  ///

  // JSONを作成する
  StaticJsonDocument&lt;JSON_OBJECT_SIZE(4)&gt; json_array;
  char json_string&#91;255];
  // JSONに変換したいデータを連想配列で指定する
  json_array&#91;"espid"] = 1;
  json_array&#91;"temp"] = 2;
  json_array&#91;"humi"] = 3;
  json_array&#91;"press"] = 4;
  // JSONフォーマットの文字列に変換する
  serializeJson(json_array, json_string, sizeof(json_string));
  // HTTPClinetでPOSTする
  httpClient.begin("https://test.lc/hoge.php");
  // postするのはjsonなので、Content-Typeをapplication/jsonにする
  httpClient.addHeader("Content-Type", "application/json");
  // POSTしてステータスコードを取得する
  int status_code = httpClient.POST((uint8_t *)json_string, strlen(json_string));
  if (status_code == 200)
  {
    Serial.printf("&#91;POST]Send to server (URL:%s)", postUrl);
  }
  else
  {
    Serial.printf("&#91;POST]failed to send to server (URL:%s)", postUrl);
  }
  // HTTPClinetを終了する
  httpClient.end();
</code></pre>



<p>espid,temp,humi,pressの4つのデータをJSONに変換し、 https://test.lc/hoge.phpに送信するサンプルとしてみました。</p>



<p>ArduinoJsonを使用し、配列をJSON形式の文字列に変換させ、変換した文字列をサーバーにPOSTしています。</p>



<p>レスポンスも受け取るようにしており、200以外ではシリアルにエラーを出力するようにしてみました。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>HTTPClientとArduinoJSONの組み合わせて、JSONによるデータのやり取りもかんたんに対応できます。ESP32で収集したデータをサーバーに送信する際など、ぜひ使ってみてください。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://takabus.com/tips/759/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>ESPAsyncWebServerでパラメータを取得するには？</title>
		<link>https://takabus.com/tips/29/</link>
					<comments>https://takabus.com/tips/29/#respond</comments>
		
		<dc:creator><![CDATA[ばすにっきTips]]></dc:creator>
		<pubDate>Fri, 17 Sep 2021 05:46:41 +0000</pubDate>
				<category><![CDATA[ESP32]]></category>
		<category><![CDATA[ESPAsyncWebServer]]></category>
		<guid isPermaLink="false">http://192.168.1.3/~t.h/tips/?p=29</guid>

					<description><![CDATA[ESP32で動作する非同期Webサーバー「ESPAsyncWebServer」をつかって、GET・POSTされたパラメータを取得する方法を紹介します。]]></description>
										<content:encoded><![CDATA[
<p>ESP32で動作する非同期Webサーバー「ESPAsyncWebServer」をつかって、GET・POSTされたパラメータを取得する方法を紹介します。argとgetParamsの違いがわかりにくかったので、整理してみました。</p>



<h2 class="wp-block-heading">クエリパラメータを取得するには？</h2>



<p>クエリパラメータとは、</p>



<p class="has-watery-yellow-background-color has-background"><strong>http://&lt;ESP32のIPアドレス&gt;/api?param=hoge</strong></p>



<p>でいうところの<strong><span class="bold-red">?param=hoge</span></strong>のことです。つまり、URL末尾に含まれるパラメータのことを指します。</p>



<p>ESPAsyncWebServerでクエリパラメータを取得するには、<strong><span class="marker">getParam()</span></strong>を使用します。</p>



<pre class="wp-block-code"><code> server.on("/test", HTTP_GET, &#91;](AsyncWebServerRequest *request) {
      String value=request-&gt;getParam("param")-&gt;value();
      Serial.print(value);
}
</code></pre>



<p><code>http://&lt;ESP32のIPアドレス&gt;/test?param=hoge</code>にアクセスすると、シリアルコンソールにhogeと表示されます。</p>



<p>このサンプルではGETされたときに取得していますが、HTTP_GETをHTTP_ANYにすれば、POSTやPUTといった他のメソッドでも同様に動作させることができます。</p>



<h2 class="wp-block-heading">POSTされたパラメータを取得するには？</h2>



<p>POSTされたパラメータ（<span class="bold-red">formタグにより送信されたパラメータ</span>など）を取得するには、<strong><span class="marker">arg()</span></strong>を使用します。</p>



<pre class="wp-block-code"><code> server.on("/test", HTTP_ANY, &#91;](AsyncWebServerRequest *request) {
      String value=request-&gt;arg("param");
      print(value);
}</code></pre>



<p>/testにデータがPOSTされると、paramの値を取得して、シリアルポートに出力します。</p>



<p>arg()は、application/x-www-form-urlencodedとmultipart/form-dataの両者に対応します。<strong><span class="marker-under">つまり、&lt;form&gt;タグで作成したフォームのデータでも、javascriptのFormDataオブジェクトでも解釈することができます。</span></strong></p>




<a rel="noopener" href="https://developer.mozilla.org/ja/docs/Web/HTTP/Methods/POST" title="POST - HTTP | MDN" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img loading="lazy" decoding="async" src="https://developer.mozilla.org/mdn-social-share.d893525a4fb5fb1f67a2.png" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">POST - HTTP | MDN</div><div class="blogcard-snippet external-blogcard-snippet">HTTP の POST メソッドは、サーバーにデータを送信します。リクエストの本文の型は Content-Type ヘッダーで示されます。</div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://developer.mozilla.org/ja/docs/Web/HTTP/Reference/Methods/POST" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">developer.mozilla.org</div></div></div></div></a>



<div class="wp-block-cocoon-blocks-icon-box alert-box common-icon-box block-box">
<p><strong>getParamはクエリパラメータを取得するための関数！</strong></p>



<p>公式のGitHubには、POSTされたパラメータを取得する関数としてgetParams()が紹介されています。</p>



<p><span class="marker-under"><span class="bold-red">しかし、</span></span><span class="marker-under"><span class="bold-red">この方法</span></span><span class="marker-under"><span class="bold-red">でPOSTされたデータを取得することは、基本的にできません。</span></span></p>



<p>getParamsは、<strong>クエリパラメータの取得</strong>に使用される関数です。</p>



<p>クエリパラメータとは、</p>



<p class="has-watery-yellow-background-color has-background"><strong>http://&lt;ESP32のIPアドレス&gt;/api?param=hoge</strong></p>



<p>でいうところの<strong>?param=hoge</strong>のこと。つまり、URLに含まれるパラメータを取得するための関数です。</p>



<p><span class="bold-red">getParam()でformタグやFormDataから送信されたボディパラメータを取得することはできません</span>ので、注意してください。ボディパラメータをgetParam()で取得しようとすると、以下のような例外が発生し、ESP32がリセット（再起動）されてしまいます。</p>



<pre class="wp-block-code"><code>Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x40151d6b  PS      : 0x00060a30  A0      : 0x800d6d03  A1      : 0x3ffd0c50
A2      : 0x0000000c  A3      : 0x3ffd0cb8  A4      : 0x00000001  A5      : 0x00000003
A6      : 0x00ff0000  A7      : 0xff000000  A8      : 0x800d6a17  A9      : 0x3ffd0c30
A10     : 0x3ffd0cb8  A11     : 0x3ffd0cb8  A12     : 0x3ffd14e8  A13     : 0x0000ff00
A14     : 0x00ff0000  A15     : 0xff000000  SAR     : 0x00000010  EXCCAUSE: 0x0000001c
EXCVADDR: 0x00000014  LBEG    : 0x400012e5  LEND    : 0x40001309  LCOUNT  : 0x800d6f47

ELF file SHA256: 0000000000000000

Backtrace: 0x40151d6b:0x3ffd0c50 0x400d6d00:0x3ffd0c70 0x400d0f13:0x3ffd0c90 0x400d5871:0x3ffd0d00 0x400d4739:0x3ffd0d40 0x400d47c1:0x3ffd0d90 0x401489c1:0x3ffd0db0 0x40148a3d:0x3ffd0df0 0x401490ee:0x3ffd0e10 0x4008996a:0x3ffd0e40</code></pre>
</div>



<h2 class="wp-block-heading">まとめ</h2>



<p>ESPAsyncWebServerをつかって、リクエストされたパラメーターを取得する方法を紹介しました。</p>



<p>argとgetParamsの違いがわかりにくいので、注意が必要です。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://takabus.com/tips/29/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
