2016-12-01 68 views
1

我想用Arduino燈點亮Android燈光。每個連接都已經過測試。手機可以看到HC-06模塊。但我認爲我在Android代碼中遇到問題。不能用Arduino點亮燈光And 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; 
    } 
    } 
    } 

回答

0

檢查OU本教程HC06適合我。有第2部分解決缺失的第一個字符問題。

+0

非常感謝你,夥伴。我會檢查。 –