ESP32同士によるwifiUDP通信
こんにちは。
久しぶりの投稿となりました。
今回はESP32を2つ使って、wifiUDP通信でデータを送ってみました。
自分の備忘録的な意味合いのほうが大きいため、あまり参考にはならないかもしれませんが、よければご覧ください。
今回使ったESP32です。
どちらも秋月電子で売ってるdevkitですが、写真右側のは新しいほうのESP32-WROOM-32Dですね。まぁ何が違うのかさっぱりわからないんですが...
左側のほうをアクセスポイント(サーバ)とし、右側のほう(クライアント)でアクセスするようにしました。
今回参考にさせて頂いたサイト様は以下の2つです。
サーバ側
【ESP32】ESP32とスマホを接続してWiFiUDP通信する方法 - ソースに絡まるエスカルゴ
クライアント側
ESP32でUDP通信やってみた(ESP32インストール手順解説あり) - Qiita
まず、サーバ側(文字データ受け取り側)です。
#include <WiFi.h> #include <WiFiUdp.h> const char ssid[] = "ESP32_wifi"; // SSID const char pass[] = "esp32pass"; // password const int localPort = 10000; // ポート番号 const IPAddress ip(192, 168, 4, 1); // IPアドレス(ゲートウェイも兼ねる) const IPAddress subnet(255, 255, 255, 0); // サブネットマスク WiFiUDP udp; void setup() { Serial.begin(115200); WiFi.softAP(ssid, pass); // SSIDとパスの設定 delay(100); // 追記:このdelayを入れないと失敗する場合がある WiFi.softAPConfig(ip, ip, subnet); // IPアドレス、ゲートウェイ、サブネットマスクの設定 Serial.print("AP IP address: "); IPAddress myIP = WiFi.softAPIP(); Serial.println(myIP); Serial.println("Starting UDP"); udp.begin(localPort); // UDP通信の開始(引数はポート番号) Serial.print("Local port: "); Serial.println(localPort); } void loop() { if (udp.parsePacket()) { char i = udp.read(); //ceramie追記 askiiから文字列へ Serial.println(i); // UDP通信で来た値を表示 } }
ほとんどそのままですが、そのままでは10進数のASKIIコードで表示されてしまうため、char型変数に一回代入してます。
次に、クライアント側(文字データ送信側)です。
#include <WiFi.h> #include <WiFiUdp.h> const char ssid[] = "ESP32_wifi"; // SSID const char pass[] = "esp32pass"; // password static WiFiUDP wifiUdp; static const char *kRemoteIpadr = "192.168.4.1"; //送信先のIPアドレス static const int kRmoteUdpPort = 10000; //送信先のポート static void WiFi_setup() { static const int kLocalPort = 5000; //自身のポート WiFi.begin(ssid, pass); while( WiFi.status() != WL_CONNECTED) { delay(500); } wifiUdp.begin(kLocalPort); } static void Serial_setup() { Serial.begin(115200); Serial.println(""); // to separate line } void setup() { Serial_setup(); WiFi_setup(); } void loop() { wifiUdp.beginPacket(kRemoteIpadr, kRmoteUdpPort); wifiUdp.write('a'); //10進数のaskiiで送信される wifiUdp.endPacket(); delay(3000); }
こちらはほとんど変えていません。
SSIDとパスワードとIPアドレスとポートを入力しただけです。
一応、この2つのコードをそのまま書き込めば動くはずです。
クライアント側のloopの中にあるwifiUdp.write('a');でaを送信してます。
現状では1文字しか送れてません。
サーバ側をシリアルモニタで確認して、aが3秒経過ごとに送られてきたら成功です。
ESP32はサーバ側→クライアント側の順でリセットして使ってください。
それでは!
Hiletgoの2.8インチ TFT液晶で画像を表示してみた
こんにちは。
今回はSDカードに保存したBMP画像をArduinoNanoで読み込み、TFT液晶に表示させてみました。
Adafruit ILI9341のスケッチ例の"spitftbitmap"を自分が使いやすいように改造する形で行いました。
このTFT液晶モジュールはSDカードスロットが備わっているので、それを使用します。
配線は、
TFT_DC → 9
TFT_CS → 9
SD_CS → 4
TFT_MOSI → 11
TFT_MISO → 12
TFT_SCK → 13
SD_MOSI → 11
SD_MISO → 12
SD_SCK → 13
で接続しました。
ただし、このLCDは3.3V駆動なので、レベルコンバータを間に挟む必要があります。
- 出版社/メーカー: サンハヤト
- メディア: Tools & Hardware
- この商品を含むブログを見る
で、改変したソースコードがこちらです。
gochiusa.bmpをSDカードから読み込み、表示させるようになっています。
/*************************************************** This is our Bitmap drawing example for the Adafruit ILI9341 Breakout and Shield ----> http://www.adafruit.com/products/1651 Check out the links above for our tutorials and wiring diagrams These displays use SPI to communicate, 4 or 5 pins are required to interface (RST is optional) Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. MIT license, all text above must be included in any redistribution ****************************************************/ #include <Adafruit_GFX.h> // Core graphics library #include "Adafruit_ILI9341.h" // Hardware-specific library #include <SPI.h> #include <SD.h> // TFT display and SD card will share the hardware SPI interface. // Hardware SPI pins are specific to the Arduino board type and // cannot be remapped to alternate pins. For Arduino Uno, // Duemilanove, etc., pin 11 = MOSI, pin 12 = MISO, pin 13 = SCK. #define TFT_DC 9 #define TFT_CS 10 //TFT_RSTはつながなくてよいが、GNDに落としといたほうがいいかもしれない Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC); #define SD_CS 4 void setup(void) { Serial.begin(9600); tft.begin(); yield(); Serial.print("Initializing SD card..."); if (!SD.begin(SD_CS)) { Serial.println("failed!"); } Serial.println("OK!"); } //BMPファイルのファイル名は半角英数で8文字以下 void loop() { uint8_t r = 3; //回転角度 r=0~3 tft.setRotation(r); tft.fillScreen(ILI9341_BLUE); bmpDraw("gochiusa.bmp",0,0); //表示開始座標 /*for(uint8_t r=0; r<4; r++) { tft.setRotation(r); tft.fillScreen(ILI9341_BLUE); for(int8_t i=-2; i<1; i++) { bmpDraw("gochiusa.bmp", (tft.width() / 2) + (i * 120), (tft.height() / 2) + (i * 160)); } }*/ } // This function opens a Windows Bitmap (BMP) file and // displays it at the given coordinates. It's sped up // by reading many pixels worth of data at a time // (rather than pixel by pixel). Increasing the buffer // size takes more of the Arduino's precious RAM but // makes loading a little faster. 20 pixels seems a // good balance. #define BUFFPIXEL 20 void bmpDraw(char *filename, int16_t x, int16_t y) { File bmpFile; int bmpWidth, bmpHeight; // W+H in pixels uint8_t bmpDepth; // Bit depth (currently must be 24) uint32_t bmpImageoffset; // Start of image data in file uint32_t rowSize; // Not always = bmpWidth; may have padding uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer boolean goodBmp = false; // Set to true on valid header parse boolean flip = true; // BMP is stored bottom-to-top int w, h, row, col, x2, y2, bx1, by1; uint8_t r, g, b; uint32_t pos = 0, startTime = millis(); if((x >= tft.width()) || (y >= tft.height())) return; Serial.println(); Serial.print(F("Loading image '")); Serial.print(filename); Serial.println('\''); // Open requested file on SD card if ((bmpFile = SD.open(filename)) == NULL) { Serial.print(F("File not found")); return; } // Parse BMP header if(read16(bmpFile) == 0x4D42) { // BMP signature Serial.print(F("File size: ")); Serial.println(read32(bmpFile)); (void)read32(bmpFile); // Read & ignore creator bytes bmpImageoffset = read32(bmpFile); // Start of image data Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC); // Read DIB header Serial.print(F("Header size: ")); Serial.println(read32(bmpFile)); bmpWidth = read32(bmpFile); bmpHeight = read32(bmpFile); if(read16(bmpFile) == 1) { // # planes -- must be '1' bmpDepth = read16(bmpFile); // bits per pixel Serial.print(F("Bit Depth: ")); Serial.println(bmpDepth); if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed goodBmp = true; // Supported BMP format -- proceed! Serial.print(F("Image size: ")); Serial.print(bmpWidth); Serial.print('x'); Serial.println(bmpHeight); // BMP rows are padded (if needed) to 4-byte boundary rowSize = (bmpWidth * 3 + 3) & ~3; // If bmpHeight is negative, image is in top-down order. // This is not canon but has been observed in the wild. if(bmpHeight < 0) { bmpHeight = -bmpHeight; flip = false; } // Crop area to be loaded x2 = x + bmpWidth - 1; // Lower-right corner y2 = y + bmpHeight - 1; if((x2 >= 0) && (y2 >= 0)) { // On screen? w = bmpWidth; // Width/height of section to load/display h = bmpHeight; bx1 = by1 = 0; // UL coordinate in BMP file if(x < 0) { // Clip left bx1 = -x; x = 0; w = x2 + 1; } if(y < 0) { // Clip top by1 = -y; y = 0; h = y2 + 1; } if(x2 >= tft.width()) w = tft.width() - x; // Clip right if(y2 >= tft.height()) h = tft.height() - y; // Clip bottom // Set TFT address window to clipped image bounds tft.startWrite(); // Requires start/end transaction now tft.setAddrWindow(x, y, w, h); for (row=0; row<h; row++) { // For each scanline... // Seek to start of scan line. It might seem labor- // intensive to be doing this on every line, but this // method covers a lot of gritty details like cropping // and scanline padding. Also, the seek only takes // place if the file position actually needs to change // (avoids a lot of cluster math in SD library). if(flip) // Bitmap is stored bottom-to-top order (normal BMP) pos = bmpImageoffset + (bmpHeight - 1 - (row + by1)) * rowSize; else // Bitmap is stored top-to-bottom pos = bmpImageoffset + (row + by1) * rowSize; pos += bx1 * 3; // Factor in starting column (bx1) if(bmpFile.position() != pos) { // Need seek? tft.endWrite(); // End TFT transaction bmpFile.seek(pos); buffidx = sizeof(sdbuffer); // Force buffer reload tft.startWrite(); // Start new TFT transaction } for (col=0; col<w; col++) { // For each pixel... // Time to read more pixel data? if (buffidx >= sizeof(sdbuffer)) { // Indeed tft.endWrite(); // End TFT transaction bmpFile.read(sdbuffer, sizeof(sdbuffer)); buffidx = 0; // Set index to beginning tft.startWrite(); // Start new TFT transaction } // Convert pixel from BMP to TFT format, push to display b = sdbuffer[buffidx++]; g = sdbuffer[buffidx++]; r = sdbuffer[buffidx++]; tft.writePixel(tft.color565(r,g,b)); } // end pixel } // end scanline tft.endWrite(); // End last TFT transaction } // end onscreen Serial.print(F("Loaded in ")); Serial.print(millis() - startTime); Serial.println(" ms"); } // end goodBmp } } bmpFile.close(); if(!goodBmp) Serial.println(F("BMP format not recognized.")); } // These read 16- and 32-bit types from the SD card file. // BMP data is stored little-endian, Arduino is little-endian too. // May need to reverse subscript order if porting elsewhere. uint16_t read16(File &f) { uint16_t result; ((uint8_t *)&result)[0] = f.read(); // LSB ((uint8_t *)&result)[1] = f.read(); // MSB return result; } uint32_t read32(File &f) { uint32_t result; ((uint8_t *)&result)[0] = f.read(); // LSB ((uint8_t *)&result)[1] = f.read(); ((uint8_t *)&result)[2] = f.read(); ((uint8_t *)&result)[3] = f.read(); // MSB return result; }
BMPファイルの作り方なんですが、MSペイントで画像を開き、320px × 240px に縮小し、24ビットマップで保存しました。
ただし、ファイル名は半角英数で8文字までみたいです。
実行すると...
表示されました!
ということで、BMP画像を表示することに成功しました。
拙い文章で申し訳ないです。
わからないことがあればお気軽にコメント欄までお寄せください。
HiLetgo® 2.8インチTFT LCDディスプレイを使ってみた
HiLetgo® 2.8インチ TFT LCDディスプレイを注文し、それが今日届いたので使ってみました。
HiLetgo® 2.8 "TFT LCDディスプレイ タッチパネル SPIシリアル240 * 320 ILI9341 5V / 3.3V STM32 [並行輸入品]
- 出版社/メーカー: HiLetgo
- メディア:
- この商品を含むブログを見る
ArduinoUnoと同じくらいの大きさですね。
以前、Aitendo製のLCDディスプレイを買ってみたんですが、使い方も何もわからず...
LCDディスプレイを使って何か作る予定はないんですが、使えるようにはしておきたかったんで代わりにこれを購入しました。
今回は、Amazonで詳しくレビューしてくださってる方がいらっしゃったのでそちらを参考にさせて頂きました。
この方はESP32を使用されたようですが、私は今回はArduinoNano互換品を使用しました。
ということで、Adafruit ILI9341ライブラリとAdafruit GFXライブラリを導入し、スケッチ例のAdafruit ILI9341の中のgraphicstestを動かしてみます。
まず、25~28行のこの部分に修正を加えます。
// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// If using the breakout, change pins as desired
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);
上のAda...をコメントアウトし、下のAda...のコメントアウトを外し、以下のようにします。
// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// If using the breakout, change pins as desired
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);
また、これに伴い、#defineでどのピンを割り当てるかを記述します。
すでに22~23行でTFT_DCとTFT_CSは定義されていたので、
#define TFT_DC 9
#define TFT_CS 10
#define TFT_MOSI 11
#define TFT_CLK 13
#define TFT_RST 2
#define TFT_MISO 12
上のように青字の部分を付け加えました。
次に、配線していくわけですが、このLCD、3.3V動作のため、5VであるArduinoと直接配線するわけにはいきません。
そのため、ロジックレベル変換モジュールをArduinoとLCDのあいだにかませました。
配線を済ませ、プログラムを書き込むと...
動きました!
思っていたよりだいぶ綺麗でビックリしました。
これで工作の幅も広がりそうですね。
それではまた(^O^)/
ブログ初めてみました
はじめまして、ceramieと申します。
この度、ブログを始めることにしました。
私は機械系エンジニアですが、趣味として電子工作をやっておりまして、現在はesp32を触ってみたり、LCDモジュールを触ってみたりと、幅広く手を出している状況です。
あまり参考にはならないかもしれませんが、よろしくお願いします(^O^)/