最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arduino - communication between Java and esp32 via wifi - Stack Overflow

programmeradmin1浏览0评论

I am trying to send and receive message programmatically between esp32 and Java using a wifi connection. I was able to send and receive message to esp32 using my internet browser using this address: http://192.168.4.1/ - to receive message and http://192.168.4.1/get?data=hello world - to send message to esp32 (hello world).

I am using this code in arduino:

#include <WiFi.h>
#include <WebServer.h>

WebServer server(80);

void handleRoot() {
  server.send(200, "text/plain", "Ready");
}

void handleGet() {
  if (server.hasArg("data")) {
    String data = server.arg("data");
    Serial.println("Data: " + data);
  }
  server.send(200, "text/plain", "Data Received");
}

void handlePost() {
  server.send(200, "text/plain", "Processing Data");
}

void handleUpload() {
  HTTPUpload& upload = server.upload();
  if (upload.status == UPLOAD_FILE_START) {
    Serial.println("Receiving data:");
  } else if (upload.status == UPLOAD_FILE_WRITE) {
    Serial.write(upload.buf, upload.currentSize);
  } else if (upload.status == UPLOAD_FILE_END) {
    server.send(200, "text/plain", "Data: ");
  }
}

void setup() {
  Serial.begin(115200);
  WiFi.softAP("ESP32");
  server.on("/", handleRoot);
  server.on("/get", HTTP_GET, handleGet);
  server.on("/post", HTTP_POST, handlePost, handleUpload);
  server.begin();
}

void loop() {
  server.handleClient();
}

in java i was able to get a message from esp32 using this code:

     public static void main(String[] args) {
         try {
            get("http://192.168.4.1/");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }

 public static void get(String uri) throws Exception {
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                  .uri(URI.create(uri))
                  .build();

            HttpResponse<String> response =
                  client.send(request, BodyHandlers.ofString());

            System.out.println(response.body());
        }

I tried different things to send a message from Java to esp32 but they didn't work. Can someone help please?

发布评论

评论列表(0)

  1. 暂无评论