1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ESP32 全自動ブロードキャストにしてみた

1
Last updated at Posted at 2018-12-13

序章

このあいだ普通にUDP通信したけど脳死でUDPしたくてブロードキャストやってみました。
完全に備忘録かつ脳死プログラムなので、大したものじゃないです。
見た人の1mm程度の参考にでもなればいいなと。

こけたとこ

自分プログラミング初心者なのでデータ型で躓いてしまいました。
・IPAddress
っていう型があるんですけどこれがよくわからなかったのでまとめます。
結果を言うと、このデータ型は配列っぽいのでした。
実はこの配列、IPaddressを格納するのに優れています。
例えば 「192.168.222.333」 というIPaddressがあり

 IPAddress ip = WiFi.localIP();

このように入手したとします。この時、ipには以下のようにアドレスが格納されています。

配列 ip[0] ip[1] ip[2] ip[3]
格納されてる値 192 168 222 333

てな感じでdot(.)区切りになって格納されてる便利な型です。

ブロードキャストの手引き

手順
(1から3までStringで処理してます。)
1.自分のwlanのipaddressを入手する。
2.自分のipaddressを分割する→最後のまとまり(ip[3])以外を足し算。
3.ip[3]があった場所に'255'を付け足す。
4.charに直す。

やってみよう

1.このipが上で説明したデータ型。

IPAddress ip = WiFi.localIP();

2.この辺脳筋です( TДT)ゴメンヨー

String a,b,c,d;
a = ip[0];
b = ip[1];
c = ip[2];

3.またまた脳筋...(上の続きです)

d = a + '.' b  + '.'+ c + '.' + "255";

4.char型に直す

int d_length = d.length()+1;
char IP[d_length];
d.toCharArray(IP,d_length);

5.脳死でUDPにドーーンできるよ( ´∀`)bグッ!

wifiUdp.beginPacket(IP,9000);
wifiUdp.write('1');
wifiUdp.endPacket();  

完成形態

以下のコードは自己責任です。
責任の一切は負いかねます。

broad.ino
# include <WiFi.h>
# include <WiFiUDP.h>


const char* ssid     = "****";
const char* password = "****";
static WiFiUDP wifiUdp; 

void setup()
{
    Serial.begin(115200);
    delay(10);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
}


IPAddress ip;
String a,b,c,d;
void loop()
{
    // print your subnet mask:
    ip = WiFi.localIP();
    a = ip[0];
    b = ip[1];
    c = ip[2];
    d = a + '.' + b + '.' + c + '.' + "255";
    Serial.println(d);
    int d_length = d.length()+1;
    char IP[d_length];
    d.toCharArray(IP,d_length);
    wifiUdp.beginPacket(IP,9000); //9000は任意のポート番号
    wifiUdp.write('O');
    wifiUdp.endPacket();  

  delay(3000);
    Serial.println("END");
    delay(5000);
}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?