Android通过蓝牙到Arduino。 App不会发送字符串

时间:2018-04-03 14:56:26

标签: java android string bluetooth arduino

我在互联网上找到了一些代码并进行了更改。我尝试通过蓝牙发送短字符串。我使用的是HC-05蓝牙模块。

我可以将我的Android设备连接到模块,但是我无法将字符串发送到我的Arduino。 我有: 1 EditText输入我的字符串。

2个按钮:

-1发送

-2连接

你能查看我的代码吗?谢谢:))

Android代码......

data

Android XML ...

union

2 个答案:

答案 0 :(得分:0)

尝试使用此代码,但此代码在 Fragment 中运行,因此请根据您的活动小心更改代码。

  package com.example.rishabhrawat.tablayoutapp;
  import android.app.Fragment;
  import android.app.ProgressDialog;
  import android.bluetooth.BluetoothAdapter;
  import android.bluetooth.BluetoothDevice;
  import android.bluetooth.BluetoothSocket;
  import android.content.ActivityNotFoundException;
  import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.media.Image;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.speech.RecognizerIntent;
  import android.support.annotation.Nullable;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.view.ViewGroup;
  import android.widget.AdapterView;
  import android.widget.ArrayAdapter;
  import android.widget.Button;
  import android.widget.ImageView;
  import android.widget.ListView;
  import android.widget.TextView;
  import android.widget.Toast;
  import java.io.IOException;
  import java.util.ArrayList;
  import java.util.Locale;
  import java.util.Set;
  import java.util.UUID;

  import static android.app.Activity.RESULT_OK;

/**
* Created by Rishabh Rawat on 6/18/2017.
*/

public class OfflineVideo extends android.support.v4.app.Fragment {


Button f,r,l,b,s,dis;
ListView listView;
ImageView mic;
BluetoothAdapter adapter;
private Set<BluetoothDevice> paireddevices;
private String address;

BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
private ProgressDialog progress;

private final int REQ_CODE_SPEECH_INPUT = 100;

static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.offlinevideo,container,false);

    f=(Button)view.findViewById(R.id.forward);
    r=(Button)view.findViewById(R.id.right);
    l=(Button)view.findViewById(R.id.left);
    b=(Button)view.findViewById(R.id.backward);
    s=(Button)view.findViewById(R.id.stop);
    dis=(Button)view.findViewById(R.id.discover);
    mic=(ImageView)view.findViewById(R.id.mic);
    listView=(ListView)view.findViewById(R.id.listview);

    f.setEnabled(false);
    r.setEnabled(false);
    l.setEnabled(false);
    b.setEnabled(false);
    s.setEnabled(false);
    mic.setEnabled(false);


   adapter=BluetoothAdapter.getDefaultAdapter();


    dis.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
         ShowPairedDevices();
        }
    });

    f.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            forward();
        }
    });

    r.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            right();
        }
    });

    l.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            left();
        }
    });

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            backward();
        }
    });

    s.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stop();
        }
    });

    mic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          VoiceInput();
        }
    });

    return view;
}

public void ShowPairedDevices()
{
    paireddevices=adapter.getBondedDevices();
    ArrayList list = new ArrayList();
    if (paireddevices.size()>0)
    {
        for(BluetoothDevice bt : paireddevices)
        {
            list.add(bt.getName() + "\n" + bt.getAddress());
        }
    }
    else
    {
        Toast.makeText(getContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
    }
    final ArrayAdapter adapter=new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, list);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(myclicklistner);
}


private AdapterView.OnItemClickListener myclicklistner= new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
        String info = ((TextView) v).getText().toString();
        address = info.substring(info.length() - 17);
        new  connectbt().execute();

    }
};


private class connectbt extends AsyncTask<Void, Void, Void>  // UI thread
{
    private boolean ConnectSuccess = true; //if it's here, it's almost connected

    @Override
    protected void onPreExecute()
    {
        progress = ProgressDialog.show(getActivity(), "Connecting...", "Please wait!!!");  //show a progress dialog
    }

    @Override
    protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
    {
        try
        {
            if (btSocket == null || !isBtConnected)
            {
                adapter = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
                BluetoothDevice dispositivo = adapter.getRemoteDevice(address);//connects to the device's address and checks if it's available
                btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
                BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                btSocket.connect();//start connection
            }
        }
        catch (IOException e)
        {
            ConnectSuccess = false;//if the try failed, you can check the exception here
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
    {
        super.onPostExecute(result);

        if (!ConnectSuccess)
        {
           Toast.makeText(getActivity().getApplicationContext(),"Connection Failed Please Try again later",Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(getActivity().getApplicationContext(), "Successfully Connected ", Toast.LENGTH_SHORT).show();
            f.setEnabled(true);
            r.setEnabled(true);
            l.setEnabled(true);
            b.setEnabled(true);
            s.setEnabled(true);
            mic.setEnabled(true);
            isBtConnected = true;
        }
        progress.dismiss();
    }
}


public void toast(String message)
{
    Toast.makeText(getActivity().getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void forward()
{
    if (btSocket!=null)
    {
        try
        {
            btSocket.getOutputStream().write("F".toString().getBytes());
        }
        catch (IOException e)
        {
            toast("Error");
        }
    }
}

private void left()
{
    if (btSocket!=null)
    {
        try
        {
            btSocket.getOutputStream().write("L".toString().getBytes());
        }
        catch (IOException e)
        {
            toast("Error");
        }
    }
}

private void right()
{
    if (btSocket!=null)
    {
        try
        {
            btSocket.getOutputStream().write("R".toString().getBytes());
        }
        catch (IOException e)
        {
            toast("Error");
        }
    }
}
private void backward()
{
    if (btSocket!=null)
    {
        try
        {
            btSocket.getOutputStream().write("B".toString().getBytes());
        }
        catch (IOException e)
        {
            toast("Error");
        }
    }
}
private void stop()
{
    if (btSocket!=null)
    {
        try
        {
            btSocket.getOutputStream().write("S".toString().getBytes());
        }
        catch (IOException e)
        {
            toast("Error");
        }
    }
}


public void VoiceInput()
{

    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            "Speak Command for Robot");
    try {
        startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
    } catch (ActivityNotFoundException a) {

    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==REQ_CODE_SPEECH_INPUT)
    {
        if(resultCode==RESULT_OK)
        {
            ArrayList<String> result = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if(result.get(0).equals("forward"))
            {
                forward();
            }
            else if(result.get(0).equals("backward"))
            {
                backward();
            }
            else if(result.get(0).equals("stop"))
            {
                stop();
            }
            else if(result.get(0).equals("left"))
            {
                left();
            }
            else if(result.get(0).equals("right"))
            {
                right();
            }
            else
            {
                Toast.makeText(getActivity(), result.get(0), Toast.LENGTH_SHORT).show();
            }
        }
    }
}
}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/forward"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Forward"
    android:background="#00bfff"
    android:textColor="#fff"
    android:layout_above="@+id/stop"
    android:layout_alignStart="@+id/stop"
    android:layout_marginBottom="27dp" />

<Button
    android:id="@+id/backward"
    android:background="#00bfff"
    android:textColor="#fff"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/forward"
    android:layout_centerVertical="true"
    android:text="Backward"
    />

<Button
    android:id="@+id/left"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="24dp"
    android:layout_marginEnd="14dp"
    android:text="Left"
    android:background="#00bfff"
    android:textColor="#fff"
    android:layout_above="@+id/backward"
    android:layout_alignParentEnd="true" />

<Button
    android:id="@+id/right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:background="#00bfff"
    android:textColor="#fff"
    android:layout_alignTop="@+id/left"
    android:layout_marginStart="17dp"
    android:text="Right" />

<Button
    android:id="@+id/stop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="STOP"
    android:background="#d22d2d"
    android:textColor="#fff"
    android:layout_alignBaseline="@+id/right"
    android:layout_alignBottom="@+id/right"
    android:layout_centerHorizontal="true" />

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/backward"
    android:divider="#52f202"
    android:dividerHeight="1dp"
    android:id="@+id/listview"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="48dp" />

<Button
    android:id="@+id/discover"
    android:background="#80ff00"
    android:textSize="25dp"
    android:textColor="#000099"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:fontFamily="sans-serif-smallcaps"
    android:text="Discovery"
    android:textAppearance="@style/TextAppearance.AppCompat.Light.Widget.PopupMenu.Large" />

<ImageView
    android:id="@+id/mic"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/discover"
    app:srcCompat="@drawable/microphone" />
 </RelativeLayout>

Arduino代码

char myserial;
void setup()
{
  pinMode(11,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);
  Serial.begin(9600);
}
void loop()
{
  myserial=Serial.read();
  switch(myserial)
{
  case 'S':
  digitalWrite(11,LOW);
  digitalWrite(10,LOW);
  digitalWrite(9,LOW);
  digitalWrite(8,LOW);
  break;


  case 'B':
  digitalWrite(11,HIGH);
  digitalWrite(10,LOW);
  digitalWrite(9,HIGH);
  digitalWrite(8,LOW);
  break;


  case 'F':
  digitalWrite(11,LOW);
  digitalWrite(10,HIGH);
  digitalWrite(9,LOW);
  digitalWrite(8,HIGH);
  break;

  case 'L':
  digitalWrite(11,HIGH);
  digitalWrite(10,LOW);
  digitalWrite(9,LOW);
  digitalWrite(8,HIGH);
  break;


  case 'R':
  digitalWrite(11,LOW);
  digitalWrite(10,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(8,LOW);
  break;

 }
 }

答案 1 :(得分:0)

btSocket.getOutputStream().write(sendText.getText().toString().getBytes());