我想通过蓝牙将数据从 Android 发送到 Arduino

问题描述

我编写了一个 Android 应用程序,它应该通过蓝牙模块将数据发送到 Arduino hc-06 传感器以控制汽车。蓝牙连接正常。

我只想向 arduino 发送信号,例如当我按下右侧的按钮时。

我想写这样的东西:

customButtonRight.setonClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Bluetooth.sendValue("R");
           }
       });

接收信号的arduino代码部分:

if(mySerial.available() > 0)  // Send data only when you receive data:
    {
      
        data = mySerial.read();      //Read the incoming data and store it into variable data
        Serial.print(data);        //Print Value inside data in Serial monitor
        Serial.print("\n");        //New line 
     
        switch(data) 
        {
                 case 'F':
                      digitalWrite(led_galben_fata,HIGH);
                      
                      digitalWrite(led_rosu_spate,LOW);
                      digitalWrite(led_albastru_stanga,LOW);
                      digitalWrite(led_alb_dreapta,LOW);
                      
                 break;
                    
                 case 'B':
                      digitalWrite(led_rosu_spate,HIGH);
                      
                      digitalWrite(led_galben_fata,LOW);
                 break;
  
                 case 'L':
                      digitalWrite(led_albastru_stanga,LOW);
                      digitalWrite(led_rosu_spate,LOW);
                 break;
  
                 case 'R':
                      digitalWrite(led_alb_dreapta,HIGH);

                      digitalWrite(led_galben_fata,LOW);
                 break;
                 
                 case 'G':   ////   fata stanga
                      digitalWrite(led_galben_fata,HIGH);
                      digitalWrite(led_albastru_stanga,HIGH);

                      digitalWrite(led_rosu_spate,LOW);
                 break;
                    
                 case 'I':   ///// fata dreapta
                      digitalWrite(led_galben_fata,HIGH);
                      digitalWrite(led_alb_dreapta,LOW);
                 break;
  
                 case 'H':   //// spate stanga
                      digitalWrite(led_rosu_spate,LOW);
                 break;
  
                 case 'J':   //// spate dreapta
                      digitalWrite(led_rosu_spate,LOW);
                 break;
                 
                 default:
                     digitalWrite(led_galben_fata,LOW);
                     digitalWrite(led_rosu_spate,LOW);
                     digitalWrite(led_albastru_stanga,LOW);
                     digitalWrite(led_alb_dreapta,LOW);
        }   
     }

这是我关于我的 android 活动的完整代码

public class MonitoringScreen extends Activity {


    private static String LOG_TAG = "UIElementsPracticeLog";
    private static final String TAG = "BlueTest5-MainActivity";
    private int mMaxChars = 50000;//Default
    private UUID mDeviceUUID;
    private BluetoothSocket mBTSocket;
    private ReadInput mReadThread = null;


    private boolean mIsUserInitiateddisconnect = false;

    private boolean mIsBluetoothConnected = false;

    private BluetoothDevice mDevice;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitoring_screen);
        ActivityHelper.initialize(this);

        Intent intent = getIntent();
        Bundle b = intent.getExtras();
        mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
        mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
        mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);

        Button customButtonDown = findViewById(R.id.custom_button_down);
        Button customButtonUp = findViewById(R.id.custom_button_up);
        Button customButtonLeft = findViewById(R.id.custom_button_left);
        Button customButtonRight = findViewById(R.id.custom_button_right);

        customButtonDown.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i(LOG_TAG,"Down-Arrow button is pressed by user");
            }
        });
        customButtonUp.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i(LOG_TAG,"Up-Arrow button is pressed by user");
            }
        });
        customButtonLeft.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(LOG_TAG,"Left-Arrow button is pressed by user");
            }
        });
        customButtonRight.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i(LOG_TAG,"Right-Arrow button is pressed by user");
            }
        });
    }

    private class ReadInput implements Runnable {

        private boolean bStop = false;
        private Thread t;

        public Readinput() {
            t = new Thread(this,"Input Thread");
            t.start();
        }
        public boolean isRunning() {
            return t.isAlive();
        }

        @Override
        public void run() {
            InputStream inputStream;

            try {
                inputStream = mBTSocket.getInputStream();
                while (!bStop) {
                    byte[] buffer = new byte[256];
                    if (inputStream.available() > 0) {
                        inputStream.read(buffer);
                        int i = 0;
                        /*
                         * This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
                         */
                        for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
                        }
                        final String strInput = new String(buffer,i);

                        /*
                         * If checked then receive text,better design would probably be to stop thread if unchecked and free resources,but this is a quick fix
                         */
                    }
                    Thread.sleep(500);
                }
            } catch (IOException e) {
// Todo Auto-generated catch block
                e.printstacktrace();
            } catch (InterruptedException e) {
// Todo Auto-generated catch block
                e.printstacktrace();
            }

        }

        public void stop() {
            bStop = true;
        }

    }

    private class disConnectBT extends AsyncTask<Void,Void,Void> {

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected Void doInBackground(Void... params) {

            if (mReadThread != null) {
                mReadThread.stop();
                while (mReadThread.isRunning())
                    ; // Wait until it stops
                mReadThread = null;

            }

            try {
                mBTSocket.close();
            } catch (IOException e) {
// Todo Auto-generated catch block
                e.printstacktrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mIsBluetoothConnected = false;
            if (mIsUserInitiateddisconnect) {
                finish();
            }
        }

    }

    private void msg(String s) {
        Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        if (mBTSocket != null && mIsBluetoothConnected) {
            new disConnectBT().execute();
        }
        Log.d(TAG,"Paused");
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (mBTSocket == null || !mIsBluetoothConnected) {
            new ConnectBT().execute();
        }
        Log.d(TAG,"Resumed");
        super.onResume();
    }

    @Override
    protected void onStop() {
        Log.d(TAG,"Stopped");
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
// Todo Auto-generated method stub
        super.onSaveInstanceState(outState);
    }

    private class ConnectBT extends AsyncTask<Void,Void> {
        private boolean mConnectSuccessful = true;

        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(MonitoringScreen.this,"Hold on","Connecting");// http://stackoverflow.com/a/11130220/1287554
        }

        @Override
        protected Void doInBackground(Void... devices) {

            try {
                if (mBTSocket == null || !mIsBluetoothConnected) {
                    mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
                    BluetoothAdapter.getDefaultAdapter().canceldiscovery();
                    mBTSocket.connect();
                }
            } catch (IOException e) {
// Unable to connect to device
                e.printstacktrace();
                mConnectSuccessful = false;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (!mConnectSuccessful) {
                Toast.makeText(getApplicationContext(),"Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings",Toast.LENGTH_LONG).show();
                finish();
            } else {
                msg("Connected to device");
                mIsBluetoothConnected = true;
                mReadThread = new Readinput(); // Kick off input reader
            }

            progressDialog.dismiss();
        }
    }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)