有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我正在尝试通过蓝牙发送数据,但不是串行的。available()始终返回0

我创建了一个安卓应用程序(理论上)通过蓝牙向arduino发送数据。 我知道我已成功连接(蓝牙模块上的led停止闪烁),但串行端口已断开。当我写一些值时,available()没有改变。 我尝试过使用不同的应用程序(从play store)——运气不好

用于读取数据的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);
} 
}

操纵杆[]是一个int数组

安卓代码:

    bluetoothIn = new Handler() {
        public void handleMessage(安卓.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) 个答案

  1. # 1 楼答案

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

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