如何通过蓝牙从Android手机发送角色到arduino?

时间:2015-04-22 17:10:38

标签: android sockets bluetooth arduino

目前我正在使用Arduino nano接收数据并通过蓝牙将其传输到Android手机。我想在我的智能手机上设置一些按钮,然后按下它后,它会将一个角色传送给arduino。 我测试了我的arduino,如果我在串行监视器中给出某些命令,它会给我模拟读取信号。

我想问一下如何将手机中的角色(如“E”)传送给arduino? 以下代码与蓝牙连接相关联。我还可以添加什么来实现我的目标?

arduino中的蓝牙代码

public class Homescreen extends Activity {

private Button mBtnSearch;
private Button mBtnConnect;
private ListView mLstDevices;

private BluetoothAdapter mBTAdapter;

private static final int BT_ENABLE_REQUEST = 10; // This is the code we use for BT Enable
private static final int SETTINGS = 20;

private UUID mDeviceUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID
// (http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord%28java.util.UUID%29)

private int mBufferSize = 50000; //Default
public static final String DEVICE_EXTRA = "com.blueserial.SOCKET";
public static final String DEVICE_UUID = "com.blueserial.uuid";
private static final String DEVICE_LIST = "com.blueserial.devicelist";
private static final String DEVICE_LIST_SELECTED = "com.blueserial.devicelistselected";
public static final String BUFFER_SIZE = "com.blueserial.buffersize";
private static final String TAG = "BlueTest5-Homescreen";
public  String isECG;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_homescreen);

    ActivityHelper.initialize(this); //This is to ensure that the rotation persists across activities and not just this one
    Log.d(TAG, "Created");

    Intent i = getIntent();
    if (i.hasExtra("isECG")){
         isECG = i.getStringExtra("isECG");   
    }
    TextView tv1 = (TextView)findViewById(R.id.tv1);
    tv1.setText(isECG);

    mBtnSearch = (Button) findViewById(R.id.btnSearch);
    mBtnConnect = (Button) findViewById(R.id.btnConnect);

    mLstDevices = (ListView) findViewById(R.id.lstDevices);
    Button btBack = (Button) findViewById(R.id.btBack);

    btBack.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {


            Intent intent = new Intent();

            intent.setClass(Homescreen.this, StartScreen.class);

            startActivity(intent);


        }
    });
    /*
     *Check if there is a savedInstanceState. If yes, that means the onCreate was probably triggered by a configuration change
     *like screen rotate etc. If that's the case then populate all the views that are necessary here 
     */
    if (savedInstanceState != null) {
        ArrayList<BluetoothDevice> list = savedInstanceState.getParcelableArrayList(DEVICE_LIST);
        if(list!=null){
            initList(list);
            MyAdapter adapter = (MyAdapter)mLstDevices.getAdapter();
            int selectedIndex = savedInstanceState.getInt(DEVICE_LIST_SELECTED);
            if(selectedIndex != -1){
                adapter.setSelectedIndex(selectedIndex);
                mBtnConnect.setEnabled(true);
            }
        } else {
            initList(new ArrayList<BluetoothDevice>());
        }

    } else {
        initList(new ArrayList<BluetoothDevice>());
    }


    mBtnSearch.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            mBTAdapter = BluetoothAdapter.getDefaultAdapter();

            if (mBTAdapter == null) {
                Toast.makeText(getApplicationContext(), "Bluetooth not found", Toast.LENGTH_SHORT).show();
            } else if (!mBTAdapter.isEnabled()) {
                Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBT, BT_ENABLE_REQUEST);
            } else {
                new SearchDevices().execute();
            }
        }
    });

    mBtnConnect.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            BluetoothDevice device = ((MyAdapter) (mLstDevices.getAdapter())).getSelectedItem();
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            intent.putExtra(DEVICE_EXTRA, device);
            intent.putExtra(DEVICE_UUID, mDeviceUUID.toString());
            intent.putExtra(BUFFER_SIZE, mBufferSize);

            intent.putExtra("isECG", isECG);

            intent.setClass(Homescreen.this, MainActivity.class);

            startActivity(intent);
        }
    });
}

/**
 * Called when the screen rotates. If this isn't handled, data already generated is no longer available
 */
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    MyAdapter adapter = (MyAdapter) (mLstDevices.getAdapter());
    ArrayList<BluetoothDevice> list = (ArrayList<BluetoothDevice>) adapter.getEntireList();

    if (list != null) {
        outState.putParcelableArrayList(DEVICE_LIST, list);
        int selectedIndex = adapter.selectedIndex;
        outState.putInt(DEVICE_LIST_SELECTED, selectedIndex);
    }
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case BT_ENABLE_REQUEST:
        if (resultCode == RESULT_OK) {
            msg("Bluetooth Enabled successfully");
            new SearchDevices().execute();
        } else {
            msg("Bluetooth couldn't be enabled");
        }

        break;
    case SETTINGS: //If the settings have been updated
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String uuid = prefs.getString("prefUuid", "Null");
        mDeviceUUID = UUID.fromString(uuid);
        Log.d(TAG, "UUID: " + uuid);
        String bufSize = prefs.getString("prefTextBuffer", "Null");
        mBufferSize = Integer.parseInt(bufSize);

        String orientation = prefs.getString("prefOrientation", "Null");
        Log.d(TAG, "Orientation: " + orientation);
        if (orientation.equals("Landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else if (orientation.equals("Portrait")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else if (orientation.equals("Auto")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
        }
        break;
    default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

/**
 * Quick way to call the Toast
 * @param str
 */
private void msg(String str) {
    Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}

/**
 * Initialize the List adapter
 * @param objects
 */
private void initList(List<BluetoothDevice> objects) {
    final MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.list_item, R.id.lstContent, objects);
    mLstDevices.setAdapter(adapter);
    mLstDevices.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            adapter.setSelectedIndex(position);
            mBtnConnect.setEnabled(true);
        }
    });
}

/**
 * Searches for paired devices. Doesn't do a scan! Only devices which are paired through Settings->Bluetooth
 * will show up with this. I didn't see any need to re-build the wheel over here
 * @author ryder
 *
 */
private class SearchDevices extends AsyncTask<Void, Void, List<BluetoothDevice>> {

    @Override
    protected List<BluetoothDevice> doInBackground(Void... params) {
        Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
        List<BluetoothDevice> listDevices = new ArrayList<BluetoothDevice>();
        for (BluetoothDevice device : pairedDevices) {
            listDevices.add(device);
        }
        return listDevices;

    }

    @Override
    protected void onPostExecute(List<BluetoothDevice> listDevices) {
        super.onPostExecute(listDevices);
        if (listDevices.size() > 0) {
            MyAdapter adapter = (MyAdapter) mLstDevices.getAdapter();
            adapter.replaceItems(listDevices);
        } else {
            msg("No paired devices found, please pair your serial BT device and try again");
        }
    }

}

/**
 * Custom adapter to show the current devices in the list. This is a bit of an overkill for this 
 * project, but I figured it would be good learning
 * Most of the code is lifted from somewhere but I can't find the link anymore
 * @author ryder
 *
 */
private class MyAdapter extends ArrayAdapter<BluetoothDevice> {
    private int selectedIndex;
    private Context context;
    private int selectedColor = Color.parseColor("#abcdef");
    private List<BluetoothDevice> myList;

    public MyAdapter(Context ctx, int resource, int textViewResourceId, List<BluetoothDevice> objects) {
        super(ctx, resource, textViewResourceId, objects);
        context = ctx;
        myList = objects;
        selectedIndex = -1;
    }

    public void setSelectedIndex(int position) {
        selectedIndex = position;
        notifyDataSetChanged();
    }

    public BluetoothDevice getSelectedItem() {
        return myList.get(selectedIndex);
    }

    @Override
    public int getCount() {
        return myList.size();
    }

    @Override
    public BluetoothDevice getItem(int position) {
        return myList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class ViewHolder {
        TextView tv;
    }

    public void replaceItems(List<BluetoothDevice> list) {
        myList = list;
        notifyDataSetChanged();
    }

    public List<BluetoothDevice> getEntireList() {
        return myList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        ViewHolder holder;
        if (convertView == null) {
            vi = LayoutInflater.from(context).inflate(R.layout.list_item, null);
            holder = new ViewHolder();

            holder.tv = (TextView) vi.findViewById(R.id.lstContent);

            vi.setTag(holder);
        } else {
            holder = (ViewHolder) vi.getTag();
        }

        if (selectedIndex != -1 && position == selectedIndex) {
            holder.tv.setBackgroundColor(selectedColor);
        } else {
            holder.tv.setBackgroundColor(Color.WHITE);
        }
        BluetoothDevice device = myList.get(position);
        holder.tv.setText(device.getName() + "\n   " + device.getAddress());

        return vi;
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.homescreen, menu);
    return true;
}

}

1 个答案:

答案 0 :(得分:0)

在我的android代码中我有这些全局变量:

 BluetoothAdapter mBluetoothAdapter;
 BluetoothSocket mmSocket;
 BluetoothDevice mmDevice;
 OutputStream mmOutputStream;
 InputStream mmInputStream;

然后我以与你所做的相似的方式获得配对的蓝牙设备:

@Override
    protected List<BluetoothDevice> doInBackground(Void... params) {
        Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
        List<BluetoothDevice> listDevices = new ArrayList<BluetoothDevice>();
        for (BluetoothDevice device : pairedDevices) {
            listDevices.add(device);
        }
        return listDevices;

    }

然后,当我选择正确的蓝牙设备时,我将其设置为mmDevice:

mmDevice = device;

然后我使用这种方法打开蓝牙连接:

void openBT() throws IOException{
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

        //Optional
        System.out.println("Bluetooth Opened");
        Toast.makeText(getApplicationContext(), "Bluetooth Opened", Toast.LENGTH_SHORT).show();
    }

mmOutputStream将数据发送到蓝牙模块,mmInputStream从蓝牙模块读取传入数据。我有这种方法将数据发送到蓝牙模块:

void sendData(String m) throws IOException{
        String msg = m;
        mmOutputStream.write(msg.getBytes());
        System.out.println("Data Sent");
    }

这会将字符串转换为字节并将其发送到Arduino。在Arduino方面,你可以说

if(bluetooth.available())
  {
    char c = bluetooth.read();
    Serial.println(c);
  }

如果您只是阅读一个字母或说:

if(bluetooth.available())
      {
        int data = bluetooth.parseInt();
        Serial.println(data);
      }

读取通过蓝牙发送的整数值。希望这可以帮助。如果您需要什么,请不要犹豫。

相关问题