2014年9月14日日曜日

android usbserial

   

usbserialの作り方

if (manager == null)
{
    manager = (UsbManager) getSystemService(this.USB_SERVICE);
}
if (manager != null)
    usb = UsbSerialProber.findFirstDevice(manager);
if (usb == null)
{
    Toast toast = Toast.makeText(this, "USB接続がありません", Toast.LENGTH_LONG);
    mainMessage("USB接続がありません");
    toast.setGravity(Gravity.TOP, 0, 50);
    toast.show();
    return;
}

if (usb != null)
{
    try{
        usb.open();
        usb.setParameters(MONI_BPS, usb.DATABITS_8, usb.STOPBITS_1, usb.PARITY_ODD);
        start_read_thread(); // シリアル通信を読むスレッドを起動
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

読み取りスレッド

static int nMaxR = 0;
    static private byte buf[] = new byte[1024];
    public void start_read_thread(){
          new Thread(new Runnable(){
            public void run(){
              try{
                while(!bUsbClose){
                  int num = usb.read(buf, 256);
                  for (int i = 0; i < num; i++)
                  {
                      if (mWcnt >= mRecBuf.capacity())
                          mWcnt = 0;
                      mRecBuf.put(mWcnt, buf[i]);
                      mWcnt++;
                      if (mWcnt == mRcnt)
                      {
                          mOver++;
                          Log.d(TAG,"mOver = "+ String.format("%d", mOver));
                      }
                  }
                  if (num > nMaxR)
                      nMaxR = num;
                  if (num == 0)
                      Thread.sleep(10);
                }
              }
              catch(IOException e){
                e.printStackTrace();
              }
              catch (InterruptedException e) {
                e.printStackTrace();
              }
            }
          }).start();
        }

0 件のコメント:

コメントを投稿