You are currently viewing How to read/write data to a serial port in Android using Xamarin C#?
Xamarin

How to read/write data to a serial port in Android using Xamarin C#?

How to read/write data to a serial port in Android using Xamarin C#?

If you are looking for Xamarin C# example to Read/Write data to a serial port in Android then you are at the right page. In this post, I will give you an example to communicate with Serial Port using USB OTG. If you are looking for USB OTG example to communicate with your Arduino device then this example also helps you.

Related Question – USB OTG communication in Android with an example using Xamarin c#.

In GitHub, you can find numbers of solution for USB Serial For Android. If you are working with the JAVA then usb-serial-for-android by mik3y is the best example for you.

How to read/write data to a serial port in Android using Xamarin C#?[Solution]

USB Serial For Android – Xamarin C# Example: xamarin-usb-serial-for-android-2019

You can visit my GitHub public repository xamarin-usb-serial-for-android-2019 for reading and writing data to a serial port in Android using Xamarin c#. This Project is a modified version of https://github.com/anotherlab/xamarin-usb-serial-for-android.

I try the example provided by anotherlab but it was not working while reading and writing operation performs with the serial device. I modify the example provided by anotherlab and uploaded on GitHub so that other developer can use that.

What is the change?

I modify the hardcoded endpoint interface for read and write endpoint.

Old (CdcAcmSerialDriver.cs)

//mReadEndpoint = mDataInterface.GetEndpoint(1);
//Log.Debug(TAG, "Read endpoint direction: " + mReadEndpoint.Direction);
//mWriteEndpoint = mDataInterface.GetEndpoint(0);
//Log.Debug(TAG, "Write endpoint direction: " + mWriteEndpoint.Direction);

New (CdcAcmSerialDriver.cs)

for (int i = 0; i < mDataInterface.EndpointCount; ++i)
                {
                    UsbEndpoint ep = mDataInterface.GetEndpoint(i);
                    if ((ep.Direction == UsbAddressing.In) &&
                             (ep.Type == UsbAddressing.XferBulk))
                    {
                        Log.Debug(TAG, "Found reading endpoint");
                        mReadEndpoint = ep;
                    }
                    else if ((ep.Direction == UsbAddressing.Out) &&
                          (ep.Type == UsbAddressing.XferBulk))
                    {
                        Log.Debug(TAG, "Found writing endpoint");
                        mWriteEndpoint = ep;
                    }
                }

 

I also modify other changes but for initial purpose, it’s good to go with these changes.

It’s good to download the example and try it for a better solution. Please comment below for issue or report issue over GitHub.