Forum Xamarin.Android

How to write to serial port?

I have a project where I am trying to convert a Windows based app that sends data over USB/serial to Android. I've downloaded and examined https://bitbucket.org/lusovu/xamarinusbserial but I can't for the life of me find or figure out how to use the write() method the documentation refers to. I can't find anywhere in the example file that shows using a write command, and SerialIoManager.Write() doesn't exist. What am I missing?

Answers

  • daPyr0xdaPyr0x CAMember

    I've tried running the code below after serialIoManager.open is confirmed successful but I get a crash.

    byte[] msg = new byte[1]; msg[1] = Convert.ToByte('S'); port.Write(msg, 1);

    Any examples of a successful write command would be appreciated.

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    I have done an app for android that connect to usb printer and print some data. Can be useful?

  • daPyr0xdaPyr0x CAMember

    It could. Could you share the write portion?

  • Unicorn7Unicorn7 USMember ✭✭

    @AlessandroCaliaro Thank you very much for the example. I know you didn't need it for this project, but how would you open UsbDeviceConnection to receive/read a byte[] response (of unknown length) in reply to sending a message?

  • RahulKumar.3337RahulKumar.3337 USMember

    You can enable the write functionality in "xamarinusbserial" library by adding bellow function in "SerialInputOutputManager.cs" class.

    public int Write(String str, int timeout)
    {
    int bytesWritten = 0;
    try
    {
    byte[] buff = Encoding.ASCII.GetBytes(str);
    bytesWritten = port.Write(buff, timeout);
    }
    catch (Exception ex)
    {
    // log or handle
    }
    return bytesWritten;
    }

    To access this function use serialIoManager instance

  • Hello, I need a support to send data to the serial port using the "xamarinusbserial". I already have the "xamarinusbserial" package (NuGet) in my project but I can not find code examples that can help me. I need to monitor the serial port (rx) and send packets on it (tx). Thanks in advance!!

  • PaulParkinsPaulParkins USMember ✭✭

    @AlessandroCaliaro Thanks for your post. How did you determine the value for ACTION_USB_PERMISSION? I'm writing code for accessing a serial USB accessory (rather than USB device), but the process is similar and I need to request permission to use the accessory. But using "it.mobi-ware.android.USB" or "com.android.example.USB_PERMISSION" (as in this article) both give me an "unknown permission" exception.

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    Hi @PaulParkins

    Really, I don't know. Maybe you have to request permission at runtime?

  • PaulParkinsPaulParkins USMember ✭✭

    Yes that's exactly what I'm doing (or trying to)

  • to receive the data instead how would the code be?

Sign In or Register to comment.