android,kotlin2024. 6. 21. 14:55

[android] Android RS232 구현방법

 

gradle

dependencies {
    implementation 'com.github.mik3y:usb-serial-for-android:3.4.6'
}

 

manifest

<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.USB_PERMISSION" />

<application
    ...>
    <activity ...>
        ...
        <intent-filter>
            <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        </intent-filter>
        <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
            android:resource="@xml/device_filter" />
    </activity>
</application>

 

필터

<resources>
    <usb-device vendor-id="0x2341" product-id="0x0043" />
</resources>

 

하드웨어에서 제공하는 키를 넣으면 된다.

vendor-id="0x2341" product-id="0x0043"

 

activity

 private lateinit var usbManager: UsbManager
    private var serialPort: UsbSerialPort? = null
    
     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        usbManager = getSystemService(USB_SERVICE) as UsbManager
        setupSerialConnection()
    }
    
    private fun setupSerialConnection() {
        val availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager)
        if (availableDrivers.isEmpty()) {
            Log.d(TAG, "No USB devices found")
            return
        }

        val driver = availableDrivers[0]
        val connection = usbManager.openDevice(driver.device)
        if (connection == null) {
            Log.d(TAG, "Could not open connection")
            return
        }

        serialPort = driver.ports[0]
        serialPort?.open(connection)
        serialPort?.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)

        val usbIoManager = SerialInputOutputManager(serialPort, object : SerialInputOutputManager.Listener {
            override fun onNewData(data: ByteArray) {
                runOnUiThread {
                    Log.d(TAG, "Received data: ${String(data)}")
                }
            }

            override fun onRunError(e: Exception) {
                Log.e(TAG, "Runner stopped.", e)
            }
        })
        Executors.newSingleThreadExecutor().submit(usbIoManager)

        // Example: Sending data
        val sendData = "하드웨어에 전해줄 명령어".toByteArray()
        serialPort?.write(sendData, 1000)
    }
    
      override fun onDestroy() {
        super.onDestroy()
        serialPort?.close()
    }

 

협약 된 명령어 넣어준다.

 val sendData = "하드웨어에 전해줄 명령어".toByteArray()

Posted by thdeodls85