简体   繁体   English

通过蓝牙将Android转换为Arduino。 应用程序不会发送字符串

[英]Android to Arduino via Bluetooth. App won't send string

I found some code in the Internet and changed it. 我在互联网上找到了一些代码并进行了更改。 I try to send a short string via Bluetooth. 我尝试通过蓝牙发送短字符串。 I use the HC-05 Bluetooth module. 我使用HC-05蓝牙模块。

I can connect my android device with the module but I can't send a string to my Arduino. 我可以将我的android设备与该模块连接,但是无法将字符串发送到Arduino。 I have: 1 EditText to enter my string. 我有:1 EditText输入我的字符串。

2 Buttons: 2个按钮:

-1 to send -1发送

-2 to connect -2连接

Could you look over my code? 你能看一下我的代码吗? Thank you:) 谢谢:)

Android Code... Android代码...

    private BluetoothDevice device;
    private BluetoothSocket socket;
    private OutputStream outputStream;


    String command;//string variable that will store value to be transmitted to the bluetooth module

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button BtSend = findViewById(R.id.BtSend);
        Button BtVerbinden = findViewById(R.id.BtVerbinden);
        final EditText EtEingabe = findViewById(R.id.EtEingabe);
        BtSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                command = EtEingabe.getText().toString();
                try {
                    outputStream.write(command.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });


        //Button that connects the device to the bluetooth module when pressed
        BtVerbinden.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (BTinit()) {
                    BTconnect();
                }

            }
        });
    }

    public boolean BTinit() {
        boolean found = false;

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter == null) //Checks if the device supports bluetooth
        {
            Toast.makeText(getApplicationContext(), "Device doesn't support bluetooth", Toast.LENGTH_SHORT).show();
        }

        if (!bluetoothAdapter.isEnabled())
        {
            Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableAdapter, 0);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();

        if (bondedDevices.isEmpty())
        {
            Toast.makeText(getApplicationContext(), "Please pair the device first", Toast.LENGTH_SHORT).show();
        } else {
            for (BluetoothDevice iterator : bondedDevices) {
                if (iterator.getAddress().equals(DEVICE_ADDRESS)) {
                    device = iterator;
                    found = true;
                    break;
                }
            }
        }

        return found;
    }

    public boolean BTconnect() {
        boolean connected = true;

        try {
            socket = device.createRfcommSocketToServiceRecord(PORT_UUID); //Creates a socket to handle the outgoing connection
            socket.connect();

            Toast.makeText(getApplicationContext(),
                    "Connection to bluetooth device successful", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
            connected = false;
        }

        if (connected) {
            try {
                outputStream = socket.getOutputStream(); //gets the output stream of the socket
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream == null) {
            try {
                outputStream = socket.getOutputStream();
            } catch (IOException e) {
            }
        }
        return connected;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

}

Android XML... Android XML ...

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.swini.gimbalarduino.MainActivity">

    <Button
        android:id="@+id/BtSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="184dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:text="Send"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/EtEingabe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="220dp"
        android:ems="10"
        android:hint="Hoi"
        android:inputType="textPersonName"
        android:text="Text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/BtVerbinden"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Connect"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Try to use this code but this code run in Fragment so carefully change the Code according to your activity. 尝试使用此代码,但是该代码在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();
            }
        }
    }
}
}

Layout File 布局文件

<?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 Code 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;

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

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

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