スーパーファミコン コントローラーの無線化プロジェクト:ESP WiFi UDP

(コントローラーの無線化にトライというだけでまだ出来ていませんのであしからず)

消費電力の観点からBLEがよさそうではあるが、WiFiのUDPでの2つのESPの間で通信をしてみる。基礎的な動作の確認。

サーバー側:

#include <ESP8266WiFi.h> // WiFi
#include <WiFiUDP.h>     // UDP
// SSIDとパスワード
const char *ssid = "esp8266";
const char *password = "12345678";
//create UDP instance
static WiFiUDP udp;

#define LOCAL_PORT  5000  // port number for local
#define REMOTE_PORT 5000  // port number for remote

IPAddress localIP; //local IP address
IPAddress remoteIP;  // remote address

void setup() {
  Serial.begin(115200);
  delay(100);
 
  // AP setting
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);
   delay(100);
  localIP = WiFi.softAPIP();
  Serial.println();
  Serial.print("AP IP address: ");Serial.println(localIP);
 
  // start udp
  udp.begin(LOCAL_PORT);
   delay(100);
}
void loop() {
  char packetBuffer[256];
 
  int packetSize = udp.parsePacket();
  if (packetSize) {
    int len = udp.read(packetBuffer, packetSize);
    if (len > 0) packetBuffer[len] = '\0';
   
    // gettin remote IP address
    remoteIP = udp.remoteIP();
   
    Serial.print(remoteIP);
    Serial.print(" / ");
    Serial.println(packetBuffer);
   
    udp.beginPacket(remoteIP, REMOTE_PORT);
    udp.write(packetBuffer);
    //udp.write(1);
    udp.endPacket();
  }
}

クライアント側

#include <ESP8266WiFi.h> // WiFih>
#include <WiFiUdp.h>

const char ssid[] = "esp8266"; // SSID
const char pass[] = "12345678";  // password

static WiFiUDP wifiUdp; //create UDP instance

// IP address to send UDP data to.
// it can be ip address of the server or
static const char *kRemoteIpadr = "192.168.4.1";  
static const int kRmoteUdpPort = 5000;

void setup() {
  Serial.begin(115200);
  Serial.println(""); // to separate line  
  static const int kLocalPort = 5000;  //local port
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass); //Connect to the WiFi network
  while( WiFi.status() != WL_CONNECTED) {
    delay(500);  
  }  
  Serial.print("IP address:");
  Serial.println(WiFi.localIP());
  wifiUdp.begin(kLocalPort);
}

void loop()
{
//data will be sent to server
  uint8_t buffer[50] = "hello world";
  //send hello world to server
  wifiUdp.beginPacket(kRemoteIpadr, kRmoteUdpPort);
  wifiUdp.write(buffer, 11);
  wifiUdp.endPacket();
  memset(buffer, 0, 50);
  //processing incoming packet, must be called before reading the buffer
  wifiUdp.parsePacket();
  //receive response from server, it will be HELLO WORLD
  if(wifiUdp.read(buffer, 50) > 0){
    Serial.print("Server to client: ");
    Serial.println((char *)buffer);
  }
  //Wait for 1 second
  delay(1000);
}

ESP32-Arduino-Case-37/NO.19 Demo 19 How to use UDPIP with Arduino ESP32/源码/Arduino ESP32 UDP client.ino at master · LilyGO/ESP32-Arduino-Case-37 · GitHub

とかを参考にクライアント側を作っていたが、ちゃんと勉強してなかったので結構ハマったのが、

WiFi.mode(WIFI_STA);

この1行を入れる事(笑)。サーバー側がAPモードで動いていて、そりゃSTAモードでクライアントは動かさないと・・・。





コメント

このブログの人気の投稿

Attiny85とAQM0802A(LCD)のI2C接続

Attiny85 FuseRest