为了账号安全,请及时绑定邮箱和手机立即绑定

通过蓝牙将超声波传感器的数据从 Arduino 发送到 Android

通过蓝牙将超声波传感器的数据从 Arduino 发送到 Android

杨魅力 2023-11-01 22:32:36
我正在写我的文凭论文,但在使用蓝牙与 Arduino -> Android 进行通信时遇到问题。这是我的应用程序: 我想要显示到障碍物的距离的活动在 TextView 中,我想将来自 Arduino 的数据与距离放在一起,我需要想法,我找不到东西,如何将数据从不同的传感器发送到不同的视图(例如前、后保险杠、左和右)。这里有arduino代码: #include <SoftwareSerial.h>// Mid-back sensor#define trigPinLeft 11 #define echoPinLeft 10// Right-back sensor (looking from back)#define trigPinRight 7#define echoPinRight 6SoftwareSerial btSerial = SoftwareSerial(0,1);void setup() {  // put your setup code here, to run once:  Serial.begin(115200);  btSerial.begin(115200);  // Mid-back sensor  pinMode(trigPinLeft, OUTPUT);  pinMode(echoPinLeft, INPUT);  // Right-back sensor   pinMode(trigPinRight, OUTPUT);  pinMode(echoPinRight, INPUT);}void loop() {  // put your main code here, to run repeatedly:  long durationLeft, distanceLeft;  digitalWrite(trigPinLeft, LOW);  delayMicroseconds(5);  digitalWrite(trigPinLeft, HIGH);  delayMicroseconds(5);  digitalWrite(trigPinLeft, LOW);  durationLeft = pulseIn(echoPinLeft, HIGH);  distanceLeft = (durationLeft *0.034 / 2);  if (distanceLeft>=400 || distanceLeft<=18){    Serial.println("Out of range");     btSerial.println("Out of range");  }  else{    Serial.print("BACK LEFT: ");    Serial.print(distanceLeft);    Serial.println(" cm");    btSerial.println(distanceLeft + "cm");  }  //delayMicroseconds(1);  long durationRight, distanceRight;  digitalWrite(trigPinRight, LOW);  delayMicroseconds(5);  digitalWrite(trigPinRight, HIGH);  delayMicroseconds(10);  digitalWrite(trigPinRight, LOW);  durationRight = pulseIn(echoPinRight, HIGH);  distanceRight = (durationRight *0.034 / 2);  if (distanceRight>=400 || distanceRight<=18){    Serial.println("Out of range");     btSerial.println("Out of range");  }  else{    Serial.print("BACK RIGHT: ");    Serial.print(distanceRight);    Serial.println(" cm");    btSerial.println(distanceRight + "cm");  }  delay(10000);}我编译并运行了应用程序,但在看到闪屏后,我的手机出现白屏和延迟。我在 Android-Studio 中没有错误。感谢帮助。
查看完整描述

1 回答

?
跃然一笑

TA贡献1826条经验 获得超6个赞

您显然似乎有线程问题。

在您的代码中HomeActivity,您已经注释掉了允许在手机上打开蓝牙服务器的代码,以便您的 Arduino 设备可以连接到它,并在UUIDRFCOM 模式下提供相关和其他相关参数。

然而,该代码与网络相关并且是阻塞的,因此永远不应该在应用程序UI 线程上执行,该线程负责处理所有 UI 任务,例如显示视图、监视用户交互(触摸事件)等。

这就是您的手机显示白屏且有延迟的原因。

因此,您绝对应该在单独的线程上执行蓝牙逻辑。

我建议使用以下类来处理所有与蓝牙相关的逻辑。这非常简单。

public class BluetoothHandler {


    private final Handler handler;

    private final BluetoothAdapter bluetoothAdapter;


    @Nullable

    private BluetoothServerSocket serverSocket;

    private BluetoothSocket bluetoothSocket;



    public BluetoothHandler(Context context) {

        final HandlerThread ht = new HandlerThread("Bluetooth Handler Thread", Thread.NORM_PRIORITY);

        ht.start(); // starting thread


        this.handler = new Handler(ht.getLooper());


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {

            this.bluetoothAdapter = ((BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();

        } else {

            this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        }

    }



    public void startBluetoothServer() {

        // execute code in our background worker thread

        this.handler.post(new Runnable() {

            @Override

            public void run() {

                try {

                    serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("name", "your UUID");

                    bluetoothSocket = serverSocket.accept(); // will wait as long as possible (no timeout) so there is blocking


                    // do your logic to retrieve in and out put streams to read / write data from / to your Arduino device


                }  catch (IOException ioe) {


                }

            } 

        });

    }



    @AnyThread

    public void writeData(byte[] data) {

        // remember, all network operation are to be executed in a background thread

        this.handler.post(new Runnable() {

            @Override

            public void run() {

                // write data in output stream     

            }

        });

    }



    @AnyThread

    public void readData(OnDataReadCallback callback) {

        // remember, all network operation are to be executed in a background thread

        this.handler.post(new Runnable() {

            @Override

            public void run() {

                // read data and notify via callback.

            }

        });

    }



    @AnyThread // should be call from your Activity onDestroy() to clear resources and avoid memory leaks.

    public void termainte() {

       try {

           if (serverSocket != null) {

               serverSocket.close();

           }


           if (bluetoothSocket != null) {

                bluetoothSocket.close();

           }

       } catch (IOException ioe) {


       }


        this.handler.getLooper().quit(); // will no longer be usable. Basically, this class instance is now trash.

    }



    public interface OnDataReadCallback {

        @WorkerThread // watch out if you need to update some view, user your Activity#runOnUiThread method !

        void onDataRead(byte[] data);

    }

}


查看完整回答
反对 回复 2023-11-01
  • 1 回答
  • 0 关注
  • 180 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信