Skip to content Skip to sidebar Skip to footer

How To Read-write Character Devices (like /dev/ttys0) In Android

I have little knowledge of Java and Android. What I am trying to do is to open /dev/ttyS0 in an Android App which should talk to the serial line, but I am getting lost. My device i

Solution 1:

After many tries, and with the help of much information from the SO site, I finally succeded in the task. Here is the code:

publicclassMainActivityextendsAppCompatActivity {

    File serport;
    private FileInputStream mSerR;
    private FileOutputStream mSerW;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // let this program to access the serial port, and// turn off the local echo. sudo() is a routine found here on S.O.
        sudo("chmod a+rw /dev/ttyS0");
        sudo("stty -echo </dev/ttyS0");
        
        // open the file for read and write
        serport = newFile("/dev/ttyS0");
        try {
            mSerR = newFileInputStream(serport);
            mSerW = newFileOutputStream(serport);
        } catch (FileNotFoundException e) {}

        // edLine is a textbox where to write a string and send to the portfinalEditTextedLine= (EditText) findViewById(R.id.edLine);
        // edTerm is a multiline text box to show the dialogfinalTextViewedTerm= findViewById(R.id.edTerm);
        // pressing Enter, the content of edLine is echoed and sent to the port
        edLine.setOnKeyListener(newView.OnKeyListener() {
            publicbooleanonKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" buttonif ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key pressStringcmd= edLine.getText()+"\n";
                    edTerm.append(cmd);
                    byte[] obuf = cmd.getBytes();
                    try {
                        mSerW.write(obuf);
                    } catch  (IOException e)  {}
                    edLine.setText("");

                    // read the reply; some time must be granted to the server// for replying
                    cmd = "";
                    int b=-1, tries=8;
                    while (tries>0) {
                        try {
                            b = mSerR.read();
                        } catch  (IOException e)  {}
                        if (b==-1) {
                            try {
                                Thread.sleep(5);
                            } catch  (InterruptedException e)  {}
                            --tries;
                        } else {
                            tries=3;    // allow more timeout (more brief)if (b==10) break;
                            cmd = cmd + (char) b;
                        }
                    }
                    // append the received reply to the multiline control
                    edTerm.append(cmd+"\n");
                    returntrue;
                }
                returnfalse;
            }
        });

    }
}

Please note the presence of the sudo() command in the code: it is there to give r/w permissions to the ttyS0 file, and to disable its echo option. If those permissions+options are already right, or another mean to set them exists, then the sudo() command is not needed.

Note: I believe that the sudo() command implies that the device must be rooted.

Solution 2:

All File access in Java is done via input and output streams. If you want to open a file, you simply create a FileOutputStream or FileInputStream for it. These are unbuffered streams. If you then want to write raw bytes you can wrap that in a ByteArrayOutputStream or ByteArrayInputStream.

To do character mode, you can use a Writer. An OutputStreamWriter with a charset of ascii can wrap the FileOutputStream. That should do the character conversion for you. Just don't use a FileWriter- while it seems like the right fit, it has no option to select a character set, and the default is not ascii. For reading in, use an InputStreamReader.

Post a Comment for "How To Read-write Character Devices (like /dev/ttys0) In Android"