簡體   English   中英

嘗試通過 WiFi 將數據從 Android 應用程序發送到 ESP32 - 數據似乎未發送

[英]Trying to send data over WiFi to an ESP32 from an Android app - Data seemingly not sending

我對 ESP32(arduino IDE)上的 C++ 比我對 Android 應用程序的 Java 更滿意,所以我認為問題在於 Java 代碼實際上沒有發送任何數據。

這是預期的行為:

  1. ESP32 作為接入點啟動(它們都有 WiFi 芯片,因此可以這樣編程)
  2. Android 設備進入網絡設置並連接到 ESP32 熱點/接入點
  3. Android 設備返回應用程序並按下按鈕發送一串數據
  4. ESP32 正在偵聽以 '\n' 結尾的任何數據,然后使板載 LED 閃爍。 對於我的 Java 代碼,發送代碼使用 PrintWriter class 和 println 方法(意味着發送的任何數據都將以 '\n' 作為后綴

我今天制作了 APK 並將其安裝在 android 手機上,啟動了 ESP32 並檢查了串行監視器以確保 IP 與我在 Java 代碼中指定的相同,端口 (80) 也相同。

我從我的 Android 設備和 go 連接到 ESP32 回到應用程序,按下按鈕,沒有任何反應。 ESP32 的 Arduino IDE 中的串行監視器也沒有顯示任何內容(它應該打印接收到的數據)。

所以我將粘貼 Java 代碼,我認為這可能是錯誤所在。 如您所見,我正在嘗試將“Hello ESP32”作為字符串發送。

package com.benledmatrix.esp32controloverwifi;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set up a button to send data when clicked
        Button sendButton = findViewById(R.id.send_button);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendData();
            }
        });
    }

    private void sendData() {
        // Set up a thread to send the data in the background
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Connect to the ESP32's IP address and port
                    Socket socket = new Socket("192.168.4.1", 80);
                    PrintWriter out = new PrintWriter(socket.getOutputStream());

                    // Send the data
                    out.println("Hello, ESP32!");
                    out.flush();

                    // Close the connection
                    out.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

這是 ESP32 上的 Arduino C++ 代碼

#include <WiFi.h>

const char* ssid = "ESP32 HotSpot";
const char* password = "password";

WiFiServer server(80);  // Create a server on port 80

void setup() {

  Serial.begin(115200);
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);
  Serial.print("IP address: ");
  Serial.println(WiFi.softAPIP());
  server.begin();      // Start the server
  pinMode(2, OUTPUT);  // Set onboard LED as an output
}

void loop() {
  WiFiClient client = server.available();  // Listen for incoming clients

  if (client) {                                  // If a client connects
    String data = client.readStringUntil('\n');  // Read the data from the client
    Serial.println(data);                        // Print the data to the serial monitor

    if (data == "Hello, ESP32!") {  // If the data is "Hello, ESP32!"
      // Flash the onboard LED twice
      for (int i = 0; i < 2; i++) {
        digitalWrite(2, HIGH);
        delay(200);
        digitalWrite(2, LOW);
        delay(200);
      }
    } else {
      // Flash the onboard LED once
      digitalWrite(2, HIGH);
      delay(200);
      digitalWrite(2, LOW);
      delay(200);
    }

    client.stop();  // Disconnect the client
  }
}

以防萬一我是一個完整的 div 這里是按鈕的 XML 代碼:D 你永遠不知道

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/send_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:background="#008080"
            android:text="Send Data" />

    </RelativeLayout>


</androidx.constraintlayout.widget.ConstraintLayout>

對於這樣的轉儲感到抱歉,但由於我對 Android 沒有那么多經驗,所以我認為最好將所有內容都放在那里。 它編譯得很好,沒有發現錯誤,但只是沒有執行所需的操作。

如果有人有想法,我會嘗試。 非常感謝本

經過大量研究,我有一個功能代碼,當按下 Android 應用程序上的“發送數據”按鈕時,它會閃爍 ESP32 的板載 LED 兩次,表示它已收到字符串。 很高興!

最后的原因是我沒有任何使用 inte.net 的權限。 我使用了 USB 調試並輸入了一些 log.d,它告訴我我沒有使用 inte.net 的權限,所以輸入該權限和一些 toast 消息來檢查權限修復它。

C++ 和 XML 代碼保持不變,但在 Android XML 清單文件中我添加了:

<uses-permission android:name="android.permission.INTERNET" />

而最終的Java代碼如下:

package com.benledmatrix.esp32controloverwifi;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;


public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Check for Internet permission for SDK 23 or higher
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.INTERNET)) {

                //rationale to display why the permission is needed
                Toast.makeText(this, "The app needs access to the Internet to send data to the ESP32", Toast.LENGTH_SHORT).show();
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PERMISSION_REQUEST_CODE);
        }

        // Set up a button to send data when clicked
        Button sendButton = findViewById(R.id.send_button);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendData();
            }
        });
    }

    //Check for result of permissions and feedback accordingly
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted, you can perform the network operation here
                Log.d("Permission", "Granted");
            } else {
                // Permission denied, show a message to the user
                Log.d("Permission", "Denied");
                Toast.makeText(this, "Permission denied, you cannot perform network operations", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void sendData() {
        // Set up a thread to send the data in the background
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Connect to the ESP32's IP address and port
                    Log.d("Sending Data", "Button Pressed, connecting to ESP32.....");
                    Socket socket = new Socket("192.168.4.1", 80);
                    PrintWriter out = new PrintWriter(socket.getOutputStream());

                    // Send the data
                    out.println("Hello, ESP32!");
                    out.flush();
                    Log.d("Sending Data", "Data Sent!");

                    // Close the connection
                    out.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("Sending Data", "Error Sending Data: "+e.getMessage());
                }
            }
        }).start();
    }
}

當然,任何關於我可能不需要的事情的進一步建議或我可以做出的改進都會很棒。

非常感謝本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM