首页 > 解决方案 > 通过蓝牙向安卓发送字符串

问题描述

实际上,我正在构建一个 arduino 机器人,由我的应用程序发出语音命令,我不知道问题到底出在哪里,但我认为我的应用程序没有发送命令,因为谷歌辅助语音识别器检测到我的声音并将其传输到命令,但是当我制作 btsocket.getOutputStream.write() 时,我的事情不起作用,因为我的机器人没有任何动作来寻求帮助?

这里是安卓代码:

package com.example.enit_controller;

import android.content.ActivityNotFoundException;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    String address = null , name=null;
    public String cmd="sending ...." ;

    BluetoothAdapter myBluetooth = null;
    BluetoothSocket btSocket = null;
    Set<BluetoothDevice> pairedDevices;
    static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");


    Button ahki ;
    TextView device_marbout ;

    private final int REQ_CODE_SPEECH_INPUT = 100;

    public static 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);

        //declaration of button variables
        ahki = (Button) findViewById(R.id.ahki);
        device_marbout =(TextView) findViewById(R.id.device_marbout) ;
        try {
            bluetooth_connect_device();
        }
        catch (Exception e) {

        }

        ahki.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                promptSpeechInput();

                //Log.i("hahahahahh", command1) ;


            }
        });


    }



    private void promptSpeechInput() {
        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, "a7ki");
        try {
            startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
        } catch (ActivityNotFoundException a) {
            Toast.makeText(getApplicationContext(),
                    "there is no bleutooth ",
                    Toast.LENGTH_SHORT).show();
        }


    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_CODE_SPEECH_INPUT: {
                if (resultCode == RESULT_OK && null != data) {

                    ArrayList<String> result = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    command=result.get(0)  ;
                        try{
                            send_command(command);
                        }
                        catch (Exception e){

                        }

                }
                break;
            }

        }
    }


    private void bluetooth_connect_device() throws IOException
    {
        try
        {
            myBluetooth = BluetoothAdapter.getDefaultAdapter();
            address = myBluetooth.getAddress();
            pairedDevices = myBluetooth.getBondedDevices();
            if (pairedDevices.size()>0)
            {
                for(BluetoothDevice bt : pairedDevices)
                {
                    address=bt.getAddress().toString();name = bt.getName().toString();
                    Toast.makeText(getApplicationContext(),"Connected", Toast.LENGTH_SHORT).show();

                }
            }

        }
        catch(Exception we){}
        myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
        BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
        btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
        btSocket.connect();
        try { device_marbout.setText("BT Name: "+name+"\nBT Address: "+address); }
        catch(Exception e){}
    }

    private void send_command(String i)
    {
        try
        {
            if (btSocket!=null)
            {
                Log.e("test0", i) ;
                Log.e("test1 ", i) ;
                Log.e("test3 ",i.toString()+"nihaha") ;

                String cmd ;
                if (i.equals("right")){
                    Log.e("passeded_partially ", i) ;
                    cmd="*r" ;
                    btSocket.getOutputStream().write(cmd.toString().getBytes());
                    Log.e("passsed absolutly ", cmd) ;
                    }
            }

        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();

        }

    }





}

Arduino代码:

#include <AFMotor.h>
String command ; 
AF_DCMotor Memin (4, MOTOR12_1KHZ);
AF_DCMotor Misar (3, MOTOR12_1KHZ);

void setup() {
    Serial.begin(9600); 

}

void loop() {
    while (Serial.available()){ 
    char c = Serial.read();
    if (c == '#') {break;} 
    command += c; 
  }
  Serial.println(command) ;
  if (command.length() > 0){
    if(command == "f"){
      forward();
      }
    else if(command == "b"){
      back();
      }
    else if(command == "*r") {
      Right();
    }
    else if(command == "*l") {
      left();
    }
    else if(command == "  s") {
      stop_karhba();
    }

  command="";
  }

}



void forward() {
  Memin.run(FORWARD);
  Memin.setSpeed(170);
  Misar.run(FORWARD);
  Misar.setSpeed(170);
  delay(2000);
  Memin.run(RELEASE);
  Misar.run(RELEASE);
  }

  void back()
{
  Memin.run(BACKWARD);
  Memin.setSpeed(170);
  Misar.run(BACKWARD);
  Misar.setSpeed(170);
  delay(2000);
  Memin.run(RELEASE);
  Misar.run(RELEASE);
}


void Right() {
  Memin.run(BACKWARD);
  Memin.setSpeed(170);
  Misar.run(FORWARD);
  Misar.setSpeed(170);
  delay(1000);
  Memin.run(RELEASE);
  Misar.run(RELEASE);
}

void left(){
  Misar.run(BACKWARD);
  Misar.setSpeed(170);
  Memin.run(FORWARD);
  Memin.setSpeed(170);
  delay(1000);
  Misar.run(RELEASE);
  Misar.run(RELEASE);
}

void stop_karhba() {
  Memin.run(RELEASE) ; 
  Misar.run(RELEASE) ; 
}

标签: androidbluetootharduinoarduino-unoarduino-ide

解决方案


尽管我对这些基于外部硬件的应用程序缺乏经验,但我对此知之甚少,也对此进行了研究。

大多数专业人士使用麻省理工学院的应用程序发明者(在线工具)来开发你正在开发的这种应用程序。在这个工具中,你必须使用最容易理解和最简单的块代码 (根据我的经验)。

我找到了一个与您的项目接近的示例项目,您可以在此处找到它,您可以使用该项目根据您的要求进行更改。

你可以在这里找到 MIT 应用程序发明者

希望能帮助到你。


推荐阅读