Connect Android to Rambo using USB - android

I try to connect my archos Titanium HD to my RAMBo (http://reprap.org/wiki/Rambo). At the moment i can connect to the device and I find the USB_DIR_IN but when i Read from the connection i get null. What am I doing wrong?
public void onReceive(Context context, Intent intent) {
EditText myfield = (EditText) findViewById(R.id.editText1);
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
myfield.setText(myfield.getText()+"start connection");
UsbInterface intf = device.getInterface(0);
UsbManager mUsbManager=(UsbManager) getSystemService(Context.USB_SERVICE);
UsbDeviceConnection connection = mUsbManager.openDevice(device);
if(connection.claimInterface(intf, forceClaim)){
for(int i=0;i<intf.getEndpointCount();i++){
UsbEndpoint endpoint = intf.getEndpoint(i);
if(endpoint.getDirection()== UsbConstants.USB_DIR_IN){
myfield.setText(myfield.getText()+"endpoint zum lesen:"+i);
int ret=connection.bulkTransfer(endpoint, mybytes, 20, TIMEOUT);
myfield.setText(myfield.getText()+"ret"+ret+" "+Arrays.toString(mybytes)+"first read");
}
else if(endpoint.getDirection()==UsbConstants.USB_DIR_OUT){
myfield.setText(myfield.getText()+"endpoint zum schreiben"+i);
}
else{
myfield.setText(myfield.getText()+"irgendein endpoint");
}
}
}
else{
myfield.setText(myfield.getText()+"verbindung nicht möglich");
}
//call method to set up device cmmunication
}
}
else {
myfield.setText("Permission denied");
//Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};

Related

Unable to read data from usb serial device in android

I went through lots of demos and SO threads before asking this, but none of them is working for me. I am trying to read data over usb serial port using the below code.
public class MainActivity extends Activity {
public final String ACTION_USB_PERMISSION = "com.myprject.usbex.USB_PERMISSION";
Button startButton, sendButton, clearButton, stopButton;
TextView textView;
EditText editText;
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serialPort;
UsbDeviceConnection connection;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
Toast.makeText(MainActivity.this, "Callback Received"+arg0, Toast.LENGTH_SHORT).show();
String data = null;
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
tvAppend(textView, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Exception:"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
};
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the 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.
setUiEnabled(true);
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);
try {
serialPort.read(mCallback);
Toast.makeText(MainActivity.this, "Read"+serialPort.read(mCallback), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Exception in read:"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
tvAppend(textView, "Serial Connection Opened!\n");
Toast.makeText(MainActivity.this, "Serial port connected", Toast.LENGTH_SHORT).show();
} else {
Log.d("SERIAL", "PORT NOT OPEN");
}
} else {
Log.d("SERIAL", "PORT IS NULL");
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED");
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onClickStart(startButton);
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
onClickStop(stopButton);
}
}
;
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
startButton = (Button) findViewById(R.id.buttonStart);
sendButton = (Button) findViewById(R.id.buttonSend);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
setUiEnabled(false);
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);
}
public void setUiEnabled(boolean bool) {
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public void onClickStart(View view) {
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
if (deviceVID == 1659)//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 onClickSend(View view) {
String string = editText.getText().toString();
serialPort.write(string.getBytes());
tvAppend(textView, "\nData Sent : " + string + "\n");
}
public void onClickStop(View view) {
setUiEnabled(false);
serialPort.close();
tvAppend(textView,"\nSerial Connection Closed! \n");
}
public void onClickClear(View view) {
textView.setText(" ");
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}
}
I want to read data continuously from the usb. With above code I am able to get device vendor-id and serialPort.open() is also working. Problem is that I am not receiving the data.
Library used with this code is from here https://github.com/felHR85/SerialPortExample.
Point me where I am going wrong. open for any alternative solution to read data over usb in Android.
The code seems to be right and is working properly. Tried it and it runs smoothly without any problems. You might want to rearrange your widgets a little bit, which could be obstructing/interfering with your output (although I don't think this could be the problem). The toast in onReceivedData function was causing the app to crash. Also, check your Arduino device vendor ID. Mine was different (0x2341 for Arduino UNO R3).
Hello I know its too late for a reply but here it goes.
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);
Make sure that these are the config set at your USB Device, try changing BaudRate
i guess that library is specially designed for Arduino and some boards. I tried with PSOc Usb serial data transfer from its ROM, The data was not able to be read properly.

Reading the data from Usb in android

Please forgive me if I am not be able to elaborate my problem clearly.
I am trying to communicate with usb device and the which is getting successfully done
but i want to read from the usb device.
the code for the transferring the command is as follows.
public final static String TAG = "UsbClient";
private UsbManager mUsbManager;
private final int VID = 0x1fc9;
private final int PID = 0x0003;
private int toggle = 0;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
mUsbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
getActivity().registerReceiver(mUsbReceiver, filter);
HashMap<String, UsbDevice> devlist = mUsbManager.getDeviceList();
Iterator<UsbDevice> deviter = devlist.values().iterator();
while (deviter.hasNext()) {
UsbDevice d = deviter.next();
print("Found device: "
+ String.format("%04X:%04X", d.getVendorId(),
d.getProductId()));
if (d.getVendorId() == VID && d.getProductId() == PID) {
mUsbManager.requestPermission(d, mPermissionIntent);
}
}
The code for the Registered Receiver is
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) {
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
if (device.getVendorId() == VID && device.getProductId() == PID) {
print("Got permission for the device");
permissionGranted = true;
UsbInterface intf = device.getInterface(0);
conn = mUsbManager.openDevice(device);
//intf=device.getInterface(0);
conn.claimInterface(intf, true);
/* if (!conn.claimInterface(device.getInterface(1), true)) {
print("Could not claim the interface");
return;
}
*/
int i = conn.controlTransfer(0x21, 0x09, 0x0200, 0x0000, new byte[] { (byte) toggle }, 1, 0);
endpoint=device.getInterface(0).getEndpoint(0);
if (toggle == 0) {
toggle = 1;
}
else {
toggle = 0;
}
if ((i == 0) || (i==1)) {
print("transfer successful");
}
else {
print("transfer failed");
}
}
}
}
else {
print("permission denied for device " + device);
}
}
}
}
};
Now i wanted to know the procedure to read the data from the usb device that is attached to the android tablet Using OTG cable.
and one more thing how to obtain the endpoints for read and write to the usb device.
Thanks in advance.

android usb UsbDeviceConnection.bulkTransfer returns -1

I am trying to send commands to a POS printer from my android tablet. I have been able to get the basic connections wroking but now when I try to send data to the printer, the bulkTransfer returns -1. Please help me understand what is going on. The following is a modified broadcast receiver taken from the android site where I do all the data transfer.
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) {
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
if(device.getVendorId() != 1659)
return;
UsbInterface intf = device.getInterface(0);
UsbEndpoint endpoint = intf.getEndpoint(0);
int direction = endpoint.getDirection();
UsbDeviceConnection connection = mUsbManager.openDevice(device);
connection.claimInterface(intf, forceClaim);
bytes = new byte[]{27, 64};
//**This returns -1 always**
int ret = connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT);
if(ret < 0)
{
Log.d("WTF", "Error happened!");
}
else if(ret == 0)
{
Log.d("WTF", "No data transferred!");
}
else
{
Log.d("WTF", "success!");
}
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};

communication between android and fpga board

I am trying to transfer data from my android device to FPGA board. The android device supports the USB host mode and the connected FPGA board uses RS_232 port. So I got a USB-RS232 converter device(CP210x) for the connection. I coded the transfer as mentioned on this page: http://developer.android.com/guide/topics/connectivity/usb/host.html My code is:
public class MainActivity extends Activity
implements View.OnClickListener, Runnable {
private static final String TAG = "TransferData";
private Button sendB;
private UsbManager mUsbManager;
private UsbDevice mDevice;
private UsbDeviceConnection mConnection;
private UsbEndpoint mEndpointIntr;
private static final char DATA = 'A';
static UsbDevice device;
static int TIMEOUT = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendB = (Button)findViewById(R.id.send);
sendB.setOnClickListener(this);
mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
Log.d(TAG, "intent: " + intent);
String action = intent.getAction();
device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
setDevice(device);
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
if (mDevice != null && mDevice.equals(device)) {
setDevice(null);
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void setDevice(UsbDevice device) {
Log.d(TAG, "setDevice " + device);
if (device.getInterfaceCount() != 1) {
Log.e(TAG, "could not find interface");
return;
}
else Log.w(TAG, "found interface");
UsbInterface intf = device.getInterface(0);
// device should have one endpoint
if (intf.getEndpointCount() == 0) {
Log.e(TAG, "could not find endpoint");
return;
}
else Log.w(TAG, "found endpoint");
// endpoint should be of type interrupt
Log.w("endpoint", "" + intf.getEndpointCount());
UsbEndpoint ep = intf.getEndpoint(1);
if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_BULK) {
Log.e(TAG, "endpoint is not interrupt type");
return;
}
else Log.w(TAG, "endpoint is interrupt");
mDevice = device;
mEndpointIntr = ep;
if (device != null) {
UsbDeviceConnection connection = mUsbManager.openDevice(device);
if (connection != null && connection.claimInterface(intf, true)) {
Log.d(TAG, "open SUCCESS");
mConnection = connection;
Thread thread = new Thread(this);
thread.start();
} else {
Log.d(TAG, "open FAIL");
mConnection = null;
}
}
}
private void sendCommand(char control) {
if (mConnection != null) {
byte[] message = new byte[1];
message[0] = (byte)control;
// Send command via a control request on endpoint zero
UsbInterface intf = device.getInterface(0);
UsbEndpoint endpoint = intf.getEndpoint(1);
mConnection.claimInterface(intf,true);
int res = mConnection.bulkTransfer(endpoint, message, message.length, TIMEOUT);
Log.w("data sent","result " + res);
}
}
public void onClick(View v) {
if (v == sendB) {
sendCommand(DATA);
}
}
#Override
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(1);
UsbRequest request = new UsbRequest();
request.initialize(mConnection, mEndpointIntr);
byte status = -1;
request.queue(buffer, 1);
// send poll status command
sendCommand(DATA);
// wait for status event
if (mConnection.requestWait() == request) {
byte newStatus = buffer.get(0);
if (newStatus != status) {
Log.d(TAG, "got status " + newStatus);
status = newStatus;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
} else {
Log.e(TAG, "requestWait failed, exiting");
}
}
I get success in opening device and I get send result as 1. But no data received is reflected as the FPGA board. What am I doing wromg?
Try to switch RX with TX on FPGA. Did other communcation work with this connection?
Is there a design on the FPGA which will serve the UART?

Android USB- "could not find endpoint"

I'm a beginner android programmer who is trying to set up some USB functionality with my tablet and a device. My program uses an Intent filter to find the device. I took the Android's MissileLauncherActivity.java example and rewrote it. I am getting a "could not find endpoint" error in logcat. Is there something wrong with my code, or could it be my device? LogCat is finding the error in the setDevice method where it is trying to find the OUT endpoint. Here is the code:
public class UsbTestActivity extends Activity implements Runnable {
private UsbManager mUsbManager;
private UsbDevice mDevice;
private UsbDeviceConnection mConnection;
private UsbEndpoint mEndpointIntr;
private static final String TAG = "UsbTestActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onResume(){
super.onResume();
Intent intent = getIntent();
Log.d(TAG, "intent: " + intent);
String action = intent.getAction();
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
setDevice(device);
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
if (mDevice != null && mDevice.equals(device)) {
setDevice(null);
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void setDevice(UsbDevice device){
Log.d(TAG, "setDevice " + device);
if (device.getInterfaceCount() != 1) {
Log.e(TAG, "could not find interface");
return;
}
UsbInterface intf = device.getInterface(0);
// device should have one endpoint
if (intf.getEndpointCount() != 1) {
Log.e(TAG, "could not find endpoint");
return;
}
System.out.println("Got endpoint");
// endpoint should be of type interrupt
UsbEndpoint ep = intf.getEndpoint(0);
if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) {
Log.e(TAG, "endpoint is not interrupt type");
return;
}
mDevice = device;
mEndpointIntr = ep;
if (device != null) {
UsbDeviceConnection connection = mUsbManager.openDevice(device);
if (connection != null && connection.claimInterface(intf, true)) {
Log.d(TAG, "open SUCCESS");
mConnection = connection;
Thread thread = new Thread(this);
thread.start();
} else {
Log.d(TAG, "open FAIL");
mConnection = null;
}
}
}
private void sendCommand(int control) {
synchronized (this) {
if (mConnection != null) {
byte[] message = new byte[1];
message[0] = (byte)control;
// Send command via a control request on endpoint zero
if(mConnection.controlTransfer(0x21, 0x9, 0x200, 0, message, message.length, 0) > 0){
Log.d(TAG, "Sending Failed");
}
}
}
}
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(1);
UsbRequest request = new UsbRequest();
request.initialize(mConnection, mEndpointIntr);
byte status = -1;
while (true) {
// queue a request on the interrupt endpoint
request.queue(buffer, 1);
// send poll status command
if (mConnection.requestWait() == request) {
byte newStatus = buffer.get(0);
if (newStatus != status) {
Log.d(TAG, "got status " + newStatus);
status = newStatus;
sendCommand(7);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
} else {
Log.e(TAG, "requestWait failed, exiting");
break;
}
}
}
}
// device should have one endpoint
if (intf.getEndpointCount() != 1) {
Log.e(TAG, "could not find endpoint");
return;
}
Looks like you are trying to work with a USB HID device and its OUT endpoint. But HID mandates the IN endpoint to be present - so getEndpointCount() will most likely return 2 instead of one. You will need to check which is the IN and which is OUT.

Categories

Resources