sockets - How to send character from android phone to arduino through Bluetooth? -
currently using arduino nano receive data , transmit android phone through bluetooth. want set button on smart phone, , after pressed it, transmit character arduino. have tested arduino if give command in serial monitor , give me analog read signal.
i wanna ask how can transmit character(like "e") phone arduino? following code associated bluetooth connection. else can add achieve goal?
bluetooth code in arduino
public class homescreen extends activity { private button mbtnsearch; private button mbtnconnect; private listview mlstdevices; private bluetoothadapter mbtadapter; private static final int bt_enable_request = 10; // code use bt enable private static final int settings = 20; private uuid mdeviceuuid = uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb"); // standard spp uuid // (http://developer.android.com/reference/android/bluetooth/bluetoothdevice.html#createinsecurerfcommsockettoservicerecord%28java.util.uuid%29) private int mbuffersize = 50000; //default public static final string device_extra = "com.blueserial.socket"; public static final string device_uuid = "com.blueserial.uuid"; private static final string device_list = "com.blueserial.devicelist"; private static final string device_list_selected = "com.blueserial.devicelistselected"; public static final string buffer_size = "com.blueserial.buffersize"; private static final string tag = "bluetest5-homescreen"; public string isecg; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_homescreen); activityhelper.initialize(this); //this ensure rotation persists across activities , not 1 log.d(tag, "created"); intent = getintent(); if (i.hasextra("isecg")){ isecg = i.getstringextra("isecg"); } textview tv1 = (textview)findviewbyid(r.id.tv1); tv1.settext(isecg); mbtnsearch = (button) findviewbyid(r.id.btnsearch); mbtnconnect = (button) findviewbyid(r.id.btnconnect); mlstdevices = (listview) findviewbyid(r.id.lstdevices); button btback = (button) findviewbyid(r.id.btback); btback.setonclicklistener(new button.onclicklistener() { @override public void onclick(view v) { intent intent = new intent(); intent.setclass(homescreen.this, startscreen.class); startactivity(intent); } }); /* *check if there savedinstancestate. if yes, means oncreate triggered configuration change *like screen rotate etc. if that's case populate views necessary here */ if (savedinstancestate != null) { arraylist<bluetoothdevice> list = savedinstancestate.getparcelablearraylist(device_list); if(list!=null){ initlist(list); myadapter adapter = (myadapter)mlstdevices.getadapter(); int selectedindex = savedinstancestate.getint(device_list_selected); if(selectedindex != -1){ adapter.setselectedindex(selectedindex); mbtnconnect.setenabled(true); } } else { initlist(new arraylist<bluetoothdevice>()); } } else { initlist(new arraylist<bluetoothdevice>()); } mbtnsearch.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { mbtadapter = bluetoothadapter.getdefaultadapter(); if (mbtadapter == null) { toast.maketext(getapplicationcontext(), "bluetooth not found", toast.length_short).show(); } else if (!mbtadapter.isenabled()) { intent enablebt = new intent(bluetoothadapter.action_request_enable); startactivityforresult(enablebt, bt_enable_request); } else { new searchdevices().execute(); } } }); mbtnconnect.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { bluetoothdevice device = ((myadapter) (mlstdevices.getadapter())).getselecteditem(); intent intent = new intent(getapplicationcontext(), mainactivity.class); intent.putextra(device_extra, device); intent.putextra(device_uuid, mdeviceuuid.tostring()); intent.putextra(buffer_size, mbuffersize); intent.putextra("isecg", isecg); intent.setclass(homescreen.this, mainactivity.class); startactivity(intent); } }); } /** * called when screen rotates. if isn't handled, data generated no longer available */ @override protected void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); myadapter adapter = (myadapter) (mlstdevices.getadapter()); arraylist<bluetoothdevice> list = (arraylist<bluetoothdevice>) adapter.getentirelist(); if (list != null) { outstate.putparcelablearraylist(device_list, list); int selectedindex = adapter.selectedindex; outstate.putint(device_list_selected, selectedindex); } } @override protected void onpause() { // todo auto-generated method stub super.onpause(); } @override protected void onstop() { // todo auto-generated method stub super.onstop(); } @override protected void onactivityresult(int requestcode, int resultcode, intent data) { switch (requestcode) { case bt_enable_request: if (resultcode == result_ok) { msg("bluetooth enabled successfully"); new searchdevices().execute(); } else { msg("bluetooth couldn't enabled"); } break; case settings: //if settings have been updated sharedpreferences prefs = preferencemanager.getdefaultsharedpreferences(this); string uuid = prefs.getstring("prefuuid", "null"); mdeviceuuid = uuid.fromstring(uuid); log.d(tag, "uuid: " + uuid); string bufsize = prefs.getstring("preftextbuffer", "null"); mbuffersize = integer.parseint(bufsize); string orientation = prefs.getstring("preforientation", "null"); log.d(tag, "orientation: " + orientation); if (orientation.equals("landscape")) { setrequestedorientation(activityinfo.screen_orientation_landscape); } else if (orientation.equals("portrait")) { setrequestedorientation(activityinfo.screen_orientation_portrait); } else if (orientation.equals("auto")) { setrequestedorientation(activityinfo.screen_orientation_full_sensor); } break; default: break; } super.onactivityresult(requestcode, resultcode, data); } /** * quick way call toast * @param str */ private void msg(string str) { toast.maketext(getapplicationcontext(), str, toast.length_short).show(); } /** * initialize list adapter * @param objects */ private void initlist(list<bluetoothdevice> objects) { final myadapter adapter = new myadapter(getapplicationcontext(), r.layout.list_item, r.id.lstcontent, objects); mlstdevices.setadapter(adapter); mlstdevices.setonitemclicklistener(new onitemclicklistener() { @override public void onitemclick(adapterview<?> parent, view view, int position, long id) { adapter.setselectedindex(position); mbtnconnect.setenabled(true); } }); } /** * searches paired devices. doesn't scan! devices paired through settings->bluetooth * show this. didn't see need re-build wheel on here * @author ryder * */ private class searchdevices extends asynctask<void, void, list<bluetoothdevice>> { @override protected list<bluetoothdevice> doinbackground(void... params) { set<bluetoothdevice> paireddevices = mbtadapter.getbondeddevices(); list<bluetoothdevice> listdevices = new arraylist<bluetoothdevice>(); (bluetoothdevice device : paireddevices) { listdevices.add(device); } return listdevices; } @override protected void onpostexecute(list<bluetoothdevice> listdevices) { super.onpostexecute(listdevices); if (listdevices.size() > 0) { myadapter adapter = (myadapter) mlstdevices.getadapter(); adapter.replaceitems(listdevices); } else { msg("no paired devices found, please pair serial bt device , try again"); } } } /** * custom adapter show current devices in list. bit of overkill * project, figured learning * of code lifted somewhere can't find link anymore * @author ryder * */ private class myadapter extends arrayadapter<bluetoothdevice> { private int selectedindex; private context context; private int selectedcolor = color.parsecolor("#abcdef"); private list<bluetoothdevice> mylist; public myadapter(context ctx, int resource, int textviewresourceid, list<bluetoothdevice> objects) { super(ctx, resource, textviewresourceid, objects); context = ctx; mylist = objects; selectedindex = -1; } public void setselectedindex(int position) { selectedindex = position; notifydatasetchanged(); } public bluetoothdevice getselecteditem() { return mylist.get(selectedindex); } @override public int getcount() { return mylist.size(); } @override public bluetoothdevice getitem(int position) { return mylist.get(position); } @override public long getitemid(int position) { return position; } private class viewholder { textview tv; } public void replaceitems(list<bluetoothdevice> list) { mylist = list; notifydatasetchanged(); } public list<bluetoothdevice> getentirelist() { return mylist; } @override public view getview(int position, view convertview, viewgroup parent) { view vi = convertview; viewholder holder; if (convertview == null) { vi = layoutinflater.from(context).inflate(r.layout.list_item, null); holder = new viewholder(); holder.tv = (textview) vi.findviewbyid(r.id.lstcontent); vi.settag(holder); } else { holder = (viewholder) vi.gettag(); } if (selectedindex != -1 && position == selectedindex) { holder.tv.setbackgroundcolor(selectedcolor); } else { holder.tv.setbackgroundcolor(color.white); } bluetoothdevice device = mylist.get(position); holder.tv.settext(device.getname() + "\n " + device.getaddress()); return vi; } } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.homescreen, menu); return true; }
}
in android code have these global variables:
bluetoothadapter mbluetoothadapter; bluetoothsocket mmsocket; bluetoothdevice mmdevice; outputstream mmoutputstream; inputstream mminputstream;
and paired bluetooth devices in similar way did:
@override protected list<bluetoothdevice> doinbackground(void... params) { set<bluetoothdevice> paireddevices = mbtadapter.getbondeddevices(); list<bluetoothdevice> listdevices = new arraylist<bluetoothdevice>(); (bluetoothdevice device : paireddevices) { listdevices.add(device); } return listdevices; }
then when select correct bluetooth device, set equal mmdevice:
mmdevice = device;
then use method open bluetooth connection:
void openbt() throws ioexception{ uuid uuid = uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb"); //standard serialportservice id mmsocket = mmdevice.createrfcommsockettoservicerecord(uuid); mmsocket.connect(); mmoutputstream = mmsocket.getoutputstream(); mminputstream = mmsocket.getinputstream(); //optional system.out.println("bluetooth opened"); toast.maketext(getapplicationcontext(), "bluetooth opened", toast.length_short).show(); }
the mmoutputstream sends data bluetooth module , mminputstream reads incoming data bluetooth module. have method send data bluetooth module:
void senddata(string m) throws ioexception{ string msg = m; mmoutputstream.write(msg.getbytes()); system.out.println("data sent"); }
this converts string bytes , sends arduino. on arduino side, can either say
if(bluetooth.available()) { char c = bluetooth.read(); serial.println(c); }
if reading single char or say:
if(bluetooth.available()) { int data = bluetooth.parseint(); serial.println(data); }
to read integer value sent on bluetooth. hope helps. if need anything, don't hesitate ask.
Comments
Post a Comment