我试图通过蓝牙发送数据,但Serial.available()总是返回0

时间:2016-07-12 21:22:04

标签: java android c bluetooth arduino

我创建了一个Android应用程序(理论上)通过蓝牙将数据发送到arduino。 我知道我已经设法获得连接(蓝牙模块上的led停止闪烁)但是当我写一些值时,Serial.available()并没有改变。 我尝试过使用不同的应用程序(来自游戏商店) - 没有运气。

假设读取数据的arduino代码:

void setup() {
Serial.begin(9600);
Serial.println("Simple Motor Shield sketch");
}
void loop() {
if(Serial.available()>0){
Serial.println("in");
for(int i=0;i<=2;i++){
  joystick[i] = Serial.read();
}
for(int i=0;i<=2;i++){
  Serial.println(joystick[i]);
}
delay(1);
} 
}

joystick []是一个int数组

android代码:

    bluetoothIn = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == handlerState) {                                     //if message is what we want
                String readMessage = (String) msg.obj;                                                                // msg.arg1 = bytes from connect thread
                recDataString.append(readMessage);                                      //keep appending to string until ~
                int endOfLineIndex = recDataString.indexOf("~");                    // determine the end-of-line
                if (endOfLineIndex > 0) {                                           // make sure there data before ~
                    String dataInPrint = recDataString.substring(0, endOfLineIndex);    // extract string
                    int dataLength = dataInPrint.length();                          //get length of data received

                    recDataString.delete(0, recDataString.length());                    //clear all string data
                }
            }
        }
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
    checkBTState();

    // Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
    btnLeft.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mConnectedThread.write("0");    // Send "0" via Bluetooth
            Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
        }
    });

    btnRight.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mConnectedThread.write("1");    // Send "1" via Bluetooth
            Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
        }
    });
    layout_joystick.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View arg0, MotionEvent arg1) {
            js.drawStick(arg1);
            if (arg1.getAction() == MotionEvent.ACTION_DOWN
                    || arg1.getAction() == MotionEvent.ACTION_MOVE) {
                //int x = js.getX();
                //int y = js.getY();
                int angle = (int)js.getAngle();
                int distance = (int)js.getDistance();
                int maxDist = js.getOffset()+js.getLayoutHeight();

                distance =(int)(distance/(maxDist/9));
                angle=(int)(angle/40);
                distance=Math.max(distance,-9);
                distance=Math.min(distance,9);
                angle=Math.max(angle,-9);
                angle=Math.min(angle,9);
                //mConnectedThread.write(String.valueOf(x));
                //mConnectedThread.write(String.valueOf(y));
                mConnectedThread.write(String.valueOf(angle));
                mConnectedThread.write(String.valueOf(distance));
                Log.i("Bluetooth","Distance: " + distance);
                Log.i("Bluetooth","Angle: " + angle);

            }

            return true;
        }
    });
}

private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {

    return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
    //creates secure outgoing connecetion with BT device using UUID
}

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

    //Get MAC address from DeviceListActivity via intent
    Intent intent = getIntent();

    //Get the MAC address from the DeviceListActivty via EXTRA
    address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);

    //create device and set the MAC address
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
    }
    // Establish the Bluetooth socket connection.
    try
    {
        btSocket.connect();
    } catch (IOException e) {
        try
        {
            btSocket.close();
        } catch (IOException e2)
        {
            //insert code to deal with this
        }
    }
    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();

    //I send a character when resuming.beginning transmission to check device is connected
    //If it is not an exception will be thrown in the write method and finish() will be called
    mConnectedThread.write("0");
}

@Override
public void onPause()
{
    super.onPause();
    try
    {
        //Don't leave Bluetooth sockets open when leaving activity
        btSocket.close();
    } catch (IOException e2) {
        //insert code to deal with this
    }
}

//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {

    if(btAdapter==null) {
        Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
    } else {
        if (btAdapter.isEnabled()) {
        } else {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
    }
}

//create new class for connect thread
private class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    //creation of the connect thread
    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            //Create I/O streams for connection
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[256];
        int bytes;

        // Keep looping to listen for received messages
        while (true) {
            try {
                bytes = mmInStream.read(buffer);            //read bytes from input buffer
                String readMessage = new String(buffer, 0, bytes);
                // Send the obtained bytes to the UI Activity via handler
                bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
    //write method
    public void write(String input) {
        byte[] msgBuffer = input.getBytes();           //converts entered String into bytes
        try {
            mmOutStream.write(msgBuffer);                //write bytes over BT connection via outstream
        } catch (IOException e) {
            //if you cannot write, close the application
            Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
            finish();

        }
    }
}

2 个答案:

答案 0 :(得分:0)

对不起,对不起,我基本上想做的是检查蓝牙串口连接上是否有可用的数据。 所以当我发送数据时,我希望Serial.available()大于0。但是,当我发送数据时,Serial.available()和Serial.Read()似乎不起作用。 *我已设法使用以下程序解决问题:http://www.circuitmagic.com/arduino/arduino-and-bluetooth-hc-06-to-control-the-led-with-android-device/ *

答案 1 :(得分:0)

我认为你已经在arduino板的串行RX,TX引脚上连接了蓝牙模块。不是这种情况。您需要使用单独的串行与蓝牙通信。您可以使用软件序列来实现此目的,否则蓝牙模块将无法正常工作。 这背后的原因是arduino使用相同的串行引脚与PC通信(串行终端和程序加载),因此无法同时向蓝牙发送数据。

请看这里:https://bellcode.wordpress.com/2012/01/02/android-and-arduino-bluetooth-communication/