android - 我如何从arduino接收蓝牙数据到android?

标签 android bluetooth arduino

我使用连接到arduino的温度传感器,然后通过蓝牙将温度信息发送到我的手机。我的电话应用程序具有完整的用户界面,可以接收信息。

我看到的每一个教程都是用来进行蓝牙配对的。我还没有完成这部分(因为arduino代码还没有完成,所以无法测试),但是假设我使用电话选项进行配对,我仍然不知道如何进行数据传输。

如何在手机上接收信息并显示出来?谁能指出有关如何继续的教程或解释/代码?

提前致谢!

最佳答案

看看这个……非常有效。在此代码中,您通过文件获取 MAC 地址并将其自动连接到设备。然后你就可以从 Arduino 发送和接收字符串数据了。您可以从此代码中获取灵感。

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Scroller;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;

public class MainActivity extends Activity implements OnSeekBarChangeListener {

public String ultimodato;

////
private static final String TAG = "bluetooth2";
Handler h;
final int RECEIVE_MESSAGE = 1;    //1    // Status  for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:14:02:13:00:10";
////

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    /* se non esiste il folder, creare il folder */
    File folder = new File(Environment.getExternalStorageDirectory() + "/Asiagem");
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdir();
    }
    
    setContentView(R.layout.main);
    
    //LETTURA DA FILE DEL MAC-ADDRESS A CUI CONNETTERSI
    try{
        String MACFile = readFileAsString("/sdcard/MAC.txt");
        if(MACFile==""){
             Toast.makeText(this,"Nessun dispositivo salvato, torno alla fase precedente", Toast.LENGTH_LONG).show();
             Intent i = new Intent(getApplicationContext(), Home.class);
             startActivity(i);
             finish();
        }else {
            address = MACFile;
        }
 }catch(Exception e){
     Toast.makeText(getApplicationContext(),"Errore nella lettura dei dati" , Toast.LENGTH_LONG).show();
     Intent i = new Intent(getApplicationContext(), Home.class);
     startActivity(i);
     finish();
 }
    h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:                                                   // if receive massage
                byte[] readBuf = (byte[]) msg.obj;
                String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
                Toast.makeText(getBaseContext(), strIncom, Toast.LENGTH_SHORT).show();
                Log.d("INCOME", "INCOME: " + strIncom);
                
               break;
            }
        };
    };
      
    btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
    checkBTState();
    
}

     
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
      if(Build.VERSION.SDK_INT >= 10){
          try {
              final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
              return (BluetoothSocket) m.invoke(device, MY_UUID);
          } catch (Exception e) {
              Log.e(TAG, "Could not create Insecure RFComm Connection",e);
          }
      }
      return  device.createRfcommSocketToServiceRecord(MY_UUID);
  }
        
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void SendMessageBT(View v){
        //INVIO MESSAGGIO AL BLUETOOTH
        mConnectedThread.write("U");
}   
@Override
  public void onResume() {
    super.onResume();
  
    Log.d(TAG, "...onResume - try connect...");
    
    // Set up a pointer to the remote node using it's address.
    BluetoothDevice device = btAdapter.getRemoteDevice(address);
    
    // Two things are needed to make a connection:
    //   A MAC address, which we got above.
    //   A Service ID or UUID.  In this case we are using the
    //     UUID for SPP.
     
    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }
    
    // Discovery is resource intensive.  Make sure it isn't going on
    // when you attempt to connect and pass your message.
    btAdapter.cancelDiscovery();
    
    // Establish the connection.  This will block until it connects.
    Log.d(TAG, "...Connecting...");
    try {
      btSocket.connect();
      Log.d(TAG, "....Connection ok...");
    } catch (IOException e) {
      try {
        btSocket.close();
      } catch (IOException e2) {
        errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
      }
    }
      
    // Create a data stream so we can talk to server.
    Log.d(TAG, "...Create Socket...");
    
    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();
    
    previousTime = System.currentTimeMillis();
    
  }
          
  @Override
  public void onPause() {
    super.onPause();
  
    Log.d(TAG, "...In onPause()...");
   
    try     {
      btSocket.close();
    } catch (IOException e2) {
      errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }
  }
    
  private void checkBTState() {
    // Check for Bluetooth support and then check to make sure it is turned on
    // Emulator doesn't support Bluetooth and will return null
    if(btAdapter==null) { 
      errorExit("Fatal Error", "Bluetooth not support");
    } else {
      if (btAdapter.isEnabled()) {
        Log.d(TAG, "...Bluetooth ON...");
      } else {
        //Prompt user to turn on Bluetooth
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
      }
    }
  }
  
  private void errorExit(String title, String message){
    Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
    finish();
  }
  
  private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
      
        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
      
            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }
      
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
      
        public void run() {
            byte[] buffer = new byte[256];  // buffer store for the stream
            int bytes; // bytes returned from read()
 
            // Keep listening to the InputStream until an exception occurs
            while (true) {
                if(System.currentTimeMillis() - previousTime > 10000){
                    previousTime = System.currentTimeMillis();
                    mConnectedThread.write("w");
                }
                
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                    h.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
    
                } catch (IOException e) {
                    break;
                }
            }
        }
      
        /* Call this from the main activity to send data to the remote device */
        public void write(String message) {
            Log.d(TAG, "...Data to send: " + message + "...");
            byte[] msgBuffer = message.getBytes();
            try {
                mmOutStream.write(msgBuffer);
            } catch (IOException e) {
                Log.d(TAG, "...Error data send: " + e.getMessage() + "...");  
                ultimodato=message;
                to_send=true;
                //connect();
                new connect_and_send().execute();
            }
        }
    }

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

        @Override
        protected void onPreExecute() {  // Fa vedere solo il dialog
            super.onPreExecute();
        }
 
        
        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                btSocket.close();
                Log.d(TAG, "...ALERT: " + "SOCKET CHIUSA" + "...");
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
                Log.d(TAG, "...ALERT: " + "IMPOSSIBILE CHIUDERE SOCKET" + "...");
            }
           
            Log.d(TAG, "...onResume - try connect...");
            
            // Set up a pointer to the remote node using it's address.
            BluetoothDevice device = btAdapter.getRemoteDevice(address);
            
            // Two things are needed to make a connection:
            //   A MAC address, which we got above.
            //   A Service ID or UUID.  In this case we are using the
            //     UUID for SPP.
             
            try {
                btSocket = createBluetoothSocket(device);
            } catch (IOException e) {
                errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
            }
            
            // Discovery is resource intensive.  Make sure it isn't going on
            // when you attempt to connect and pass your message.
            btAdapter.cancelDiscovery();
            
            // Establish the connection.  This will block until it connects.
            Log.d(TAG, "...Connecting...");
            try {
              btSocket.connect();
              Log.d(TAG, "....Connection ok...");
            } catch (IOException e) {
              try {
                btSocket.close();
              } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
              }
            }
              
            // Create a data stream so we can talk to server.
            Log.d(TAG, "...Create Socket...");
            
            mConnectedThread = new ConnectedThread(btSocket);
            mConnectedThread.start();
            //REINVIA L'ULTIMO DATO
            
            if (to_send==true){
                mConnectedThread.write(ultimodato);
                to_send=false;
            }
            
            previousTime = System.currentTimeMillis();
        return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
    }
public static String readFileAsString(String filePath) {

    String result = "";
    File file = new File(filePath);
    if ( file.exists() ) {
       FileInputStream fis = null;
        try {
           fis = new FileInputStream(file);
            char current;
            while (fis.available() > 0) {
                current = (char) fis.read();
                result = result + String.valueOf(current);

            }

        } catch (Exception e) {
            Log.d("TourGuide", e.toString());
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException ignored) {
            }
        }
       
   }
    return result;
    }
}

关于android - 我如何从arduino接收蓝牙数据到android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40590908/

相关文章:

android - 如何使用 Switch 基于字符串对 RecyclerView 中的 CardView 进行排序?

Android - Activity 之外的 startActivityForResult?

c# - 无法连接到蓝牙打印机

android - 当 Arduino 遇上 Android

c++打包和解包参数包以在没有STL的情况下调用匹配的函数指针

C - 如何从位字段接收位作为函数中的参数?

android - 如何将 Dagger 2 与自定义 View 一起使用?

android - 来自 Bitbucket 管道的权限被拒绝

android - Galaxy Tab 10 布局限定符

javascript - 使用 chrome.bluetoothLowEnergy API 连接到 iOS 设备