ESP32でLCDに文字を出力する。
目標
ESP32を用いてLCDに任意の文字を出力する。
環境
- macOS 10.15.2 Catalina
- Arduino IDE 1.8.10
- ESP32 DEVKIT V1 (ESP-WROOM-32)
- LCD (IIC/I2C/TWI 1602 Serial LCD Module)
配線
下の画像のように配線する。
プログラム
Arduino IDEでESP32を使用する設定をまだしていない場合は下の過去の記事を参考に設定する。
ライブラリを用意する
https://github.com/johnrickman/LiquidCrystal_I2C/archive/1.1.3.zip
I2Cのアドレスを確認する
下のプログラムをESP32に書き込みシリアルモニタを確認する。
#include <Wire.h> void setup() { Wire.begin(); Serial.begin(115200); while (!Serial); // Leonardo: wait for serial monitor Serial.println("\nI2C Scanner"); } void loop() { byte error, address; int nDevices; Serial.println("Scanning..."); nDevices = 0; for(address = 1; address < 127; address++ ) { // The i2c_scanner uses the return value of // the Write.endTransmisstion to see if // a device did acknowledge to the address. Wire.beginTransmission(address); error = Wire.endTransmission(); if (error == 0) { Serial.print("I2C device found at address 0x"); if (address<16) Serial.print("0"); Serial.print(address,HEX); Serial.println(" !"); nDevices++; } else if (error==4) { Serial.print("Unknown error at address 0x"); if (address<16) Serial.print("0"); Serial.println(address,HEX); } } if (nDevices == 0) Serial.println("No I2C devices found\n"); else Serial.println("done\n"); delay(5000); // wait 5 seconds for next scan }
プログラムを書く
下のプログラムをArduino IDEを用いてESP32に書き込むと
Hello,world! (ハートの形)
がLCDに表示される。
#include <LiquidCrystal_I2C.h> #define lcdAddress 0x3F //上で確認したアドレスを書く。 #define lcdColumns 16 //使用するLCDの列数を書く #define lcdRows 2 //使用するLCDの行数を書く LiquidCrystal_I2C lcd(lcdAddress, lcdColumns, lcdRows); int column, row; byte heart[8] = { 0b00000, 0b01010, 0b11111, 0b11111, 0b11111, 0b01110, 0b00100, 0b00000 }; void setup() { lcd.init();//LCDを初期化する lcd.backlight();//LCDのバックライトをオンにする lcd.createChar(0, heart);//上で宣言した文字を設定する } void loop() { column = 2; row = 0; lcd.setCursor(column, row); //カーソールを任意の場所に変更する lcd.print("Hello,world!");//任意の文字列を出力する column = 7; row = 1; lcd.setCursor(column, row); //カーソールを任意の場所に変更する lcd.write(0);//setupで設定した文字を出力する }