最新在做安卓新零售终端,需要通过串口读取DS18B20温度传感器温度,我们是使用第三方温度传感器板子,我们安装厂家定义的协议发送查询数据命令,就会返回温度数组的串口命令,对串口的温度值进行解析即可得到温度,我写了一个Demo进行串口读温度测试,以下为测试的源码:

(1)MainActivity.java

package kyle.me.testz;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import com.aill.androidserialport.SerialPort;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {
    private final String TAG = MainActivity.class.getSimpleName();

    private SerialPort serialPort;

    private InputStream mInputStream;
    private OutputStream mOutputStream;

    private final int BAUDRATE = 9600;                          // 波特率
    private final String SERIALPORT_NO3 = "/dev/ttyS4";         // 串口号4
    private final String QUERY_TEMP_CMD = "010300000001840a";   // 查询温度命令

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initSerialPort();
        new Thread(new ReadSerialPortTempThread()).start();
    }

    private class ReadSerialPortTempThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    final String getTemp = ReadSerialPortTemp();
                    Log.d(TAG, "getTemp =" + getTemp);
                    Thread.sleep(1000);
                    Log.d(TAG, "sleep 1000!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String ReadSerialPortTemp() {
        final String readTemp = ReadSerialPortTempCmd();
        if (readTemp.equals("")) {
            Log.d(TAG, "read temp error!");
            return "";
        } else {
            final String parserReadTemp = parserSerialPortHexTemp(readTemp);
            return parserReadTemp;
        }
    }

    private String ReadSerialPortTempCmd() {
        final String tempSendCmd = QUERY_TEMP_CMD;
        if (tempSendCmd != null && !tempSendCmd.equals("")) {
            int size;
            byte[] sendBuff = fromHexString(tempSendCmd);
            byte revBuff[] = new byte[1024];
            String tempRevCmd = "";
            try {
                mOutputStream.write(sendBuff, 0, sendBuff.length);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    if (mInputStream == null) {
                        return "";
                    }
                    size = mInputStream.read(revBuff);
                    Log.d(TAG, "size =" + size);
                    if (size > 0) {
                        for (int i = 0; i < size; i++) {
                            tempRevCmd += hexToDecimal(revBuff[i]);
                        }
                    }
                    Log.d(TAG, "resultString =" + tempRevCmd);

                    if (tempRevCmd.length() == 14) {
                        Log.d(TAG, "return tempRevCmd!");
                        return tempRevCmd;
                    } else {
                        Log.d(TAG, "no return tempRevCmd!");
                        return "";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

            }
        }
        return "";
    }

    private String parserSerialPortHexTemp(String hexTempCmd) {
        if ((!hexTempCmd.equals("")) || (!hexTempCmd.equals("8000"))) {
            final String hexTemp = hexTempCmd.substring(6, 10);
            Log.d(TAG, "newResultString = " + hexTemp);
            double temp = parseHex4(hexTemp) / 10;
            Log.d(TAG, "temp =" + temp);
            return String.valueOf(temp);
        } else {
            return "";
        }
    }

    public void initSerialPort() {
        try {
            serialPort = new SerialPort(new File(SERIALPORT_NO3), BAUDRATE, 0);
            mInputStream = serialPort.getInputStream();
            mOutputStream = serialPort.getOutputStream();
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "打开串口失败!");
        }
    }

    public void deInitSerialPort() {
        try {
            try {
                mOutputStream.close();
                mInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            serialPort.close();
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "关闭串口失败!");
        }
    }

    private static double parseHex4(String num) {
        if (num.length() != 4) {
            throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
        }
        int ret = Integer.parseInt(num, 16);
        ret = ((ret & 0x8000) > 0) ? (ret - 0x10000) : (ret);
        return (double) ret;
    }

    private String hexToDecimal(byte oneByte) {
        String str = "";
        int h = (oneByte >>> 4) & 0xF;
        int l = oneByte & 0xF;
        char ch = (char) ((h < 10) ? ('0' + h) : ('A' + h - 10));
        char cl = (char) ((l < 10) ? ('0' + l) : ('A' + l - 10));
        str = "";
        str += ch;
        str += cl;
        return str;
    }

    private static byte[] fromHexString(String hexString) {
        if (null == hexString || "".equals(hexString.trim())) {
            return new byte[0];
        }
        byte[] bytes = new byte[hexString.length() / 2];
        String hex;
        for (int i = 0; i < hexString.length() / 2; i++) {
            hex = hexString.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(hex, 16);
        }
        return bytes;
    }
}

(2)app/build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.0"
    defaultConfig {
        applicationId "kyle.me.testz"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'com.aill:AndroidSerialPort:1.0.8'
}

(3)运行结果

Android通过串口读取DS18B20温度传感器板子

 

相关文章: