Arduino Android蓝牙串行通信

时间:2015-03-16 06:34:31

标签: android bluetooth arduino

我有一个Arduino蓝牙盾牌HC-05。我首先使用Android设备配对蓝牙防护罩,并尝试通过蓝牙防护罩将数据发送到Arduino。 Android应用将数据发送到屏蔽。但Arduino没有收到超过(4到13)次的命令,我认为我的应用程序没有正确地与蓝牙屏蔽保持连接,我不确定这个问题。我尝试使用与其他Android应用程序相同的Arduino代码。它运作良好。所以问题只在我的代码中。我正在使用日志来监控代码流。数据从Android设备发送,蓝牙处于实时状态且仍然配对。我认为蓝牙盾没有收到或者它正在接收而没有将数据传递给Arduino。我困扰了几个星期。

先谢谢!!

我的代码在这里......

private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static String address = "98:D3:31:30:25:DC";//old: 20:14:12:03:12:42, 98:D3:31:30:25:DC
private static final UUID MY_UUID = UUID
        .fromString("00001101-0000-1000-8000-00805F9B34FB");
private InputStream inStream = null;
Handler handler = new Handler(); 
byte delimiter = 10;
boolean stopWorker = false;
int readBufferPosition = 0;
byte[] readBuffer = new byte[1024];
//
//Bluetooth sender ends
//
//

 private final  BroadcastReceiver commandAction = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context2, Intent intent2) {
                    String com = intent2.getStringExtra("key");
                    commandAction(com); 
                    Toast.makeText(context2, "commandAction:"+com, Toast.LENGTH_SHORT).show();
                }
           };



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

    setContentView(R.layout.activity_main);
    final Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            commandAction("up");
        }
    });
    GCMRegistrar.checkDevice( this );
    GCMRegistrar.checkManifest( this );
    final String regId = GCMRegistrar.getRegistrationId( this );
    if( regId.equals( "" ) ) {
        GCMRegistrar.register( this, "501396392354" );
        Toast.makeText(this," 501396392354", Toast.LENGTH_SHORT).show();
    }
    else {
        Toast.makeText(this,regId, Toast.LENGTH_SHORT).show();
        Log.v( TAG2, "Already registered" );
        Log.v(TAG2, "Registration id is: " + regId );
    }



    startService(new Intent(MainActivity.this, LocationService.class)); 

    CheckBt();
    Connect();
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    Log.e("Jon", device.toString());

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}


@Override
public Object onRetainNonConfigurationInstance() {
    if (mAccessory != null) {
        return mAccessory;
    } else {
        return super.onRetainNonConfigurationInstance();
    }
}

@Override
public void onResume() {
    super.onResume();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("in.robot.gcm.commandaction");
    registerReceiver(commandAction, intentFilter);

    if (mInputStream != null && mOutputStream != null) {
        return;
    }
}

@Override
public void onPause() {
    super.onPause();
     unregisterReceiver(commandAction);
    closeAccessory();
}

@Override
public void onDestroy() {
    unregisterReceiver(mUsbReceiver);

    stopService(new Intent(MainActivity.this, LocationService.class));


    try {
        btSocket.close();
    } catch (IOException e) {
    }
    super.onDestroy();
}

private void openAccessory(UsbAccessory accessory) {
    mFileDescriptor = mUsbManager.openAccessory(accessory);
    if (mFileDescriptor != null) {
        mAccessory = accessory;
        FileDescriptor fd = mFileDescriptor.getFileDescriptor();
        mInputStream = new FileInputStream(fd);
        mOutputStream = new FileOutputStream(fd);
        Log.d(TAG, "accessory opened");
    } else {
        Log.d(TAG, "accessory open fail");
    }
}


private void closeAccessory() {
    try {
        if (mFileDescriptor != null) {
            mFileDescriptor.close();
        }
    } catch (IOException e) {
    } finally {
        mFileDescriptor = null;
        mAccessory = null;
    }
}

public void commandAction(String command){

    byte[] buffer = new byte[1];
    MediaPlayer mp;

    Toast.makeText(this,"in cmd action",Toast.LENGTH_SHORT).show();

    if("up".equals(command)){
        buffer[0]=(byte)0;
        Log.v(TAG ,"up heay");
        writeData("1");
        Toast.makeText(this,"UP",Toast.LENGTH_SHORT).show();
    }

    else if("down".equals(command)) {
        buffer[0]=(byte)1;
        Log.v(TAG ,"down heay");
        writeData("2");
    }

    else if("left".equals(command)){
        buffer[0]=(byte)2;
        writeData("3");
    }
    else if("right".equals(command)){
        buffer[0]=(byte)3;
        writeData("4");
    }
    else if("break".equals(command)){
        buffer[0]=(byte)4;
        writeData("0");
    }

    else if("camera left".equals(command)){
        buffer[0]=(byte)5;
        //writeData("0");
    }
    else if("camera right".equals(command)){
        buffer[0]=(byte)6;
        //writeData("0");
    }

    else if ("jigsaw1".equals(command)){
         mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw1);  
          mp.start();
          }

        else if("jigsaw2".equals(command)){
             mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw2);  
              mp.start();
        }
        else if("horn".equals(command)){
             mp = MediaPlayer.create(MainActivity.this, R.raw.horn);  
              mp.start();
        }
        else if("start".equals(command)){
             mp = MediaPlayer.create(MainActivity.this, R.raw.start);  
              mp.start();
        }
        else if("ghosts".equals(command)){
             mp = MediaPlayer.create(MainActivity.this, R.raw.ghosts);  
              mp.start();
        }
        else if("flash on".equals(command)){

            if((this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) && !(isLighOn)){

                 cam = Camera.open();     
                    Parameters params = cam.getParameters();
                    params.setFlashMode(Parameters.FLASH_MODE_ON);
                    cam.setParameters(params);
                    cam.startPreview();
                    isLighOn=true; 
                    Log.v("camera","flash on");
            }
            else{Log.v("camera","flash not exsisted");}

        }

        else if("flash off".equals(command)){
            if(isLighOn){
            cam.stopPreview();
             cam.release();
             isLighOn=false;
             Log.v("camera","flash off");   
        } }

        else if("location on".equals(command)){
              startService(new Intent(MainActivity.this, LocationService.class)); 
        }
        else if("location off".equals(command)){
            stopService(new Intent(MainActivity.this, LocationService.class));
        }

        else if("speed min".equals(command)){
            buffer[0]=(byte)7;
        }

        else if("speed min".equals(command)){
            buffer[0]=(byte)8;
        }
        else if("speed max".equals(command)){
            buffer[0]=(byte)9;
        }

    else{
        Log.v(TAG ,"no command recieved");}



    if (mOutputStream != null) {
        try {
            mOutputStream.write(buffer);
        } catch (IOException e) {
            Log.e(TAG, "write failed", e);
        }
    }
}


//
//
//
//
private void CheckBt() {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (!mBluetoothAdapter.isEnabled()) {
        Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
                Toast.LENGTH_SHORT).show();
    }

    if (mBluetoothAdapter == null) {
        Toast.makeText(getApplicationContext(),
                "Bluetooth null !", Toast.LENGTH_SHORT)
                .show();
    }
}

    public void Connect() {
        Log.d(TAG, address);
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        Log.d(TAG, "Connecting to ... " + device);
        Toast.makeText(this, "Connecting to...", Toast.LENGTH_SHORT).show();
        mBluetoothAdapter.cancelDiscovery();
        try {
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            btSocket.connect();
            Log.d(TAG, "Connection made.");
            Toast.makeText(this, "Connection made Successful..", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                Log.d(TAG, "Unable to end the connection");
                Toast.makeText(this, "Unable to end the connection", Toast.LENGTH_SHORT).show();
            }
            Log.d(TAG, "Socket creation failed");
            Toast.makeText(this, "connection creation failed", Toast.LENGTH_SHORT).show();
        }

        //beginListenForData();
    }

private void writeData(String data) {
    try {
        outStream = btSocket.getOutputStream();
    } catch (IOException e) {
        Log.d(TAG, "Bug BEFORE Sending stuff", e);
    }

    String message = data;
    byte[] msgBuffer = message.getBytes();

    try {
        outStream.write(msgBuffer);
        Toast.makeText(this, "Data Send Successful..", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Log.d(TAG, "Bug while sending stuff", e);
        Toast.makeText(this, "Data Send Error..", Toast.LENGTH_SHORT).show();
    }
}

}

0 个答案:

没有答案