catalogs
I. Introduction to the environment
preamble
Serial port is a protocol used for android to communicate with hardware devices, you can send some kind of command to control the hardware devices, you can also accept the data sent by the sensors, such as IC/ID card, radar, sensors and so on. The following describes the use of serial port in android development in 2 ways
I. Introduction to the environment
- Android
System version :Android 7.1 Android 12
Android Studio Electric Eel | 2022.1.1jdk-18.0.2
- PC
Windows11
Serial debugging tool sscom (or other serial debugging tools are also available)
II. Introduction to equipment
2. Method 1:.
Using ARMT’s own serial port api SerialPort.java
1. Introduction of libraries
Add the jar package in build.gradle’s dependencies
//ARMT SDK
implementation files(‘libs/armtsdkapi.jar’)
2. Writing code
2.1 Initializing the serial portinitSerialPort("/dev/ttyS4");
/**
* :: Initialize the serial port
*
* @param path Serial port path
*/
private void initSerialPort(String path) {
try {
uart3 = new SerialPort(path, 9600, 8, "n", 1);
} catch (IOException e) {
e.printStackTrace();
}
//Get the output stream
mFileOutputStream3 = (FileOutputStream) uart3.getOutputStream();
//Get the input stream
mFileInputStream3 = (FileInputStream) uart3.getInputStream();
}
2.2 Preparation of acceptance data
/**
* :: Start-up thread to receive serial port data
* :: Handler refreshes sent when data is received
*/
private void readData() {
new Thread(() -> {
while (run_flag) {
int size3 = 0;
try {
size3 = mFileInputStream3.read(mRevBuffer3);
} catch (IOException e) {
e.printStackTrace();
}
if (size3 > 0) {
String str3 = new String(mRevBuffer3, 0, size3);
Log.i(" serial port ", "receiveData() --> "+ str3);
mHandler.sendMessage(mHandler.obtainMessage(1, str3));
Arrays.fill(mRevBuffer3, (byte) 0x0);
}
}
}, "Serial port receive thread").start();
}
Here we open a thread to read the data all the time, after reading the data through the Handler to update to the Textview.
2.3 Sending data
/**
* :: Send serial port data
*/
private void sendData() {
try {
if (mFileOutputStream3 != null) {
mFileOutputStream3.write(mBuffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Above is the method provided by ARMT to use the serial port, the full code is at the bottom of the page
3. Method 2:.
Using the third-party library SerialPortHelper
1. Introduction of libraries
Add the jar package in build.gradle’s dependencies
//Serial
implementation 'com.github.maybesix:Android-XHLibrary:v1.0.0'
Adding a maven repository
repositories {
maven { url 'https://jitpack.io' }
}
2. Writing code
2.1 Initializing the serial portmHelper = initSerialPortHelper("/dev/ttyS4");
Initialize SerialPortHelper here and set up a listener to update the TextView via Handler when data is received.
private SerialPortHelper initSerialPortHelper(String port) {
SerialPortHelper serialPort = new SerialPortHelper(port, 9600);
serialPort.setSerialPortReceivedListener(new SerialPortHelper.OnSerialPortReceivedListener() {
@SuppressLint("SetTextI18n")
@Override
public void onSerialPortDataReceived(ComPortData comPortData) {
String dataStr = comPortData.getRecTime() + "Received:" + new String(comPortData.getRecData());
mHandler.sendMessage(mHandler.obtainMessage(1, dataStr));
}
});
serialPort.open();
return serialPort;
}
2.2 Sending data
private void sendDataHelper() {
if (mHelper != null && mHelper.isOpen()) {
mHelper.sendTxtString(" I am SerialPortHelper");
}
}
2.3 Get all serial port addresses (generic method)
List<File> allSerial = getAllSerial();
/**
* :: Get all serial ports
*
* @return
*/
private List<File> getAllSerial() {
List<File> serialPorts = new ArrayList<>();
Pattern pattern = Pattern.compile("^ttyS|^ttyUSB|^ttyACM|^ttyAMA|^rfcomm|^tty[^/]*$");
File devDirectory = new File("/dev");
File[] files = devDirectory.listFiles();
if (files != null) {
for (File file : files) {
String name = file.getName();
if (pattern.matcher(name).find()) {
serialPorts.add(file);
Log.e("Serial port", "Serial port scanned" + file);
}
}
}
return serialPorts;
}
IV. Complete code.
package com.armt.sdktest_armt.serialPort;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.armt.sdktest_armt.R;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import cn.com.armt.sdk.hardware.SerialPort;
import top.maybesix.xhlibrary.serialport.ComPortData;
import top.maybesix.xhlibrary.serialport.SerialPortHelper;
public class SerialPortActivity extends AppCompatActivity {
private byte[] mRevBuffer3 = new byte[100];
private byte[] mBuffer = "12345".getBytes();//{1,2,3,4,5};
private SerialPort uart3;
private FileOutputStream mFileOutputStream3;
private FileInputStream mFileInputStream3;
private boolean run_flag = true;
private Button send;
private TextView content;
private SerialPortHelper mHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_serial_port);
send = findViewById(R.id.send);
content = findViewById(R.id.content);
//Get all serial ports
List<File> allSerial = getAllSerial();
Log.e("Serial Port", "All Serial Ports:" + allSerial);
//Initialize serial port, serial port address: "/dev/ttyS4".
initSerialPort("/dev/ttyS4");
//Enable threads to receive serial port data
readData();
//Second way to use the serial port
mHelper = initSerialPortHelper("/dev/ttyS4");
// Click on the Send button
send.setOnClickListener(v -> {
//Click to simulate sending data
sendData();
// sendDataHelper();
});
}
/**
* :: Get all serial ports
*
* @return
*/
private List<File> getAllSerial() {
List<File> serialPorts = new ArrayList<>();
Pattern pattern = Pattern.compile("^ttyS|^ttyUSB|^ttyACM|^ttyAMA|^rfcomm|^tty[^/]*$");
File devDirectory = new File("/dev");
File[] files = devDirectory.listFiles();
if (files != null) {
for (File file : files) {
String name = file.getName();
if (pattern.matcher(name).find()) {
serialPorts.add(file);
Log.e("Serial port", "Serial port scanned" + file);
}
}
}
return serialPorts;
}
/**
* :: Initialize the serial port
*
* @param path Serial port path
*/
private void initSerialPort(String path) {
try {
uart3 = new SerialPort(path, 9600, 8, "n", 1);
} catch (IOException e) {
e.printStackTrace();
}
//Get the output stream
mFileOutputStream3 = (FileOutputStream) uart3.getOutputStream();
//Get the input stream
mFileInputStream3 = (FileInputStream) uart3.getInputStream();
}
private Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
if (msg.what == 1) {
String data = (String) msg.obj;
content.append(data + "\n");
}
}
};
/**
* :: Send serial port data
*/
private void sendData() {
try {
if (mFileOutputStream3 != null) {
mFileOutputStream3.write(mBuffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* :: Start-up thread to receive serial port data
* :: Handler refreshes sent when data is received
*/
private void readData() {
new Thread(() -> {
while (run_flag) {
int size3 = 0;
try {
size3 = mFileInputStream3.read(mRevBuffer3);
} catch (IOException e) {
e.printStackTrace();
}
if (size3 > 0) {
String str3 = new String(mRevBuffer3, 0, size3);
Log.i(" serial port ", "receiveData() --> "+ str3);
mHandler.sendMessage(mHandler.obtainMessage(1, str3));
Arrays.fill(mRevBuffer3, (byte) 0x0);
}
}
}, "Serial port receive thread").start();
}
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * the second mode of serial port to use * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
private SerialPortHelper initSerialPortHelper(String port) {
SerialPortHelper serialPort = new SerialPortHelper(port, 9600);
serialPort.setSerialPortReceivedListener(new SerialPortHelper.OnSerialPortReceivedListener() {
@SuppressLint("SetTextI18n")
@Override
public void onSerialPortDataReceived(ComPortData comPortData) {
String dataStr = comPortData.getRecTime() + "Received:" + new String(comPortData.getRecData());
mHandler.sendMessage(mHandler.obtainMessage(1, dataStr));
}
});
serialPort.open();
return serialPort;
}
private void sendDataHelper() {
if (mHelper != null && mHelper.isOpen()) {
mHelper.sendTxtString(" I am SerialPortHelper");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
run_flag = false;
if (mFileOutputStream3 != null) mFileOutputStream3.close();
if (mFileInputStream3 != null) mFileInputStream3.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (mHelper != null) {
mHelper.close();
}
}
}
V. Source code download address.