java - Same serial port code is functioning differently in different activites -
so i'm writing app reads reads in data serial port. data coming in arduino connected force transducer - essentially, app meant measure weight of something. found serial port code here: https://www.allaboutcircuits.com/projects/communicate-with-your-arduino-through-android/, , i'm using in multiple different activities (since need activity calibration, activity actual measuring, etc.). problem same exact serial port code working in 1 activity , not working in another. works in activity, example:
public class enterdataactivity extends appcompatactivity { private static final long timer_delay = 5000; private static final long timer_length = 15000; edittext entermax, entermin; button submitmax, submitmin, continuebutton; chronometer emptybagtimer; boolean firstmeasure, getemptybagdata, canentermax, canentermin; arraylist<string> emptybagdata; float maxload, minload; // serial port variables: public final string action_usb_permission = "com.example.jake.usb_permission"; usbmanager usbmanager; usbdevice device; usbserialdevice serialport; usbdeviceconnection connection; usbserialinterface.usbreadcallback mcallback = new usbserialinterface.usbreadcallback() { //defining callback triggers whenever data read. @override public void onreceiveddata(byte[] arg0) { string data; try { data = new string(arg0, "utf-8"); if(getemptybagdata) emptybagdata.add(data); } catch (unsupportedencodingexception e) {} } }; private final broadcastreceiver broadcastreceiver = new broadcastreceiver() { //broadcast receiver automatically start , stop serial connection. @override public void onreceive(context context, intent intent) { if (intent.getaction().equals(action_usb_permission)) { boolean granted = intent.getextras().getboolean(usbmanager.extra_permission_granted); if (granted) { connection = usbmanager.opendevice(device); serialport = usbserialdevice.createusbserialdevice(device, connection); if (serialport != null) { if (serialport.open()) { //set serial connection parameters. serialport.setbaudrate(9600); serialport.setdatabits(usbserialinterface.data_bits_8); serialport.setstopbits(usbserialinterface.stop_bits_1); serialport.setparity(usbserialinterface.parity_none); serialport.setflowcontrol(usbserialinterface.flow_control_off); serialport.read(mcallback); } else { log.d("serial", "port not open"); } } else { log.d("serial", "port null"); } } else { log.d("serial", "perm not granted"); } } else if (intent.getaction().equals(usbmanager.action_usb_device_attached)) { start(); } else if (intent.getaction().equals(usbmanager.action_usb_device_detached)) { stop(); } } }; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_enter_data); usbmanager = (usbmanager) getsystemservice(usb_service); intentfilter filter = new intentfilter(); filter.addaction(action_usb_permission); filter.addaction(usbmanager.action_usb_device_attached); filter.addaction(usbmanager.action_usb_device_detached); registerreceiver(broadcastreceiver, filter); entermax = (edittext) findviewbyid(r.id.entermax); entermin = (edittext) findviewbyid(r.id.entermin); submitmax = (button) findviewbyid(r.id.submitmax); submitmin = (button) findviewbyid(r.id.submitmin); continuebutton = (button) findviewbyid(r.id.continuebutton); emptybagtimer = (chronometer) findviewbyid(r.id.emptybagtimer); firstmeasure = true; getemptybagdata = false; canentermax = true; canentermin = true; emptybagdata = new arraylist<>(); start(); } // method: measureemptybag // description: method called when button measure mass of empty bag // pressed. starts chronometer , serial port, first waiting timer_delay milliseconds // button press, sets boolean true causes serial data added // arraylist on next timer_length milliseconds. sets next views in // enter data process visible. firstmeasure boolean prevent spamming. public void measureemptybag(view view){ if(firstmeasure) { firstmeasure = false; start(); emptybagtimer.setbase(systemclock.elapsedrealtime()); emptybagtimer.start(); emptybagtimer.setformat("waiting - %s"); emptybagtimer.setonchronometerticklistener(new chronometer.onchronometerticklistener() { @override public void onchronometertick(chronometer chronometer) { if (systemclock.elapsedrealtime() - emptybagtimer.getbase() <= timer_delay) emptybagtimer.setformat("waiting - %s"); else if (systemclock.elapsedrealtime() - emptybagtimer.getbase() <= timer_delay + timer_length) { emptybagtimer.setformat("calculating - %s"); getemptybagdata = true; } else if (systemclock.elapsedrealtime() - emptybagtimer.getbase() > timer_delay + timer_length) { getemptybagdata = false; emptybagtimer.stop(); entermax.setvisibility(view.visible); submitmax.setvisibility(view.visible); } else emptybagtimer.setformat("waiting - %s"); } }); } } // method: setmaxload // description: called when submit button pressed max load, method trys // pull max load value edit text , store it. if successful (the user has // entered in number) sets next views in enter data process visible. public void setmaxload(view view){ if(canentermax){ try { canentermax = false; maxload = float.parsefloat(entermax.gettext().tostring()); entermin.setvisibility(view.visible); submitmin.setvisibility(view.visible); } catch (exception e) {} // in case user enters non number } } // method: setminload // description: called when submit button pressed min load, method trys // pull min load value edit text , store it. if successful (the user has // entered in number) sets next view in enter data process visible. public void setminload(view view){ if(canentermin){ try { canentermin = false; minload = float.parsefloat(entermin.gettext().tostring()); continuebutton.setvisibility(view.visible); } catch (exception e) {} // in case user enters non number } } // method: continuepressed // description: method called when continue button pressed. averages of // data read in on measure empty mass period find mass when empty, writes // value along maxload , minload file later use. starts pump // activity public void continuepressed(view view){ int emptymasssum = 0; int emptymass; // cleaning emptybagdata include 3,2, or 1 digit numbers (the serial output gets // wonky , spits out weird numbers throw off calculations below, // numbers need removed) (int = emptybagdata.size() - 1; >= 0; i--) if (emptybagdata.get(i).length() != 3) emptybagdata.remove(i); // add values in emptybagdata (try catch in case non-number read in) (int = emptybagdata.size() - 1; >= 0; i--) { try { emptymasssum += integer.parseint(emptybagdata.get(i)); } catch (exception e) { emptybagdata.remove(i); } } emptymass = emptymasssum / emptybagdata.size(); fileoutputstream outputstream; string dataout = "e" + emptymass + "mx" + maxload + "mn" + minload + ";"; try { outputstream = openfileoutput("bagdata.txt", context.mode_private); outputstream.write(dataout.getbytes()); outputstream.close(); } catch (exception e) { continuebutton.settext(r.string.file_write_error_message); } intent intent = new intent(this, pumpactivity.class); startactivity(intent); } // serial port methods: public void start() { hashmap<string, usbdevice> usbdevices = usbmanager.getdevicelist(); if (!usbdevices.isempty()) { boolean keep = true; (map.entry<string, usbdevice> entry : usbdevices.entryset()) { device = entry.getvalue(); int devicevid = device.getvendorid(); if (devicevid == 10755 || devicevid == 9025)//arduino vendor id { pendingintent pi = pendingintent.getbroadcast(this, 0, new intent(action_usb_permission), 0); usbmanager.requestpermission(device, pi); keep = false; } else { connection = null; device = null; } if (!keep) break; } } } public void stop() { if(serialport!=null) serialport.close(); } } by "it works", mean can data coming in serial port , use it. however, same code not work here:
public class pumpactivity extends appcompatactivity { file calibrationdata, bagdata; int mass1, mass2, read1, read2, emptymassnum; float maxload, minload; double slope, currentmassval, emptymass; boolean status, runtimer; textview statustextview, currentmasstextview; button stop; thread updatemass; arraylist<string> indata; // 2 things when handlemessage method called: // 1) takes recent data read in , calculates current mass it, updates // current mass text view reflect // 2) takes newly calculated mass , sees if status should change, depending on how // mass there is. writes value serial port (back arduino) // depending on status. updates status text view reflect handler updatemasshandler = new handler(){ public void handlemessage(message msg){ // mass calculation try{currentmassval = calculatemass(integer.parseint(indata.get(indata.size()-1)));} catch (exception e){} // try-catch in case data isn't int indata.clear(); currentmasstextview.settext(string.format(getresources().getstring(r.string.current_mass_string), currentmassval)); // status check new mass if (currentmassval >= maxload) status = true; else if (currentmassval <= minload) status = false; statustextview.settext(string.format(getresources().getstring(r.string.pump_status), getstatus())); // writing arduino if (serialport != null) { if (status) serialport.write("1".getbytes()); else serialport.write("0".getbytes()); } } }; // serial port variables: public final string action_usb_permission = "com.example.jake.usb_permission"; usbmanager usbmanager; usbdevice device; usbserialdevice serialport; usbdeviceconnection connection; usbserialinterface.usbreadcallback mcallback = new usbserialinterface.usbreadcallback() { //defining callback triggers whenever data read. @override public void onreceiveddata(byte[] arg0) { string data; try { data = new string(arg0, "utf-8"); indata.add(data); } catch (unsupportedencodingexception e) {} } }; private final broadcastreceiver broadcastreceiver = new broadcastreceiver() { //broadcast receiver automatically start , stop serial connection. @override public void onreceive(context context, intent intent) { if (intent.getaction().equals(action_usb_permission)) { boolean granted = intent.getextras().getboolean(usbmanager.extra_permission_granted); if (granted) { connection = usbmanager.opendevice(device); serialport = usbserialdevice.createusbserialdevice(device, connection); if (serialport != null) { if (serialport.open()) { //set serial connection parameters. serialport.setbaudrate(9600); serialport.setdatabits(usbserialinterface.data_bits_8); serialport.setstopbits(usbserialinterface.stop_bits_1); serialport.setparity(usbserialinterface.parity_none); serialport.setflowcontrol(usbserialinterface.flow_control_off); serialport.read(mcallback); } else { log.d("serial", "port not open"); } } else { log.d("serial", "port null"); } } else { log.d("serial", "perm not granted"); } } else if (intent.getaction().equals(usbmanager.action_usb_device_attached)) { start(); } else if (intent.getaction().equals(usbmanager.action_usb_device_detached)) { stop(); } } }; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_pump); usbmanager = (usbmanager) getsystemservice(usb_service); intentfilter filter = new intentfilter(); filter.addaction(action_usb_permission); filter.addaction(usbmanager.action_usb_device_attached); filter.addaction(usbmanager.action_usb_device_detached); registerreceiver(broadcastreceiver, filter); status = false; statustextview = (textview) findviewbyid(r.id.statustextview); statustextview.settext(string.format(getresources().getstring(r.string.pump_status), getstatus())); currentmasstextview = (textview) findviewbyid(r.id.currentmasstextview); currentmasstextview.settext(r.string.calculating_text); stop = (button) findviewbyid(r.id.stopbutton); runtimer = true; currentmassval = 0; indata = new arraylist<>(); // thread "calls" handlemessage method in updatemasshandler every 100 milliseconds updatemass = new thread(new runnable() { @override public void run() { while(runtimer){ updatemasshandler.sendemptymessage(0); try{thread.sleep(100);} catch (interruptedexception e){} } } }); // stackoverflow file reading code // reading , parsing calibration data calibrationdata = new file(getfilesdir(), "calibrationdata.txt"); stringbuilder text = new stringbuilder(); // reading in calibration data file (of same name) try { bufferedreader br = new bufferedreader(new filereader(calibrationdata)); string line; while ((line = br.readline()) != null) { text.append(line); text.append('\n'); } br.close(); } catch (ioexception e) {} // parsing values calibration data string calibdata = text.tostring(); calibdata = calibdata.substring(3); mass1 = integer.parseint(calibdata.substring(0, calibdata.indexof('r'))); calibdata = calibdata.substring(calibdata.indexof(':') + 1); read1 = integer.parseint(calibdata.substring(0, calibdata.indexof('m'))); calibdata = calibdata.substring(calibdata.indexof(':') + 1); mass2 = integer.parseint(calibdata.substring(0, calibdata.indexof('r'))); calibdata = calibdata.substring(calibdata.indexof(':') + 1); read2 = integer.parseint(calibdata.substring(0, calibdata.indexof('.'))); slope = ((double) (mass2 - mass1) / (read2 - read1)); // calculating slope of masses , reads allow // calculation of mass of unknown read // reading , parsing bag data bagdata = new file(getfilesdir(), "bagdata.txt"); stringbuilder text2 = new stringbuilder(); // reading in bag data file (of same name) try { bufferedreader br = new bufferedreader(new filereader(bagdata)); string line; while ((line = br.readline()) != null) { text2.append(line); text2.append('\n'); } br.close(); } catch (ioexception e) {} // parsing values frm bag data string bagdata = text2.tostring(); bagdata = bagdata.substring(1); emptymassnum = integer.parseint(bagdata.substring(0, bagdata.indexof('m'))); bagdata = bagdata.substring(bagdata.indexof('x') + 1); maxload = float.parsefloat(bagdata.substring(0, bagdata.indexof('m'))); bagdata = bagdata.substring(bagdata.indexof('n') + 1); minload = float.parsefloat(bagdata.substring(0, bagdata.indexof(';'))); emptymass = calculatemass(emptymassnum); // emptymassnum values read in arduino // converts mass updatemass.start(); start(); } // method: calculatemass // description: calculates mass of object on transducer based off of value read // in , data gotten calibration // input: int readval - value read in // output: double - calculated mass public double calculatemass(int readval){ return (slope * (readval-read1)) + mass1; } // method: getstatus // description: returns string representation of status public string getstatus(){ if(status) return "running"; else return "stopped"; } // method: stop // description: stops when stop button pressed public void stop(view view){ status = false; runtimer = false; stop(); stop.settext(r.string.button_stopped); } // serial port methods: public void start() { hashmap<string, usbdevice> usbdevices = usbmanager.getdevicelist(); if (!usbdevices.isempty()) { boolean keep = true; (map.entry<string, usbdevice> entry : usbdevices.entryset()) { device = entry.getvalue(); int devicevid = device.getvendorid(); if (devicevid == 10755 || devicevid == 9025)//arduino vendor id { pendingintent pi = pendingintent.getbroadcast(this, 0, new intent(action_usb_permission), 0); usbmanager.requestpermission(device, pi); keep = false; } else { connection = null; device = null; } if (!keep) break; } } } public void stop() { if(serialport!=null) serialport.close(); } } for reason, onreceiveddata method in mcallback variable not seem called in second activity (the 1 not working). i'm pretty sure problem, i'm not sure why being called in 1 activity , not in same code. if method not called, can't access data coming in, problem.
also, here's manifest:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.stylosa.hangingtransducer"> <uses-feature android:name="android.hardware.usb.host" /> <uses-permission android:name="android.permission.write_external_storage" /> <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundicon="@mipmap/ic_launcher_round" android:supportsrtl="true" android:theme="@style/apptheme"> <activity android:name=".mainactivity"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> <intent-filter> <action android:name="android.hardware.usb.action.usb_device_attached" /> </intent-filter> <intent-filter> <action android:name="android.hardware.usb.action.usb_device_detached" /> </intent-filter> </activity> <activity android:name=".calibrateactivity"> <intent-filter> <action android:name="android.hardware.usb.action.usb_device_attached" /> </intent-filter> <intent-filter> <action android:name="android.hardware.usb.action.usb_device_detached" /> </intent-filter> </activity> <activity android:name=".inputactivity" android:parentactivityname=".mainactivity"> <intent-filter> <action android:name="android.hardware.usb.action.usb_device_attached" /> </intent-filter> <intent-filter> <action android:name="android.hardware.usb.action.usb_device_detached" /> </intent-filter> </activity> <activity android:name=".enterdataactivity"> <intent-filter> <action android:name="android.hardware.usb.action.usb_device_attached" /> </intent-filter> <intent-filter> <action android:name="android.hardware.usb.action.usb_device_detached" /> </intent-filter> </activity> <activity android:name=".pumpactivity"> <intent-filter> <action android:name="android.hardware.usb.action.usb_device_attached" /> </intent-filter> <intent-filter> <action android:name="android.hardware.usb.action.usb_device_detached" /> </intent-filter> </activity> </application> any , appreciated!
Comments
Post a Comment