Oled дисплей. урок 21. ардуино

Introduction to the SSD1306 OLED Display Chip

Raspberry Pi 0.91’OLED Display Module (SSD1306)

The SSD1306 is a 128×64 dot single chip driver with a controller that’s used for graphic display systems. It’s commonly integrated into OLED display modules like the one seen above for Arduino, Raspberry Pi, or other microcontroller usages.

With embedded colour contrast and brightness control, alongside display RAM, oscillator, the SSD1306 is a chip that not only consumes minimal power, but also does not require many external components for functionality!

Other features include:

  • Internal Charge Pump Regulator
  • RAM Write Synchronisation Signal
  • Programmable Frame Rate with Multiplexing Ratio
  • On-chip Oscillator
  • Wide Operating Temperatures (-40ºC to 85ºC)

Note: The features and specifications may differ based on the design of the display modules which are integrated with the SSD1306.

Interested to find out more about this chip? Read more in the SSD1306 Datasheet and its relevant libraries!

Arduino OLED I²C Libraries for SSD1306 and Graphics Functions

Two Arduino libraries must be installed to start using the display. The SSD1306 driver library is used to initialize the display and provide low level display functions. The GFX library provides graphics functions for displaying text, drawing lines and circles, etc. Both these libraries are available from Adafruit.

Install the SSD1306 Driver Library

Download the Adafruit_SSD1306 library which is saved to your computer in a file called Adafruit_SSD1306-master.zip.

Copy the Adafruit_SSD1306-master folder from the downloaded zipped file into the Arduino libraries folder. This folder is usually found at Documents → Arduino → libraries on Windows systems. On Linux it is usually found at home folder → Arduino → libraries.

Finally in the Arduino library folder, rename the Adafruit_SSD1306-master folder to Adafruit_SSD1306.

Install the GFX Library

Download the Adafruit_GFX library which is saved to your computer in a file called Adafruit-GFX-Library-master.zip.

Copy the Adafruit-GFX-Library-master folder from the downloaded zipped file to the Arduino library folder as done for the SSD1306 driver above.

In the Arduino library folder rename the Adafruit-GFX-Library-master folder to Adafruit_GFX.

Verifying the Library Installation

After installing the libraries, your Arduino library folder should look as follows.

Arduino Library Folder with New Libraries Installed

The contents of the two library folders should look as follows, with the SSD1306 driver library folder on the left and GFX library on the right.

Adafruit SSD1306 and GFX Library Folders

Finding the OLED Libraries in Arduino

If the Arduino IDE was open during the library installation, close it first and then restart it.

In the Arduino IDE, find the libraries under the Sketch → Include Library menu from the top menu bar. When the mouse cursor is hovered above the Include Library menu item, the new libraries can be found on the pop-out menu. In Windows the libraries appeared under «Contributed libraries» near the top of the pop-out menu on my system. On my Linux computer the libraries appeared under the «Recommended libraries» section of the pop-out menu near the bottom.

Modifying the SSD1306 Driver

The SSD1306 driver isn’t set up for the Geekcreit OLED display by default. The display size must be changed in the driver before it can be used. If it is not changed, an error message will appear when attempting to verify the example sketch (see the section below) in the Arduino IDE:#error («Height incorrect, please fix Adafruit_SSD1306.h!»);

Open the Adafruit_SSD1306 folder that was just installed in the Arduino libraries folder. Find Adafruit_SSD1306.h and open it in a text editor. Scroll down the file to find the section with the header SSD1306 Displays or search for for this term in the text editor to find it quickly. Comment out #define SSD1306_128_32 and uncomment #define SSD1306_128_64 so that the code in this section looks as follows.

/*=========================================================================
    SSD1306 Displays
    -----------------------------------------------------------------------
    The driver is used in multiple displays (128x64, 128x32, etc.).
    Select the appropriate display below to create an appropriately
    sized framebuffer, etc.

    SSD1306_128_64  128x64 pixel display

    SSD1306_128_32  128x32 pixel display

    SSD1306_96_16

    -----------------------------------------------------------------------*/
   #define SSD1306_128_64
//   #define SSD1306_128_32
//   #define SSD1306_96_16
/*=========================================================================*/

Save the file after making the changes.

License

The library is free. If this project helps you, you can give me a cup of coffee. Donate via Paypal

MIT License

Copyright (c) 2016-2019, Alexey Dynda

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.

Features

  • Draw pixels at given coordinates
  • Draw lines from given coordinates to given coordinates
  • Draw or fill a rectangle with given dimensions
  • Draw Text at given coordinates:
  • Define Alignment: Left, Right and Center
  • Set the Fontface you want to use (see section Fonts below)
  • Limit the width of the text by an amount of pixels. Before this widths will be reached, the renderer will wrap the text to a new line if possible
  • Display content in automatically side scrolling carousel
  • Define transition cycles
  • Define how long one frame will be displayed
  • Draw the different frames in callback methods
  • One indicator per frame will be automatically displayed. The active frame will be displayed from inactive once

Скетч: Отображение на OLED-дисплее данных о температуре и влажности

Цель этого проекта – ознакомить вас с тем, как работает OLED-дисплей. Температура и влажность будут измеряться при помощи датчика DHT11. Если вы слышите о нем впервые, имеет смысл сначала почитать эту статью.

Подключите эти компоненты друг к другу, как показано на схеме ниже:

Код

Убедитесь, что установили обе библиотеки для управления OLED-дисплеем – «adafruit_GFX.h» и «adafruit_SSD1306.h». Кроме того, вам понадобится библиотека «DHT».

Установка библиотеки «DHT»

  • Распакуйте этот архив. В итоге у вас должна получиться папка под названием «DHT-sensor-library-master».
  • Переименуйте ее на «DHT_sensor_library».
  • Переместите папку «DHT_sensor_library» в папку «libraries» IDE Arduino.
  • Перезапустите IDE Arduino

Затем загрузите на Arduino код, показанный ниже:

 1 /*
 2  * Автор – Руи Сантос (Rui Santos)
 3  * Более подробно о проекте на: http://randomnerdtutorials.com
 4  */
 5  
 6 #include <Wire.h>
 7 #include <Adafruit_GFX.h>
 8 #include <Adafruit_SSD1306.h>
 9 #include <DHT.h>
10 
11 #define DHTPIN 2     // контакт, к которому подключаемся 
12 #define DHTTYPE DHT11   // для датчика DHT11
13 #define OLED_RESET 4
14 Adafruit_SSD1306 display(OLED_RESET);
15 
16 // создаем экземпляр класса для датчика DHT11: 
17 DHT dht(DHTPIN, DHTTYPE);
18 
19 void setup()
20 {
21   Wire.begin();
22   dht.begin(); // инициализируем объект «dht»
23   display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
24   // инициализируем объект «display» с I2C-адресом «0x3C», для 128x32
25   Serial.begin(9600);
26 }
27 void displayTempHumid(){
28   delay(2000);
29   // считывание данных о температуре и влажности 
30   // занимает около 250 мс; кроме того, это считывание
31   // может запаздывать примерно на 2 секунды 
32   // (это очень медленный датчик):
33   float h = dht.readHumidity();
34   // считываем температуру в градусах Цельсия:
35   float t = dht.readTemperature();
36   // считываем температуру в градусах Фаренгейта:
37   float f = dht.readTemperature(true);
38 
39   // проверяем, корректны ли данные, и если нет,
40   // то выходим и пробуем снова:
41   if (isnan(h) || isnan(t) || isnan(f)) {
42     display.clearDisplay();  //  очищаем дисплей
43     display.setTextColor(WHITE);  //  задаем цвет 
44     display.setTextSize(1);  //  задаем шрифт
45     display.setCursor(5,);  //  задаем координаты курсора
46     display.print("Failed to read from DHT sensor!");
47     //  "Не удалось прочесть данные с датчика DHT!"
48     return;
49   }
50   display.clearDisplay();
51   display.setTextColor(WHITE);
52   display.setTextSize(1);
53   display.setCursor(,);
54   display.print("Humidity: ");  //  "Влажность: "
55   display.print(h);
56   display.print(" %\t");
57   display.setCursor(,10);
58   display.print("Temperature: ");  //  "Температура: "
59   display.print(t);
60   display.print(" C"); 
61   display.setCursor(,20);
62   display.print("Temperature: ");  //  "Температура: " 
63   display.print(f);
64   display.print(" F"); 
65 }
66 void loop()
67 {
68   displayTempHumid();
69   display.display();
70 }

После загрузки кода OLED-дисплей начнет работать следующим образом:

Using Adafruit GFX

The SSD1306 displays are programmed using the Adafruit GFX graphics library. The easiest way is to use the Display Generator, but some of the more common commands include:

Displaying

With the SSD1306 you typically follow the pattern of:

Note that all of the commands below just write to the bitmap stored in RAM. The bitmap is not transferred to the display until you call . You probably want to do all of your drawing then call once, since it’s relatively slow to transfer the image to the display.

Fonts

There are a large number of available fonts. They’re bitmaps, so they’re specific to a particular size, but you can scale it 2x, 3x, … to make larger text, though it will be pixellated. You’ll probably want to minimize the number of fonts each font uses your code flash space. Larger fonts use more space.

In order to use a font you use setFont. You also need to include the font definition by including a specific header file. For example:

To set the font, you use:

To change the font scaling you use . The value of 1 is the normal size of the font, 2 is twice the size (each pixel is output as 2×2), 3 is three times the size (each pixel is output as 3×3), ….

Passing NULL or omitting the parameter to restores the default font.

Text

To draw text you position the cursor using and use or .

The command prints text at the current cursor position and moves the cursor to after the text. You can use multiple prints to print things left to right.

The command prints text at the current cursor position and moves the cursor to the beginning of the next line.

You can pass string constants, variables, and things you’d normally be able to pass to a String or Serial print command:

You can pass string constants and things that can be converted to a C string to print and println.

You can print a single character, a string constant or a char variable.

Passing an unsigned char or uint8_t treats the value as a number. By default, it prints in decimal (0-255). It can also be printed as hexadecimal (0-FF), octal (0-277), or binary (00000000-11111111).

Other types, both signed and unsigned, can also be printed as a number. If you pass an integer numeric constant it’s treated as int.

If you pass a double (or float), it’s printed as a decimal number. The second parameter is the number of decimal places to show, the default is 2.

Shapes

Draw a single pixel. With the SSD1306 you will almost always pass 1 for color (white).

The exception is when you’ve painted an area white, and then want to restore some pixels to black, then use color 0 (black).

Note that even when you’re using blue or yellow displays, you still use color 1 (white).

The display is coordinate (0, 0) at the upper left and (128, 64) or (128, 32) in the lower right corner depending on the display used.

Draw a line from (x0, y0) to (x1, y1).

Draw a rectangle (border only) or filled rectangle. You specify (x, y) of the upper-left and then the width and height.

Draw a rectangle with rounded corners. You specify (x, y) of the upper-left, the width and height, and the radius of the rounded corners.

Draw a circle with (x0, y0) in the center and radius (r).

Draw a triangle with corners (x0, y0), (x1, y1), and (x2, y2).

Bitmaps

The easiest way to convert a bitmap is to use the DisplayGenerator, above.

To draw a bitmap, you need the (x, y) of the upper-left, width and height (w, h) and the bitmap data.

Example: SSD1306Demo

Frame 1

This frame shows three things:

  • How to draw an xbm image
  • How to draw a static text which is not moved by the frame transition
  • The active/inactive frame indicators

Frame 2

Currently there are one fontface with three sizes included in the library: Arial 10, 16 and 24. Once the converter is published you will be able to convert any ttf font into the used format.

Frame 3

This frame demonstrates the text alignment. The coordinates in the frame show relative to which position the texts have been rendered.

Frame 4

This shows how to use define a maximum width after which the driver automatically wraps a word to the next line. This comes in very handy if you have longer texts to display.

Example: SSD1306Demo

Frame 1

This frame shows three things:

  • How to draw an xbm image
  • How to draw a static text which is not moved by the frame transition
  • The active/inactive frame indicators

Frame 2

Currently there are one fontface with three sizes included in the library: Arial 10, 16 and 24. Once the converter is published you will be able to convert any ttf font into the used format.

Frame 3

This frame demonstrates the text alignment. The coordinates in the frame show relative to which position the texts have been rendered.

Frame 4

This shows how to use define a maximum width after which the driver automatically wraps a word to the next line. This comes in very handy if you have longer texts to display.

Программирование

Для работы с дисплеем будем использовать библиотеку https://github.com/adafruit/Adafruit_SSD1306 Но одной её будет недостаточно: необходимо еще поставить https://github.com/adafruit/Adafruit-GFX-Library

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13

Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);
  
#define amperkot_logo_width 28
#define amperkot_logo_height 44
static const unsigned char PROGMEM amperkot_logo_bits[] = {
   0x60, 0x00, 0x60, 0x00, 0xe0, 0x00, 0x70, 0x00, 0xe0, 0x01, 0x70, 0x00,
   0xe0, 0xff, 0x7f, 0x00, 0xe0, 0xff, 0x7f, 0x00, 0xe0, 0xff, 0x7f, 0x00,
   0xe0, 0xff, 0x7f, 0x00, 0xe0, 0xff, 0x7f, 0x00, 0xe0, 0xff, 0x7f, 0x00,
   0xe0, 0xff, 0x7f, 0x00, 0xf8, 0xff, 0xff, 0x01, 0xf0, 0xff, 0xff, 0x00,
   0xf0, 0xff, 0xff, 0x00, 0xf8, 0xff, 0xff, 0x01, 0xe0, 0xff, 0x7f, 0x00,
   0xe0, 0xff, 0x7f, 0x00, 0xe0, 0xff, 0x7f, 0x00, 0xe0, 0xcf, 0xff, 0x00,
   0xf0, 0x0f, 0xff, 0x00, 0xf8, 0x07, 0xf8, 0x01, 0xf8, 0x07, 0xfc, 0x01,
   0xfc, 0x07, 0xfc, 0x03, 0xfc, 0x03, 0xfc, 0x03, 0xfe, 0x03, 0xfe, 0x07,
   0xfe, 0x03, 0xff, 0x07, 0xfe, 0x03, 0xff, 0x07, 0xfe, 0x83, 0xff, 0x07,
   0xfe, 0x81, 0xff, 0x07, 0xff, 0xc0, 0xff, 0x0f, 0xff, 0xc0, 0xff, 0x0f,
   0xff, 0xc0, 0xff, 0x0f, 0xff, 0x00, 0xff, 0x0f, 0xff, 0x01, 0xfc, 0x0f,
   0xff, 0x07, 0xf0, 0x0f, 0xff, 0xff, 0xf0, 0x0f, 0xff, 0xff, 0xf0, 0x0f,
   0xfe, 0xff, 0xf8, 0x0f, 0xfe, 0xff, 0xfc, 0x07, 0xfe, 0x7f, 0xfc, 0x07,
   0xfe, 0x7f, 0xfc, 0x07, 0xfe, 0x3f, 0xfe, 0x07, 0xf8, 0x3f, 0xff, 0x01,
   0xf8, 0x3f, 0xff, 0x01, 0x80, 0x1f, 0x1f, 0x00 };

void setup()
{                
    display.begin(SSD1306_SWITCHCAPVCC);

    display.drawXBitmap(128 / 2 - amperkot_logo_width / 2, 0, amperkot_logo_bits, amperkot_logo_width, amperkot_logo_height, 1);
    display.display();
  
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(18,50);
  
    display.write(65);
    display.write(109);
    display.write(112);
    display.write(101);
    display.write(114);
    display.write(107);
    display.write(111);
    display.write(116);
  
    display.display();
}


void loop()
{
  
}

Именно этот код рисует на экране логотип и надпись «Amperkot» под ней. Давайте теперь разберемся, что к чему.

Логотип содержится в массиве amperkot_logo_bits и пока не совсем понятно, как этот набор невнятной информации может на экране приобретать смысл в виде готового изображения, а самое главное, как можно загружать свои собственные изображения. Обо всем по порядку.

Компьютерное изображение это ничто иное как массив байт. На каждый пиксель изображения приходится один байт информации, который содержит в себе значение цвета этого пикселя.

Чем больше разрешение изображения, тем больше байт требуется, чтобы описать каждый из пикселей. Очевидно, что слишком большое изображение будет весить очень много, поэтому были придуманы различные форматы, вроде JPG, которые позволяют оптимизировать изображение и не кодировать его просто как массив байт, но сейчас не об этом, вернемся к изображению для дисплея.

Например, мы хотим отобразить на экране изображение размером 20×20 пикселей. Это значит, что наш массив с изображением будет состоять из 400 элементов. Пройдясь по каждому элементу и подсветив нужные пиксели, мы увидим на экране изображение.

Но есть одна хитрость. Дело в том, что массив у нас одномерный, а изображение двухмерное: у него есть ширина и высота. Именно для этого для каждого изображения необходимо хранить информацию о том, какого оно размера

#define amperkot_logo_width 28
#define amperkot_logo_height 44

Text operations

void drawString(int16_t x, int16_t y, String text);

// Draws a String with a maximum width at the given location.
// If the given String is wider than the specified width
// The text will be wrapped to the next line at a space or dash
void drawStringMaxWidth(int16_t x, int16_t y, int16_t maxLineWidth, String text);

// Returns the width of the const char* with the current
// font settings
uint16_t getStringWidth(const char* text, uint16_t length);

// Convencience method for the const char version
uint16_t getStringWidth(String text);

// Specifies relative to which anchor point
// the text is rendered. Available constants:
// TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER_BOTH
void setTextAlignment(OLEDDISPLAY_TEXT_ALIGNMENT textAlignment);

// Sets the current font. Available default fonts
// ArialMT_Plain_10, ArialMT_Plain_16, ArialMT_Plain_24
// Or create one with the font tool at http://oleddisplay.squix.ch
void setFont(const char* fontData);

Setting up

i2c Hardware setup is described here

Setting up for Arduino from github sources)

  • Download source from https://github.com/lexus2k/ssd1306
  • Put the sources to Arduino/libraries/ssd1306/ folder

Setting up for Arduino from Arduino IDE library manager

Install ssd1306 library (named ssd1306 by Alexey Dynda) via Arduino IDE library manager

Using with plain avr-gcc:

  • Download source from https://github.com/lexus2k/ssd1306
  • Build the library (variant 1)
    • cd ssd1306/src && make -f Makefile.avr MCU=<your_mcu>
    • Link library to your project (refer to Makefile.avr in examples folder).
  • Build demo code (variant 2)

For esp32:

  • Download source from https://github.com/lexus2k/ssd1306
  • Put downloaded sources to components/ssd1306/ folder.
  • Compile your project as described in ESP-IDF build system documentation

Advanced techniques

Multiple displays using SPI

While I previously said that I preferred to use I2C, there is one case where SPI is helpful: multiple displays. Most displays don’t have an I2C address selector, so if you want to connect multiple displays you either need multiple I2C busses, or an I2C multiplexer.

When using multiple SPI displays, D0 (SCK), D1 (MOSI), RESET, and DC can all be shared across all displays.

Each display needs a unique CS line, so you need one additional GPIO for each display you add.

One important thing: Only define the line on the first display that you call begin() on! You can see that instead of passing in the constructor it passes . This is because if you hardware reset again, the settings on display1 will be cleared and it will no longer work.

Two works well, even updating the displays every 20 milliseconds.

Using four displays is possible, however it takes about 40 milliseconds to update all four displays, so you can’t get the refresh rate of a dual display. But for relatively static displays, it works.

Also, it’s an odd use case, but if you need two (or more) displays with exactly the same content, you should use SPI. Just connect both displays with the same CS pin. Because SSD1306 SPI is unidirectional, you can connect multiple displays «in parallel» and have them show the same content. This does not work with I2C because the communication is bidirectional.

Using multiple displays as a single large display

It is possible to create a virtual display that spans across multiple physical displays.

In spanning mode, a single virtual display is mapped to multiple physical displays. This 4 display appears as if it is 512 x 64 pixels.

Pong Demo

The Pong Demo uses two SPI SSD1306 displays for the display unit.

It also uses two Xenons with BNO055 accelerometers to control the paddles. They communicate by BLE (bluetooth) to the display unit.

Making circuit boards with displays

One really important caveat: These displays have a finite lifetime. At a full brightness running all the time, they will become noticeably dimmer after about 2 years. And the displays do occasionally fail.

Because of these two factors, I’ve taken to putting a standard I2C SSD1306 in a 4-pin female socket instead of directly soldering it to my board. This makes it easy to swap the display.

However, it also makes it unstable, so that required adding some holes and a stand-off to secure the display properly.

Furthermore, there’s another annoying problem: The power pins are not standardized on I2C displays. Sometimes VCC is on the left, sometimes GND is on the left. Some sellers will show the wrong item in the picture.

I eventually decided to just include jumpers. There’s plenty of space under the display when you use a female socket. You just put the jumpers on horizontally for VCC on the left, or vertical for GND on the left. Problem solved!

The mounting hardware includes:

Quan Item Example Price
1 4-pin female header PTH $0.45
2 0.1″ jumpers
2 M2 10+3mm standoff
2 M2 nut
2 M2 5mm screw

I’ve included an Eagle CAD design block in the eagle directory in the Github repository. There’s a stray outline that I can’t figure out how to remove, so once you place the design block, just delete the outline and the design block will correctly merge with the rest of your board.

Key Features

  • Supports color, monochrome OLED displays, and VGA monitor
  • The library has modular structure, and some modules can be excluded from compilation at all to reduce flash usage.
  • Needs very little RAM (Attiny85 with Damellis package needs minimum 25 bytes of RAM to communicate with OLED)
  • Fast implementation to provide reasonable speed on slow microcontrollers
  • Supports i2c and spi interfaces:
    • i2c (software implementation, Wire library, AVR Twi, Linux i2c-dev)
    • spi (4-wire spi via Arduino SPI library, AVR Spi, AVR USI module)
  • Primitive graphics functions (lines, rectangles, pixels, bitmaps)
  • Printing text to display (using fonts of different size, you can use GLCD Font Creator to create new fonts)
  • Includes graphics engine to support double buffering on tiny microcontrollers.
  • Can be used for game development (bonus examples):
    • Arkanoid game (arkanoid in old style API and arkanoid8 in new style API)
    • Simple Lode runner game.
    • Snowflakes

The i2c pins can be changed via API functions. Please, refer to documentation. Keep in mind, that the pins, which are allowed for i2c or spi interface, depend on the hardware. The default spi SCLK and MOSI pins are defined by SPI library, and DC, RST, CES pins are configurable through API.

Общие сведения об OLED дисплеях

OLED означает “Organic Light emitting diode“, что переводится как органический светоизлучающий диод, или, более коротко – органический светодиод. OLED дисплеи для радиолюбителей изготавливаются по той же самой технологии, что и большинство современных телевизоров, но имеют гораздо меньше пикселов по сравнению с ними. Но устройства на их основе (в том числе и с использованием Arduino) смотрятся потрясающе.

В нашем проекте мы будем использовать монохромный 7-пиновый SSD1306 0.96” OLED дисплей. Причина, по которой мы выбрали данный дисплей, заключается в том, что он может работать с тремя разными протоколами связи, трехпроводный SPI (Serial Peripheral Interface — последовательный интерфейс) режим, четырехпроводный SPI режим и режим IIC. В данной статье мы рассмотрим его подключение по четырехпроводному SPI режиму как самому скоростному из приведенных.

Контакты дисплея и выполняемые ими функции описаны в следующей таблице.

Номер контакта Название контакта Альтернативное название контакта Назначение контакта
1 Gnd Ground земля
2 Vdd Vcc, 5V напряжение питания (в диапазоне 3-5 В)
3 SCK D0, SCL, CLK контакт синхронизации (clock pin). Применяется в интерфейсах I2C и SPI
4 SDA D1, MOSI контакт данных. Применяется в интерфейсах I2C и SPI
5 RES RST, RESET контакт сброса модуля. Применяется в интерфейсе SPI
6 DC A0 контакт команд (Data Command pin). Применяется в интерфейсе SPI
7 CS Chip Select (выбор чипа) используется когда несколько устройств взаимодействуют по интерфейсу SPI

Сообществом Arduino разработано достаточно много библиотек для работы с подобными дисплеями. Мы выбрали из них библиотеку Adafruit_SSD1306 как весьма простую и в то же время содержащую достаточно много полезных функций. Но если ваш проект имеет жесткие ограничения по памяти/скорости, то тогда вам лучше использовать библиотеку U8g поскольку она работает быстрее и занимает меньше места в памяти.

◆ SSD1306_COMPAT_SEND_PIXELS_RGB8_CMDS

#define SSD1306_COMPAT_SEND_PIXELS_RGB8_CMDS ( )

Value:

extern uint16_t ssd1306_color; \
static void send_pixels_compat(uint8_t data) \
{ \
for (uint8_t i=8; i>0; i—) \
{ \
if ( data & 0x01 ) \
{ \
ssd1306_intf.send( (uint8_t)ssd1306_color ); \
} \
else \
{ \
ssd1306_intf.send( 0B00000000 ); \
} \
data >>= 1; \
} \
} \
static void send_pixels_buffer_compat(const uint8_t *buffer, uint16_t len) \
{ \
while(len—) \
{ \
send_pixels_compat(*buffer); \
buffer++; \
} \
}

Macro generates 2 static functions, applicable for many oled controllers in 8-bit RGB mode: send_pixels_compat(), send_pixels_buffer_compat(). These functions are to be used when working in ssd1306 compatible mode.

Definition at line of file lcd_common.h.