不能点亮 Arduino&Android

Can't Light Led with Arduino&Android

我想用 Android 点亮 Arduino 板上的 LED。每个连接都在船上进行了测试。手机可以看到HC-06模块。但我认为我的 Android 代码有问题。

ArduinoHelper.java

public class ArduinoHelper {


public static void send(int character) throws  Exception
{
    try
    {
        BluetoothAdapter adp=BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> eslesmiscihazlar=adp.getBondedDevices();
        BluetoothDevice arduino=null;
        for(BluetoothDevice cihaz:eslesmiscihazlar)
        {
            if(cihaz.getName()=="HC-06" || cihaz.getName()=="20:16:07:18:09:05")
            {
                arduino=cihaz;
                break;
            }
        }

        if(arduino!=null)
        {
            String id="20.16.07.18.09.05";
            UUID uuid=UUID.nameUUIDFromBytes(id.getBytes());
            BluetoothSocket socket=arduino.createRfcommSocketToServiceRecord(uuid);
            socket.connect();
            OutputStream strm=socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(strm);
            osw.write(character);
            osw.close();
            strm.close();
            socket.close();
        }

    }
    catch (Exception e)
    {
        throw  e;
    }

}}

MainActivity.java

public class MainActivity extends AppCompatActivity {

public ToggleButton tg;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tg= (ToggleButton) findViewById(R.id.toggleButton);

    tg.setTextOff("SÖNDÜR");
    tg.setTextOn("YAK");

    tg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                if(tg.isChecked()) {
                    ArduinoHelper.send((int) 'A');
                    Toast t=Toast.makeText(MainActivity.this,"Başarılı",Toast.LENGTH_SHORT);
                    t.show();
                    }


                else
                    ArduinoHelper.send((int) 'B');
            }
            catch (Exception e)
            {
                Log.e("BAU",e.getMessage());
            }
        }

    });


}}

LedLight.ino

#include <SoftwareSerial.h>
#define arduinoRx 11
#define arduinoTx 10
int gelen_veri;
int LedCikis = 8 ;

SoftwareSerial bluetooth(arduinoRx,arduinoTx);    

void setup()
 {
 bluetooth.begin(9600);
 }

  void loop(){
  if(bluetooth.available()>0)   
  {
   gelen_veri=bluetooth.read();    
   switch(gelen_veri)
  {
   case 'A' :
   digitalWrite(LedCikis,HIGH);
   break;
   case 'B' :
   digitalWrite(LedCikis,LOW);
   break;
   default:
   break;
  }
  }
  }

查看本教程 HC06 对我来说效果很好。第 2 部分修复了第一个字符丢失的问题。