2016-03-29 16 views
1

私はこれを聞く前にたくさんのデモとSOスレッドを使いましたが、どれも私のために働いていません。私は、以下のコードを使用してUSBシリアルポート経由でデータを読み込もうとしています。androidのUSBシリアルデバイスからデータを読み取ることができません

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); 
      } 
     }); 
    } 

} 

私はUSBから連続してデータを読みたいと思います。上記のコードで私はデバイスのベンダIDを取得することができ、serialPort.open()も動作しています。問題は私がデータを受け取っていないことです。

このコードで使用されるライブラリは、ここからhttps://github.com/felHR85/SerialPortExampleです。

私が間違っているところを指摘してください。 Android上でUSB経由でデータを読み取るための代替ソリューションを用意しています。

+0

@Commonswareではこれにいくつか光を当てることができます。 –

答えて

0

コードは正しいと思われ、正しく機能しています。それを試しても問題なくスムーズに動作します。あなたのウィジェットを少し並べ替えることができます。これはあなたの出力を妨害/妨害することがあります(これは問題ではないと思いますが)。 onReceivedData関数のトーストが原因でアプリがクラッシュしていました。また、ArduinoのデバイスベンダーIDを確認してください。私のものは違いました(Arduino UNO R3の0x2341)。

+0

StackOvervlow @archityへようこそ。ディスカッションに参加していただきありがとうございます。あなたの経験は役に立ちますが、答えではなく、元の質問に対するコメントでなければなりません。 – eebbesen

関連する問題