无法使用Arduino和Android进行点亮

时间:2016-12-01 18:16:09

标签: android arduino led

我希望使用Android在Arduino板上点亮。每个连接都已经过测试。手机可以看到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;
  }
  }
  }

1 个答案:

答案 0 :(得分:0)

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