<?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>OLED | ばすにっきTips</title>
	<atom:link href="https://takabus.com/tips/tag/oled/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>OLED | ばすにっきTips</title>
	<link>https://takabus.com/tips</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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 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 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 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 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 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 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>
	</channel>
</rss>
