简体   繁体   English

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

[英]I am trying to send data via bluetooth but Serial.available() always return 0

I have created an android app that (theoretically) sends data to the arduino via bluetooth. 我创建了一个Android应用程序(理论上)通过蓝牙将数据发送到arduino。 I know that I have managed to get connectivity(the led on the bluetooth module stopped blinking) but the Serial.available() isn't changing when I write some values. 我知道我已经设法获得连接(蓝牙模块上的LED指示灯停止闪烁),但是当我编写一些值时Serial.available()并没有改变。 I have tried using different apps (from the play store) - no luck. 我尝试使用(来自Play商店)不同的应用-祝您好运。

The arduino code which suppose to read the data: 假设要读取数据的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[] is an int array joystick []是一个int数组

android code: 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();

        }
    }
}

Sorry for the unclarity, basically what I wanted to do is to check if I had any data available on the bluetooth serial connection. 抱歉,不确定,基本上我想做的是检查蓝牙串行连接上是否有可用数据。 So I hoped that Serial.available() would be more than 0 when I sent data.Yet, the Serial.available() and Serial.Read() didn't seemed to work when I sent data. 所以我希望我发送数据时Serial.available()可以大于0。但是,当我发送数据时,Serial.available()和Serial.Read()似乎不起作用。 * I have managed to solve the problem using the program from: http://www.circuitmagic.com/arduino/arduino-and-bluetooth-hc-06-to-control-the-led-with-android-device/ * *我已经使用以下程序成功解决了问题: http : //www.circuitmagic.com/arduino/arduino-and-bluetooth-hc-06-to-control-the-led-with-android-device// *

I think you have connected Bluetooth module on serial RX,TX pins of arduino board. 我认为您已经在arduino板的串行RX,TX引脚上连接了蓝牙模块。 this is not the case. 不是这种情况。 You need to use separate serial for communication with Bluetooth. 您需要使用单独的串口与蓝牙通信。 You can use software serial for this purpose otherwise Bluetooth module won't work. 您可以为此目的使用软件串行,否则蓝牙模块将无法工作。 The reason behind this is that the arduino uses same serial pins to communicate with PC (Serial terminal and program load) so it cannot simultaneously send data to Bluetooth. 这背后的原因是arduino使用相同的串行引脚与PC通信(串行终端和程序加载),因此它无法同时将数据发送到蓝牙。

Have a look at here: https://bellcode.wordpress.com/2012/01/02/android-and-arduino-bluetooth-communication/ 在这里看看: https : //bellcode.wordpress.com/2012/01/02/android-and-arduino-bluetooth-communication/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM