Skip to content Skip to sidebar Skip to footer

Reader Thread For Usb Serial Communication Between Android And Arduino Uno

I am trying to communicate between Arduino UNO and my android smartphone using USB Host API of android. So far everything is good. I am sending a test string 'Try data' from my Ard

Solution 1:

Finally after lot of time, I figured it out. The android phone doesn't read 64 bytes in every bulk transfer even though the parameter in the function call is 64. This is because the thread is executing much faster. It reads sometimes 4, sometimes 2 bytes. The solution is : use a ring buffer or just use the substring() method to get the relevant characters. The modified code looks like this :

val reader = object : Thread(){
        override fun run() {
            var buf = ByteArray(64)
            while(true){
                var len = connection.bulkTransfer(endpointIn, buf, buf.size, 0)
                if(len > 0) {
                    val msg = String(buf) 
                    tvAppend(msg.substring(0, len)) //tv is the textview inside sv
                    sv.fullScroll(View.FOCUS_DOWN) //sv is a scrollview
                }
            }
        }
    }
reader.start()

Post a Comment for "Reader Thread For Usb Serial Communication Between Android And Arduino Uno"