Transferring data USB - android

I am trying to send and receive data over USB, my device, the Acer Iconia A500 has everything needed to connect to the device and everything, that is fine and works properly, but when I try sending and receiving data it doesn't behave as expected. This is my code
for( ; ; ) { //this is the main loop for transferring
String get = "$getPos";
byte[] getBytes = get.getBytes();
conn.bulkTransfer( epOUT, getBytes, getBytes.length, 500 );
try {
Thread.sleep( 500 );
byte[] buffer = new byte[4096];
conn.bulkTransfer( epIN, buffer, 4096, 500 );
StringBuilder byStr = new StringBuilder();
for( int i = 0; i < buffer.length; i++ ) {
if( buffer[i] != 0 ) {
byStr.append( buffer[i] + ", " );
}
}
l( byStr );
}
catch( InterruptedException e ) {
e.printStackTrace();
}
if( mStop ) {
mStopped = true;
return;
}
l( "sent " + counter );
counter++;
counter = (byte)( counter % 16 );
}
Its meant to return an Array of bytes about 80 characters long but it only returns two bytes back which are 1 and 96, if there was a error on the USB devices end it would still return a few more then two. Is my code even close to correct? I based it of the USB to serial article by serverbox.

I was trying to send data over the wrong baud rate.
Here's the code that works. Posting it for everyone who is using FTDI devices and needs help.
private Runnable mLoop = new Runnable() {
#Override
public void run() {
UsbDevice dev = sDevice;
if (dev == null)
return;
UsbManager usbm = (UsbManager) getSystemService(USB_SERVICE);
UsbDeviceConnection conn = usbm.openDevice(dev);
l("Interface Count: " + dev.getInterfaceCount());
l("Using "
+ String.format("%04X:%04X", sDevice.getVendorId(),
sDevice.getProductId()));
if (!conn.claimInterface(dev.getInterface(0), true))
return;
conn.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
// mConnection.controlTransfer(0×40,
// 0, 1, 0, null, 0,
// 0);//clear Rx
conn.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
conn.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);// flow
// control
// none
conn.controlTransfer(0x40, 0x03, 0x0034, 0, null, 0, 0);// baudrate
// 57600
conn.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);// data bit
// 8, parity
// none,
// stop bit
// 1, tx off
UsbEndpoint epIN = null;
UsbEndpoint epOUT = null;
byte counter = 0;
UsbInterface usbIf = dev.getInterface(0);
for (int i = 0; i < usbIf.getEndpointCount(); i++) {
l("EP: "
+ String.format("0x%02X", usbIf.getEndpoint(i)
.getAddress()));
if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
l("Bulk Endpoint");
if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
epIN = usbIf.getEndpoint(i);
else
epOUT = usbIf.getEndpoint(i);
} else {
l("Not Bulk");
}
}
for (;;) {// this is the main loop for transferring
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String get = "$fDump G" + "\n";
l("Sending: " + get);
byte[] by = get.getBytes();
// This is where it sends
l("out " + conn.bulkTransfer(epOUT, by, by.length, 500));
// This is where it is meant to receive
byte[] buffer = new byte[4096];
StringBuilder str = new StringBuilder();
if (conn.bulkTransfer(epIN, buffer, 4096, 500) >= 0) {
for (int i = 2; i < 4096; i++) {
if (buffer[i] != 0) {
str.append((char) buffer[i]);
} else {
l(str);
break;
}
}
}
// this shows the complete string
l(str);
if (mStop) {
mStopped = true;
return;
}
l("sent " + counter);
counter++;
counter = (byte) (counter % 16);
}
}
};

Related

how to send and divide information into individual textview (Hc 05)

I am trying to make an application that connects to the arduino using the HC 05 module with three ultrasonic sensors. I was able to connect to the application and receive information from a particular sensor. But when I display the distance information of each sensor it is displayed in one text view (I would like three) but I have no idea what I could change in my code. Thanks in advance for your answer. Below I put the code in sequence: from arduino ideas, android studio app, android studio thread
int LtriggerPin = 13;
int LechoPin = 12;
int RtriggerPin = 11;
int RechoPin = 10;
int CtriggerPin = 9;
int CechoPin = 8;
int info = 0;
int state = 0;
void setup() {
Serial1.begin(9600);
pinMode(LtriggerPin, OUTPUT);
pinMode(LechoPin, INPUT);
pinMode(RtriggerPin, OUTPUT);
pinMode(RechoPin, INPUT);
pinMode(CtriggerPin, OUTPUT);
pinMode(CechoPin, INPUT);
}
void loop(){
sensor();
}
void sensor() {
int durationL, distanceL;
int durationR, distanceR;
int durationC, distanceC;
digitalWrite(LtriggerPin, HIGH);
delay(10);
digitalWrite(LtriggerPin, LOW);
durationL = pulseIn(LechoPin, HIGH);
distanceL = (durationL/2) / 29.1;
digitalWrite(RtriggerPin, HIGH);
delay(10);
digitalWrite(RtriggerPin, LOW);
durationR = pulseIn(RechoPin, HIGH);
distanceR = (durationR/2) / 29.1;
digitalWrite(CtriggerPin, HIGH);
delay(10);
digitalWrite(CtriggerPin, LOW);
durationC = pulseIn(CechoPin, HIGH);
distanceC = (durationC/2) / 29.1;
Serial1.print("Left Sensor ");
Serial1.print((String) distanceL + " cm" );
delay(500);
Serial1.println(" ");
Serial1.print("Right Sensor ");
Serial1.print((String) distanceR + " cm" );
delay(500);
Serial1.println(" ");
Serial1.print("Center Sensor ");
Serial1.print((String) distanceC + " cm" );
delay(500);
Serial1.println(" ");
Serial1.println(" ");
Serial1.println(" ");
}
//android thread
#Override
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if(bytes != 0) {
buffer = new byte[1024];
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
hesler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public void write(String input) {
byte[] bytes = input.getBytes();
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
sok.close();
} catch (IOException e) { }
}
// android Handler
handler = new Handler(Looper.getMainLooper()){
#Override
public void handleMessage(Message msg){
if(msg.what == MESSAGE_READ){
String readMessageL = null;
readMessageL = new String((byte[]) msg.obj, StandardCharsets.UTF_8);
TvC.setText(readMessageL);
}
if(msg.what == CONNECTING_STATUS){
char[] sConnected;
if(msg.arg1 == 1)
Tv3.setText(getString(R.string.BTConnected) + msg.obj);
else
Tv3.setText(getString(R.string.BTconnFail));
}
}
};

Why android mediaCodec encode low resolution video slower than high resolution

When I use Android media-codec to encode video to h264 format, I found that encode one frame of 1280 * 720 YUV420P raw image need about 10ms but one frame of 640 * 360 YUV420P raw image need about 100ms.
I have tied on serval mobile with MTK or Qualcomm video encoder, all device perform like that.
Can anyone tell me how to fix my following code to speed up or tell the reason why lower resolution cost more time.
private boolean openH264Encoder(int width, int height, int bitrate) throws TranscodeNativeException {
try {
mediaCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
Log.w(TAG, "codec name " + mediaCodec.getName());
}
for (int i = 0; i < MediaCodecList.getCodecCount(); i++) {
MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
if (codecInfo.isEncoder()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
if (mediaCodec.getName().equalsIgnoreCase(codecInfo.getName())) {
MediaCodecInfo.CodecCapabilities cc = codecInfo.getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_AVC);
for (int c : cc.colorFormats) {
Log.i(TAG, String.format("color format 0x%x", c));
if (MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar == c) {
videoColorFormat = c;
Log.i(TAG, String.format("final color format 0x%x", videoColorFormat));
break;
}
else if (MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar == c) {
videoColorFormat = c;
Log.i(TAG, String.format("find color format 0x%x", videoColorFormat));
}
}
break;
}
}
else {
return false;
}
}
}
if (videoColorFormat == 0) {
Log.e(TAG, "can't find supported color format");
return false;
}
Log.i(TAG, String.format("use color format 0x%x", videoColorFormat));
MediaFormat mediaFormat = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, videoColorFormat);
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 25);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 25);
mediaFormat.setInteger(MediaFormat.KEY_BITRATE_MODE, MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR);
mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mediaCodec.start();
encoderOutputBuffers = mediaCodec.getOutputBuffers();
} catch (Exception e) {
Log.w(TAG, "open h264 encoder failed");
throw new TranscodeNativeException("open h264 encoder failed");
}
return true;
}
public byte[] encodeH264(byte[] data, long ms) {
if (mediaCodec == null)
return null;
if (MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar == videoColorFormat) {
byte[] newData = new byte[data.length];
System.arraycopy(data, 0, newData, 0, data.length * 2 / 3);
for (int i = 0; i < data.length / 6; i++) {
newData[data.length * 2 / 3 + i * 2] = data[data.length * 2 / 3 + i];
newData[data.length * 2 / 3 + i * 2 + 1] = data[data.length * 5 / 6 + i];
}
data = newData;
}
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
try {
ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
int inputBufferIndex = mediaCodec.dequeueInputBuffer(20 * 1000);
if (inputBufferIndex >= 0) {
ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
inputBuffer.clear();
inputBuffer.put(data);
mediaCodec.queueInputBuffer(inputBufferIndex, 0, data.length, ms * 1000, MediaCodec.BUFFER_FLAG_CODEC_CONFIG);
while (true) {
int encoderStatus = mediaCodec.dequeueOutputBuffer(info, -1);
Log.i(TAG, "encoder status " + encoderStatus);
switch (encoderStatus) {
case MediaCodec.INFO_TRY_AGAIN_LATER:
Log.i(TAG, "why tell me try again later?");
return null;
case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED: {
MediaFormat encformat = mediaCodec.getOutputFormat();
Log.i(TAG, "output format changed");
return new byte[0];
}
case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
encoderOutputBuffers = mediaCodec.getOutputBuffers();
Log.i(TAG, "output buffer changed");
continue;
default: {
ByteBuffer encoderOutputBuffer = encoderOutputBuffers[encoderStatus];
if (encoderOutputBuffer == null) {
Log.w(TAG, "output buffer is null");
return null;
}
byte[] outData = new byte[info.size];
encoderOutputBuffer.get(outData);
ByteBuffer byteBuffer = ByteBuffer.wrap(outData);
if (spsppsBuffer == null && (info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
//save sps and pps
if (byteBuffer.getInt() == 0x00000001) {
spsppsBuffer = outData;
}
String d = "";
for (byte i : outData)
d += String.format("0x%02x ", i);
Log.i(TAG, "got sps pps " + d);
mediaCodec.releaseOutputBuffer(encoderStatus, false);
continue;
}
else {
//key frame
if ((outData[4] & 0x1f) == 5) {
byte[] buffer = new byte[outData.length + spsppsBuffer.length];
System.arraycopy(spsppsBuffer, 0, buffer, 0, spsppsBuffer.length);
System.arraycopy(outData, 0, buffer, spsppsBuffer.length, outData.length);
Log.i(TAG, "got key frame");
mediaCodec.releaseOutputBuffer(encoderStatus, false);
return buffer;
}
else {
Log.i(TAG, "got non key frame");
mediaCodec.releaseOutputBuffer(encoderStatus, false);
return outData;
}
}
}
}
}
}
else {
Log.w(TAG, "dequeue input buffer failed, skip one frame");
return new byte[0];
}
}
catch (Exception e) {
e.printStackTrace();
Log.w(TAG, "encode h264 failed");
return null;
}
}

Reading temperature through DHT11 using Android Things

I am using Raspberry pi3 and DHT11 sensor for temperature monitoring project.
I have following pin positions
VCC to pin no : 2
Ground to pin no : 6
Output to GPIO : BCM22 i.e pin no 15
Code that I have used:
public class WeatherStationActivity extends Activity {
private Handler mHandler = new Handler();
private TextView mTxtStatus;
private PeripheralManagerService service = new PeripheralManagerService();
private Gpio tempGpio;
private int i = 0;
int[] dht11_dat = {0, 0, 0, 0, 0};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Weather station", "Started Weather Station");
setContentView(R.layout.activity_main);
mTxtStatus = (TextView) findViewById(R.id.txtStatus);
try {
tempGpio = service.openGpio("BCM22");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (i == 10) {
handler.removeCallbacks(this);
} else {
getTemp();
handler.postDelayed(this, 5000);
}
i++;
}
}, 5000);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getTemp() {
boolean laststate = false;
try {
laststate = tempGpio.getValue();
} catch (IOException e) {
e.printStackTrace();
}
int j = 0;
final int MAXTIMINGS = 85;
dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
try {
tempGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
// tempGpio.setActiveType(Gpio.ACTIVE_LOW);
tempGpio.setValue(false);
// Thread.sleep(18);
TimeUnit.MILLISECONDS.sleep(18);
// tempGpio.setActiveType(Gpio.ACTIVE_HIGH);
// tempGpio.setActiveType(Gpio.ACTIVE_HIGH);
tempGpio.setValue(true);
TimeUnit.MICROSECONDS.sleep(40);
tempGpio.setDirection(Gpio.DIRECTION_IN);
/* tempGpio.setActiveType(Gpio.ACTIVE_HIGH);
tempGpio.setValue(true);*/
// tempGpio.setValue(true);
StringBuilder value = new StringBuilder();
for (int i = 0; i < MAXTIMINGS; i++) {
int counter = 0;
while (tempGpio.getValue() == laststate) {
counter++;
TimeUnit.MICROSECONDS.sleep(1);
if (counter == 255) {
break;
}
}
laststate = tempGpio.getValue();
mTxtStatus.append("\nLast State of Sensor " + laststate);
if (counter == 255) {
break;
}
//* ignore first 3 transitions *//*
if ((i >= 4) && (i % 2 == 0)) {
//* shove each bit into the storage bytes *//*
dht11_dat[j / 8] <<= 1;
if (counter > 16) {
dht11_dat[j / 8] |= 1;
}
j++;
}
}
// check we read 40 bits (8bit x 5 ) + verify checksum in the last
// byte
if ((j >= 40) && checkParity()) {
value.append(dht11_dat[2]).append(".").append(dht11_dat[3]);
Log.i("Logger", "temperature value readed: " + value.toString());
mTxtStatus.append("\nTemp " + value.toString());
} else {
mTxtStatus.append("\nNothing is working ");
Log.i("Logger", "Nothing is working ");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean checkParity() {
return dht11_dat[4] == (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3] & 0xFF);
}
}
Above code is giving me "Nothing is working" as output.
Any suggestion where I might be doing wrong?
You can't read data from DHT11 using Raspberry Pi 3 with Android Things because duration of DHT11 response pulses is from 26-28 us to 70 us, but max frequency of RP3 with AT GPIO is around 3kHz, which means around 300 us pulse duration. Take a look at answers to this question.

Serial to USB Android application with health device

I am creating an Android application to let communicate my Galaxy Tablet with an health device, via serial to USB connection.
The code I implemented does not work! neither the OUT nor IN communication starts
Does someone has any idea?
public void recordData(View _view){
text = (TextView)findViewById(R.id.textView1);
manager=(UsbManager) getSystemService(Context.USB_SERVICE);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
manager.requestPermission(device, mPermissionIntent);
text.setText(text.getText()+"\n"+device.getDeviceName());
}
}
private UsbManager manager=null;
private boolean forceClaim = true;
private UsbDeviceConnection connection;
private UsbEndpoint input = null,output=null;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
isRecording=true;
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
//call method to set up device communication
UsbInterface intf = device.getInterface(0);
connection = manager.openDevice(device);
connection.claimInterface(intf, forceClaim);
//connection settings
int op= connection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset //0x40
int op2= connection.controlTransfer(0x40, 0, 1, 0, null, 0, 0);//clear Rx
int op3= connection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
int op3b= connection.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);//control flow
int op4= connection.controlTransfer(0x40, 0x03, 0x001A, 0, null, 0, 0);// baud rate 115200
int op5= connection.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);//8 bit
int endPts = intf.getEndpointCount();
for(int e = 0; e < endPts; e++){
UsbEndpoint endpoint = intf.getEndpoint(e);
endpoint.getAttributes();
if( endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK){
if(endpoint.getDirection() == UsbConstants.USB_DIR_IN){
input = endpoint;
Log.d("Endpoint", "Got input");
}else if(endpoint.getDirection() == UsbConstants.USB_DIR_OUT){
output = endpoint;
Log.d("Endpoint", "Got output");
}
}
}
text.setText(text.getText()+"\nOut= "+String.valueOf(output.getEndpointNumber()));
text.setText(text.getText()+"\nIn= "+String.valueOf(input.getEndpointNumber()));
byte [] buffer = {77}; // M\n in ascii
for (int i = 0; i < buffer.length; ++i)
{
connection.bulkTransfer(output, new byte[] {buffer[i]}, 1, 0);
}
read();
}
}
else {
//error
}
}
}
}
};
//read thread
private void read() {
Runnable r = new Runnable() {
byte[] buffer = new byte[64];
byte[] buffer2;
public void run() {
while (isRecording) {
{
int op = connection.bulkTransfer(input, buffer, 64, 0);
if (op > 2) {
buffer2 = new byte[op];
for (int i = 0; i < op - 2; ++i) {
buffer2[i] = buffer[i+2];
text.setText(text.getText()+"\n"+String.valueOf(buffer2[i]));
}
}
}
}
}
};
Thread t = new Thread(r);
t.start();
Thank you very much!
Before trying to send the bytes you have to control the transaction first:
Use:
// for writing to USB with 9600 baudrate
connection.controlTransfer(0x00000000, 0x03, 0x4138, 0, null, 0, 0);
and
// for reading from USB with 9600 baudrate
connection.controlTransfer(0x00000080, 0x03, 0x4138, 0, null, 0, 0);
Reference:
http://developer.android.com/guide/topics/connectivity/usb/host.html
http://developer.android.com/reference/android/hardware/usb/UsbConstants.html

Data transfer from USB(prolific) to android device

I found a question posted for reading of USB data for FTDI devices.
Transferring data USB
I used this code for prolific device, and the usb can be detected, etc except that the the conn.bulkTransfer() gives a -1.
private class UsbRunnable implements Runnable {
private final UsbDevice mDevice;
UsbRunnable(UsbDevice dev) {
mDevice = dev;
}
public void run() {//here the main USB functionality is implemented
UsbDeviceConnection conn = mUsbManager.openDevice(mDevice);
if (!conn.claimInterface(mDevice.getInterface(1), true)) {
l("in run(), no connection");
return;
}
l("in run(), connection");
conn.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
// mConnection.controlTransfer(0×40,
// 0, 1, 0, null, 0,
// 0);//clear Rx
conn.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
conn.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);// flow
// control
// none
conn.controlTransfer(0x40, 0x03, 0xC04E, 0, null, 0, 0);// baudrate
// 38400
conn.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);// data bit
// 8, parity
// none,
// stop bit
// 1, tx off
UsbEndpoint epIN = null;
UsbEndpoint epOUT = null;
byte counter=0;
//conn.bulkTransfer(epOUT, new byte[]{msData}, 1, 0);
UsbInterface usbIf = mDevice.getInterface(0);
for (int i = 0; i < usbIf.getEndpointCount(); i++) {
l("EP: "
+ String.format("0x%02X", usbIf.getEndpoint(i)
.getAddress()));
l("Type:"+usbIf.getEndpoint(i).getType());
if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_INT) {
l("Bulk Endpoint");
l("direction: "+usbIf.getEndpoint(i).getDirection());
if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
epIN = usbIf.getEndpoint(i);
}
else l("no bulk");
l("epIN: "+epIN.toString());
}
for (;;) {// this is the main loop for transferring
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// This is where it is meant to receive
byte[] buffer = new byte[38400];
StringBuilder str = new StringBuilder();
l("bulk transfer thing: " + conn.bulkTransfer(epIN, buffer, 38400, 1000));
if (conn.bulkTransfer(epIN, buffer, 38400, 1000) > 0 ) {
l("bulk transfer is success");
for (int i = 2; i < 64; i++) {
if (buffer[i] != 0) {
str.append((char) buffer[i]);
} else {
l(str);
break;
}
}
}
// this shows the complete string
l(str);
if (mStop) {
mConnectionHandler.onUsbStopped();
return;
}
l("sent " + counter);
counter++;
counter = (byte) (counter % 16);
}
}
}
// END MAIN LOOP
private BroadcastReceiver mPermissionReceiver = new PermissionReceiver(
new IPermissionListener() {
public void onPermissionDenied(UsbDevice d) {
l("Permission denied on " + d.getDeviceId());
}
});
private static interface IPermissionListener {
void onPermissionDenied(UsbDevice d);
}
public final static String TAG = "USBController";
private void l(Object msg) {
Log.d(TAG, ">==< " + msg.toString() + " >==<");
}
private void e(Object msg) {
Log.e(TAG, ">==< " + msg.toString() + " >==<");
}
Can anyone tell me what changes I need to make? Thank you in advance.
There are several issues.
I assume that the commented out line is where you're having problems. You may want to reformat your code indentation and supply more information. In any case, assuming that your issue is occurring here:
byte counter=0;
//conn.bulkTransfer(epOUT, new byte[]{msData}, 1, 0);
The immediate problem that I see - epOut, the endpoint to which you are sending data is null. So of course it will fail. You're sending data to nothing. I followed the link that you posted to the example code that you copied, they have a line showing:
epOUT = usbIf.getEndpoint(i);
I would strongly suggest at the very least, you first make sure you understand the original code or have it working in your own program before you start making changes. DON'T just copy the above line of code to "fix" your problem.

Categories

Resources