Sending data from Android to Arduino with HC-06 Bluetooth module -


i've created android app communicate arduino using bluetooth. when i'm sending data android device arduino, arduino isn't responding i've send. able connection android device arduino. that's not problem.

here's full script android.

package nl.handoko.lumamini;  import java.io.ioexception; import java.io.outputstream; import java.util.uuid;  import android.app.activity; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothdevice; import android.bluetooth.bluetoothsocket; import android.content.intent; import android.os.bundle; import android.util.log; import android.view.menu; import android.view.menuitem; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.textview; import android.widget.toast;  public class mainactivity extends activity {     private static final string tag = "lumamini";       private static final int request_enable_bt = 1;       private bluetoothadapter btadapter = null;       private bluetoothsocket btsocket = null;       private outputstream outstream = null;        button fourty, thirty, twenty, twelve, automatic, manual;       textview message;        // known spp uuid       private static final uuid my_uuid =           uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb");         // server's mac address       private static string address = "98:d3:31:30:09:43";      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         log.d(tag, "in oncreate()");         setcontentview(r.layout.activity_mainnn);          fourty = (button) findviewbyid(r.id.button1);         thirty = (button) findviewbyid(r.id.button4);         twenty = (button) findviewbyid(r.id.button2);         twelve = (button) findviewbyid(r.id.button5);         automatic = (button) findviewbyid(r.id.button3);         manual = (button) findviewbyid(r.id.button6);          message = (textview) findviewbyid(r.id.textview1);          fourty.settext("40 leds");         thirty.settext("30 leds");         twenty.settext("20 leds");         twelve.settext("12 leds");         automatic.settext("automatic");         manual.settext("manual");         message.settext("using app can take full control of luma mini!" +                 "when it's running on automatic please switch manual first before switching other versions.");          btadapter = bluetoothadapter.getdefaultadapter();         checkbtstate();          fourty.setonclicklistener(new onclicklistener() {             public void onclick(view v) {               senddata("a");               toast msg = toast.maketext(getbasecontext(),                   "40 leds version", toast.length_short);               msg.show();             }           });         thirty.setonclicklistener(new onclicklistener() {             public void onclick(view v) {               senddata("b");               toast msg = toast.maketext(getbasecontext(),                   "30 leds version", toast.length_short);               msg.show();             }           });         twenty.setonclicklistener(new onclicklistener() {             public void onclick(view v) {               senddata("c");               toast msg = toast.maketext(getbasecontext(),                   "20 leds version", toast.length_short);               msg.show();             }           });         twelve.setonclicklistener(new onclicklistener() {             public void onclick(view v) {               senddata("d");               toast msg = toast.maketext(getbasecontext(),                   "12 leds version", toast.length_short);               msg.show();             }           });         automatic.setonclicklistener(new onclicklistener() {             public void onclick(view v) {               senddata("e");               toast msg = toast.maketext(getbasecontext(),                   "run automatically", toast.length_short);               msg.show();             }           });         manual.setonclicklistener(new onclicklistener() {             public void onclick(view v) {               senddata("f");               toast msg = toast.maketext(getbasecontext(),                   "manually switch leds", toast.length_short);               msg.show();             }           });         }     @override     public void onresume() {       super.onresume();        log.d(tag, "...in onresume - attempting client connect...");        // set pointer remote node using it's address.       bluetoothdevice device = btadapter.getremotedevice(address);        // 2 things needed make connection:       //   mac address, got above.       //   service id or uuid.  in case using       //     uuid spp.       try {         btsocket = device.createrfcommsockettoservicerecord(my_uuid);       } catch (ioexception e) {         errorexit("fatal error", "in onresume() , socket create failed: " + e.getmessage() + ".");       }        // discovery resource intensive.  make sure isn't going on       // when attempt connect , pass message.       btadapter.canceldiscovery();        // establish connection.  block until connects.       log.d(tag, "...connecting remote...");       try {         btsocket.connect();         log.d(tag, "...connection established , data link opened...");       } catch (ioexception e) {         try {           btsocket.close();         } catch (ioexception e2) {           errorexit("fatal error", "in onresume() , unable close socket during connection failure" + e2.getmessage() + ".");         }       }        // create data stream can talk server.       log.d(tag, "...creating socket...");        try {         outstream = btsocket.getoutputstream();       } catch (ioexception e) {         errorexit("fatal error", "in onresume() , output stream creation failed:" + e.getmessage() + ".");       }     }      @override     public void onpause() {       super.onpause();        log.d(tag, "...in onpause()...");        if (outstream != null) {         try {           outstream.flush();         } catch (ioexception e) {           errorexit("fatal error", "in onpause() , failed flush output stream: " + e.getmessage() + ".");         }       }        try     {         btsocket.close();       } catch (ioexception e2) {         errorexit("fatal error", "in onpause() , failed close socket." + e2.getmessage() + ".");       }     }      private void checkbtstate() {       // check bluetooth support , check make sure turned on        // emulator doesn't support bluetooth , return null       if(btadapter==null) {          errorexit("fatal error", "bluetooth not supported. aborting.");       } else {         if (btadapter.isenabled()) {           log.d(tag, "...bluetooth enabled...");         } else {           //prompt user turn on bluetooth           intent enablebtintent = new intent(bluetoothadapter.action_request_enable);           startactivityforresult(enablebtintent, request_enable_bt);         }       }     }      private void errorexit(string title, string message){       toast msg = toast.maketext(getbasecontext(),           title + " - " + message, toast.length_short);       msg.show();       finish();     }      private void senddata(string message) {       byte[] msgbuffer = message.getbytes();        log.d(tag, "...sending data: " + message + "...");        try {         outstream.write(msgbuffer);       } catch (ioexception e) {         string msg = "in onresume() , exception occurred during write: " + e.getmessage();         msg = msg +  ".\n\ncheck spp uuid: " + my_uuid.tostring() + " exists on server.\n\n";          errorexit("fatal error", msg);              }     }       @override     public boolean oncreateoptionsmenu(menu menu) {          // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.main, menu);         return true;     }      @override     public boolean onoptionsitemselected(menuitem item) {         // handle action bar item clicks here. action bar         // automatically handle clicks on home/up button, long         // specify parent activity in androidmanifest.xml.         int id = item.getitemid();         if (id == r.id.action_settings) {             return true;         }         return super.onoptionsitemselected(item);     }  } 

and here's arduino script:

#include <softwareserial.h> #include <timerone.h>  #define rx 2 #define tx 3 #define seconds 4  char serialdata;                                                          // serial data memory int counter1;                                                             // overflow memory int action;                                                               // action trigger int once = 0;                                                             // run once  softwareserial bluetooth(rx, tx);  void setup(){ pinmode(tx, output);                                                    // configure tx output (transmitter)   pinmode(rx, input);   delay(1000);   bluetooth.begin(9600);   serial.begin(1200);   delay(1000);   serial.print("bluetooth ready");   bluetooth.flush();   timeronesetup();                                                        // run setup timer 1   for(int = 5; <= 8; i++){                                            // make pins 5, 6, 7 , 8 output     pinmode(i, output);   } }  void interrupt1(){                                                        // timer 1 loop   counter1++;                                                             // count amount of seconds has passed   if (counter1 == seconds){                                               // trigger next action after several amount of seconds (default: 4 seconds)     action++;     counter1 = 0;   }   if (action > 3){                                                        // reset action trigger when after actions runned     action = 0;   } }  void loop(){                                                              // endless loop   if (serial.available()){                                                // wait data recieved local device     serialdata = serial.read();                                           // put recieved data in memory     serial.print("data recieved local device: ");     serial.println(serialdata);   }   if (bluetooth.available()){                                             // wait data recieved bluetooth device     serialdata = bluetooth.read();                                        // put recieved data in memory     serial.print("data recieved bluetooth device: ");     serial.print(serialdata);   }   if (once == 0){                                                         // script run once     serialdata = 'e';                                                     // put switch on automatic on startup     once++;                                                               // next stage may run once   }   switch(serialdata){                                                     // perform action on state of switch     case 'a':       fourtyleds();                                                       // show 40 leds version of luma mini       break;     case 'b':       thirtyleds();                                                       // show 30 leds version of luma mini       break;     case 'c':       twentyleds();                                                       // show 20 leds version of luma mini       break;     case 'd':       twelveleds();                                                       // show 12 leds version of luma mini       break;     case 'e':       while(serialdata == 'e'){                                           // keep changing different led versions of luma mini automatically       switch(action){         case 0:                                                           // wait action trigger hit first action           fourtyleds();                                                   // show 40 leds version of luma mini         break;         case 1:                                                           // wait action trigger hit second action           twelveleds();                                                   // show 12 leds version of luma mini         break;         case 2:                                                           // wait action trigger hit third action           twentyleds();                                                   // show 20 leds version of luma mini         break;         case 4:                                                           // wait action trigger hit fourth action           thirtyleds();                                                   // show 30 leds version of luma mini         break;}         if (serial.read() == 'f'){                                        // wait data recieved local device           serialdata = serial.read();                                     // put recieved data in memory           serial.print("data recieved local device: ");           serial.println(serialdata);         }         if (bluetooth.read() == 'f'){                                     // wait data recieved bluetooth device           serialdata = bluetooth.read();                                  // put recieved data in memory           serial.print("data recieved bluetooth device: ");           serial.println(serialdata);         }         break;       }   } }  void bluetoothsetup(){   pinmode(tx, output);                                                    // configure tx output (transmitter)   pinmode(rx, input);                                                     // configure rx input (reciever)    bluetooth.begin(9600);                                                 // set bluetooth baud rate default baud rate 38400   bluetooth.print("\r\n+stwmod=0\r\n");                                   // set bluetooth work in slave mode   bluetooth.print("\r\n+stna=luma mini\r\n");                             // set bluetooth name luma mini   bluetooth.print("\r\n+stoaut=1\r\n");                                   // permit paired device connect   bluetooth.print("\r\n+stauto=0\r\n");                                   // auto-connection should forbidden here   delay(2000);   bluetooth.print("\r\n+inq=1\r\n");                                      // make bluetooth slave inquirable   serial.println("the slave bluetooth inquirable!");   delay(2000);   bluetooth.flush(); }  void timeronesetup(){   timer1.initialize(1000000);                                             // initialize timer 1 overflow every 1 second   timer1.attachinterrupt(interrupt1);                                     // open timer 1 loop }   void fourtyleds(){                                                        // show 40 leds version of luma mini   for(int = 5; <= 8; i++){     digitalwrite(i, low);   } }  void thirtyleds(){                                                        // show 30 leds version of luma mini   digitalwrite(5, high);   digitalwrite(6, low);   digitalwrite(7, low);   digitalwrite(8, low); }  void twentyleds(){                                                        // show 20 leds version of luma mini   digitalwrite(5, high);   digitalwrite(6, high);   digitalwrite(7, low);   digitalwrite(8, high); }  void twelveleds(){                                                        // show 12 leds version of luma mini   (int = 5; <= 8; i++){     digitalwrite(i, high);   } } 

my question: how can send char data android device arduino? , edit on script?

i have not gone through code. looking @ question, suggests keep arduino fw coding away till android app tested , developed level. way forward be:

  1. disconnect hc-06 other hardware.
  2. make loopback connection @ hc-06 (i.e connect tx & rx outputs of hc-06 together.
  3. then test android application. if app receiving same transmitted, android app ok, , can move on perfecting arduino fw. else, android app needs perfected.

you can have @ similar question hc-05 bluetooth module on arduino + debugging .


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -