2017/02/28

Android使用Usb Serial For Android Library取得Arduino傳送資訊

Usb Serial For Android Library是一個已經整合好的Serial Driver Library
所以就不用從頭自己寫一個了
使用時Android project底下的res新增xml資料夾並在該資料夾底下新增device_filter.xml

執行結果:


Arduino程式碼:
/*
 Name:  Test.ino
 Created: 2017/2/28 上午 12:06:46
 Author: C.Y.Fang
*/

// the setup function runs once when you press reset or power the board
void setup() {
 Serial.begin(115200);

}

// the loop function runs over and over again until power down or reset
void loop() {
 Serial.println("Hi");
 delay(1000);
}
Android程式碼:
package com.example.cyfang.otgexample;

import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;

import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private UsbManager manager;
    private UsbSerialPort port;
    private UsbSerialDriver driver;
    private UsbDeviceConnection connection;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }


    private void init() {
        textView = (TextView) findViewById(R.id.textView);
        textView.postDelayed(runnable, 1000);
        manager = (UsbManager) getSystemService(USB_SERVICE);

        List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
        if (availableDrivers.isEmpty()) {
            textView.setText("Can't not find usb device.");
            return;
        }
        driver = availableDrivers.get(0);
        connection = manager.openDevice(driver.getDevice());
        if (connection == null) {
            textView.setText("Usb can't connect to mobile.");
            return;
        }

        port = driver.getPorts().get(0);
        try {
            port.open(connection);
            port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
        } catch (IOException ex) {

        }
    }

    private final Runnable runnable = new Runnable() {
        byte buffer[] = new byte[1024];

        @Override
        public void run() {
            if (port != null) {
                try {
                    int number = port.read(buffer, 1000);
                    String text = new String(buffer, "UTF-8");
                    textView.setText(text);
                    textView.postDelayed(runnable, 1000);
                } catch (IOException ex) {
                }
            }
        }
    };

}



參考資料:
https://github.com/mik3y/usb-serial-for-android