Recently received a project,Demand is to do a special project Andrews board serial read and write in order to achieve some specific external devices to interact with - yes you read right,Andrews is also a board can have serial port!
Many friends do mobile development may not come into contact with - in fact, before I did not come into contact with。He stepped on seven or eight hours a pit,Finally climb out,Here to do a summary,Each board may project different circumstances,We must improvise。
First of all you need to know
Jumper,In order to save the project board USB interface,The default external USB interfaces are not connected to the computer debugging,According to this board for me to get started,Next to that is that close to the RJ45 port USB cable will have a jumper,It can be connected to a dedicated port of the computer。--Of course,Do not forget to turn on debug mode。
Find your serial number,Usually there will be on board the specification,Or view the sample program is also in line。
Java Can notDirectly to the serial port of Android to read and write,Use C or C ++ job,Therefore, to use the more advanced JNI to bridge,The part of the serial read and write the made-link library。
Read the serial portDo not need root,At least I did not encounter,Before the process step on the pit there are a few tips without permission,But in the end I was proved wrong path。
Multiple processes (threads) or the app iscanSimultaneous access to a serial port of the same,The result is likely to serial dataWill be lost,Shows that the "loss"。
mission target
My goal is simple,You do not even need to send information,Just change a signal from an external device needed to read,Specific to the project,It is understood to be 0 and 1 like。
The specific process
My board system 4.4.4,I do use Android Studio,First is to create an empty project。
Add NDK ,This is a C library to use Java:
Automatically download and install the,as will configure everything for you,Next in the upper left corner of your project to selected project "Project":
Then app/main Right-click on,New JNI directory:
Then put into the following five files in the directory:
jni ← Click to download
This side contains the files needed to bridge,Will be used later,Next, create a new directory called in java android_serialport_api Package,Note that this name must be a。A new java class within this package,Named SerialPort ,Follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
/* * Copyright 2009 Cedric Priscal * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android_serialport_api; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.util.Log; public class SerialPort { private static final String TAG = "SerialPort"; /* * Do not remove or rename the field mFd: it is used by native method close(); */ private FileDescriptor mFd; private FileInputStream mFileInputStream; private FileOutputStream mFileOutputStream; public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException { /* Check access permission */ if (!device.canRead() || !device.canWrite()) { try { /* Missing read/write permission, trying to chmod the file */ Process su; su = Runtime.getRuntime().exec("/system/bin/su"); String cmd = "chmod 777 " + device.getAbsolutePath() + "\n" + "exit\n"; su.getOutputStream().write(cmd.getBytes()); if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) { throw new SecurityException(); } } catch (Exception e) { e.printStackTrace(); throw new SecurityException(); } } mFd = open(device.getAbsolutePath(), baudrate, flags); if (mFd == null) { Log.e(TAG, "native open returns null"); throw new IOException(); } mFileInputStream = new FileInputStream(mFd); mFileOutputStream = new FileOutputStream(mFd); } // Getters and setters public InputStream getInputStream() { return mFileInputStream; } public OutputStream getOutputStream() { return mFileOutputStream; } // JNI private native static FileDescriptor open(String path, int baudrate, int flags); public native void close(); static { System.loadLibrary("serial_port"); } } |
After the addition of Gradle to link to the C ++,This time as you would choose to build the system,Choose NDK-build ,Then follow the prompts to find five file we just downloaded in Android.mk
After linking,You can choose Make Project in the Build menu ,After the make,Check the catalog to see if successfully generated link library:
After confirming the success of,To clean up and rebuild the entire project,Oh, right,As a test case, MainActivity You can write:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
package com.logcg.r0uter.myapplication; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android_serialport_api.SerialPort; public class MainActivity extends Activity { protected SerialPort mSerialPort; protected InputStream mInputStream; protected OutputStream mOutputStream; private ReadThread mReadThread; private class ReadThread extends Thread { @Override public void run() { super.run(); while(!isInterrupted()) { int size; Log.v("debug", "接收线程已经开启"); try { byte[] buffer = new byte[64]; if (mInputStream == null) return; size = mInputStream.read(buffer); if (size > 0) { onDataReceived(buffer, size); } } catch (IOException e) { e.printStackTrace(); return; } } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { mSerialPort = new SerialPort(new File("/dev/ttyS3"), 9600, 0);//这里串口地址和比特率记得改成你板子要求的值。 mInputStream = mSerialPort.getInputStream(); mOutputStream = mSerialPort.getOutputStream(); mReadThread = new ReadThread(); mReadThread.start(); } catch (SecurityException e) { e.printStackTrace(); } catch (IOException e) { Log.v("test", "启动失败"); e.printStackTrace(); } } protected void onDataReceived(final byte[] buffer, final int size) { runOnUiThread(new Runnable(){ public void run(){ String recinfo = new String(buffer, 0, size); Log.v("debug", "接收到串口信息======>" + recinfo.getBytes()); } }); } } |
Noteworthy
This project looks simple,But in fact most of the pit where the C library is written in question,It can be chosen online are almost always in this file ...... SerialPort.c First 116 Row,besides 128 Row,You will see the version I commented out the two detection,In fact, this problem fucked me three hours!
I get our hands on this board,It is to return -1 of! He returned -1 Nothing wrong! So until I suspect that life is a desperate fight ...... ...... only to find the true life of the pedicle。
In short,If you find that there was a strange problem in the implementation process,Then put a block of statements Anti comment if the two just fine。
If the first pass,Then you have toI thank。 :)
Reference Reading
Android Studio serial jni development
Android Studio : Serial communication using jni
Android serial port (SerialPort) a brief summary of the development issues
Original article written by LogStudio:R0uter's Blog » Development plate reader serial Android Andrews
Reproduced Please keep the source and description link:https://www.logcg.com/archives/2831.html
Finally setting up the environment,thank! Also people seem to have established jnilibs also copy the five files?
Hello there,I also use this jni you use the serial port to read and write,At present no problem to send,With serial tool FBI,But the reception is very strange。I ask you if you had encountered device to receive data,It receives only part of the data,Another portion of the data has been sent to the peer equipment where? such as,Computer equipment to send asdfgh,By mInputStream.read(buffer)Read,Read-only to sdfgh,Then received a computer terminal
I have not encountered,We hope that other passing of the great God to answer your question :)
3q
3q,Merry Christmas?
Recently doing the mainland class electronic cards
Bloggers just found this article
Helped me a great
Thank
:)