Android 串口開發(fā) 支持N-8-1(數(shù)據(jù)位停止位校驗方式) 設(shè)定

依據(jù)使用Cmake的方式 對串口開發(fā)的便捷了很多,但是的大多數(shù)例子稿蹲,都不支持對 數(shù)據(jù)位 停止位 和校驗位的設(shè)定粤剧,畢竟大多數(shù)人并不會linux 下的串口編程奕污,查閱很多例子和資料
主要參考了:
https://www.cnblogs.com/rui1236/p/5988074.html
但是按照這個 例子中的 C的寫法 無校驗(N-8-1)的時候正常,有奇偶校驗 發(fā)出去的準確按厘,但是收到的卻不準確医吊。

比如HEX(十六進制) 95 收到變成15 第一位被截取了。

部分 分析實現(xiàn)過程 參考

Android 串口通信開發(fā)筆記01

Android 串口通信筆記2 調(diào)試工具分析 工具類實現(xiàn)分析逮京、項目實現(xiàn)
Android 串口通信開發(fā)筆記3:CMake 方式實現(xiàn)和 多對多的實現(xiàn)邏輯

最后是又從參考了部分 linux 下的串口 對該 奇偶校驗部分更改實現(xiàn):

最后改后的 C源碼:

 #include <termios.h>
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <string.h>
 #include <jni.h>
 #include <strings.h>


 #include "android/log.h"
 static const char *TAG = "serial_port";
 #define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO,  TAG, fmt, ##args)
 #define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
 #define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)
 int fd;
 static speed_t getBaudrate(jint baudrate)
 {
switch(baudrate)
{
    case 0:
        return B0;
    case 50:
        return B50;
    case 75:
        return B75;
    case 110:
        return B110;
    case 134:
        return B134;
    case 150:
        return B150;
    case 200:
        return B200;
    case 300:
        return B300;
    case 600:
        return B600;
    case 1200:
        return B1200;
    case 1800:
        return B1800;
    case 2400:
        return B2400;
    case 4800:
        return B4800;
    case 9600:
        return B9600;
    case 19200:
        return B19200;
    case 38400:
        return B38400;
    case 57600:
        return B57600;
    case 115200:
        return B115200;
    case 230400:
        return B230400;
    case 460800:
        return B460800;
    case 500000:
        return B500000;
    case 576000:
        return B576000;
    case 921600:
        return B921600;
    case 1000000:
        return B1000000;
    case 1152000:
        return B1152000;
    case 1500000:
        return B1500000;
    case 2000000:
        return B2000000;
    case 2500000:
        return B2500000;
    case 3000000:
        return B3000000;
    case 3500000:
        return B3500000;
    case 4000000:
        return B4000000;
    default:
        return -1;
}
 }

 /**

 * 設(shè)置串口數(shù)據(jù)卿堂,校驗位,速率,停止位

 * @param nBits 類型 int數(shù)據(jù)位 取值 位7或8

 * @param nEvent 類型 char 校驗類型 取值N ,E, O,,S

 * @param mStop 類型 int 停止位 取值1 或者 2

 */

 int set_opt(jint nBits, jchar nEvent, jint nStop)
 {

LOGE("set_opt:nBits=%d,nEvent=%c,nSpeed=%d,nStop=%d", nBits, nEvent, nStop);
LOGE("set_opt:nStop=%d",  nStop);

struct termios newtio;

if(tcgetattr(fd, & newtio) != 0)
{

    LOGE("setup serial failure");

    return -1;

}

bzero( & newtio, sizeof(newtio));

//c_cflag標志可以定義CLOCAL和CREAD懒棉,這將確保該程序不被其他端口控制和信號干擾草描,同時串口驅(qū)動將讀取進入的數(shù)據(jù)。CLOCAL和CREAD通巢哐希總是被是能的

newtio.c_cflag |= CLOCAL | CREAD;


switch(nBits) //設(shè)置數(shù)據(jù)位數(shù)
{

    case 7:
        LOGE("設(shè)置數(shù)據(jù)位數(shù)==7");
        newtio.c_cflag &= ~CSIZE;

        newtio.c_cflag |= CS7;

        break;

    case 8:
        LOGE("設(shè)置數(shù)據(jù)位數(shù)==8");
        newtio.c_cflag &= ~CSIZE;

        newtio.c_cflag |= CS8;

        break;

    default:
        newtio.c_cflag &= ~CSIZE;

        newtio.c_cflag |= CS8;
        LOGE("設(shè)置數(shù)據(jù)位數(shù)==默認=8");
        break;

}



switch(nEvent) //設(shè)置校驗位
{
    case 'o':
    case 'O':

        newtio.c_cflag |= (PARODD | PARENB);
        newtio.c_iflag |= INPCK;
        LOGE("設(shè)置校驗位O奇校驗位");

        break;
    case 'e':
    case 'E':

        newtio.c_cflag |= PARENB;
        newtio.c_cflag &= ~PARODD;
        newtio.c_iflag |= INPCK;



        LOGE("設(shè)置校驗位E偶校驗位");

        break;

    case 'N':
    case 'n':
        newtio.c_cflag &= ~PARENB; //清除校驗位


        LOGE("設(shè)置校驗位N");
        break;


    default:
        newtio.c_cflag &= ~PARENB; //清除校驗位
        LOGE("設(shè)置校驗位默認N");
        break;

}
switch(nStop) //設(shè)置停止位
{

    case 1:

        newtio.c_cflag &= ~CSTOPB;

        break;

    case 2:

        newtio.c_cflag |= CSTOPB;

        break;

    default:
        newtio.c_cflag &= ~CSTOPB;
        // LOGW("nStop:%d,invalid param", nStop);

        break;

}

newtio.c_cc[VTIME] = 0;//設(shè)置等待時間

newtio.c_cc[VMIN] = 0;//設(shè)置最小接收字符

tcflush(fd, TCIFLUSH);

if(tcsetattr(fd, TCSANOW, & newtio) != 0)
{

    LOGE("options set error");

    return -1;

}


LOGE("options set success");
return 1;

 }


 /*
  * Class:     android_serialport_SerialPort
  * Method:    open
  * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor;
  */
 JNIEXPORT jobject JNICALL Java_com_silencefun_comtest_serialport_SerialPort_open
    (JNIEnv *env, jclass thiz, jstring path, jint baudrate,
     jint databits, jint stopbits, jchar parity)
 {
 
speed_t speed;
jobject mFileDescriptor;

/*波特率 */
{
    speed = getBaudrate(baudrate);
    if (speed == -1)
    {
        /* TODO: throw an exception */
        LOGE("Invalid baudrate");
        return NULL;
    }
}

/* Opening device */
{
    jint flags = 0;
    jboolean iscopy;
    const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy);
    LOGD("Opening serial port %s with flags 0x%x", path_utf, O_RDWR | flags);
    fd = open(path_utf, O_RDWR | O_NONBLOCK);
    //fd=fd;
    LOGD("open() fd = %d", fd);
    (*env)->ReleaseStringUTFChars(env, path, path_utf);
    if (fd == -1)
    {
        /* Throw an exception */
        LOGE("Cannot open port");
        /* TODO: throw an exception */
        return NULL;
    }
}

/* Configure device */
{
    struct termios cfg;
    LOGD("Configuring serial port");
    if (tcgetattr(fd, &cfg))
    {
        LOGE("tcgetattr() failed");
        close(fd);
        /* TODO: throw an exception */
        return NULL;
    }

    cfmakeraw(&cfg);
    //設(shè)置波特率
    cfsetispeed(&cfg, speed);
    cfsetospeed(&cfg, speed);

    if (tcsetattr(fd, TCSANOW, &cfg))
    {
        LOGE("tcsetattr() failed");
        close(fd);
        /* TODO: throw an exception */
        return NULL;
    }

    //配置校驗位 停止位等等
    set_opt(databits, parity, stopbits);
}

/* Create a corresponding file descriptor */
{
    jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");
    jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()V");
    jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I");
    mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);
    (*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint)fd);
}

return mFileDescriptor;

 }

 /*
  * Class:     cedric_serial_SerialPort
  * Method:    close
  * Signature: ()V
  */
 JNIEXPORT void JNICALL Java_com_silencefun_comtest_serialport_SerialPort_close
    (JNIEnv *env, jobject thiz)
 {
jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);
jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");

jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");

jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);
jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);

LOGD("close(fd = %d)", descriptor);
close(descriptor);
 }

在寫Native 方法的時候 要對應(yīng)參數(shù)類型和位置穗慕,SerialPort類中改:

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 dataBits, int stopBits, char parity) throws SecurityException, IOException {


   // mFd = open(device.getAbsolutePath(), baudrate, flags);

    mFd = open(device.getAbsolutePath(), baudrate,dataBits,stopBits,parity);
    if (mFd == null) {
        Log.e(TAG, "native open returns null");
        throw new IOException();
    }
    mFileInputStream = new FileInputStream(mFd);
    mFileOutputStream = new FileOutputStream(mFd);
}
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {


    // mFd = open(device.getAbsolutePath(), baudrate, flags);

    mFd = open(device.getAbsolutePath(), baudrate,8,2,'E');
    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);

// 調(diào)用JNI中 打開方法的聲明

/**
 * @param dataBits 類型 int數(shù)據(jù)位 取值 位7或8
 * @param parity   char校驗類型 取值N ,E, O,,S
 * @param stopBits 類型 int 停止位 取值1 或者 2
 * @return
 */
private native static FileDescriptor open(String path, int baudrate, int dataBits, int stopBits, char parity);

public native void close();

static {
    System.loadLibrary("native-lib");
 }
}

這樣 再 打開 串口,也就是SerialHelper類中增加成員變量和set方法

 //默認 N-8-1
private char parity = 'N';//char校驗類型 取值N ,E, O,,S
private int dataBits = 8;//dataBits 類型 int數(shù)據(jù)位 取值 位7或8
private int stopBits = 1;//stopBits 類型 int 停止位 取值1 或者 2

/**
 *設(shè)定校驗位等
 */
public void setN81(String idataBits, String istopBits, String cparity) {
    this.parity =cparity.charAt(0);
    this.dataBits = Integer.parseInt(idataBits);
    this.stopBits =  Integer.parseInt(istopBits);
}

同時更改原來的打開方法 :

 mSerialPort =new SerialPort(new File(sPort), iBaudRate, dataBits, stopBits, parity);
 // 對比原來的 初始化方法
// mSerialPort = new SerialPort(new File(sPort), iBaudRate, 0); 

同樣在初始化串口對象之后打開串口之前妻导,進行N-8-1的設(shè)定逛绵,然后再打開串口

      if (isChecked) {

//ComA=new SerialControl("/dev/s3c2410_serial0", "9600");
                ComA.setPort(SpinnerCOMA.getSelectedItem().toString());
                ComA.setN81(Spinner_databits1.getSelectedItem().toString(), Spinner_stopbits1.getSelectedItem().toString(), Spinner_parity1.getSelectedItem().toString());
                //setN81(String idataBits, String istopBits, String cparity) {
                Log.e("N81----->", Spinner_databits1.getSelectedItem().toString() + Spinner_stopbits1.getSelectedItem().toString() + Spinner_parity1.getSelectedItem().toString());

                ComA.setBaudRate(SpinnerBaudRateCOMA.getSelectedItem().toString());
                OpenComPort(ComA);

            } else {
                CloseComPort(ComA);
                checkBoxAutoCOMA.setChecked(false);
            }

模擬器中截圖:


image.png

該項目 github 路徑,歡迎建議 指正倔韭。
https://github.com/silencefun/ComTest/tree/master/Android_SetN81

部分 分析實現(xiàn)過程 參考

Android 串口通信開發(fā)筆記01

Android 串口通信筆記2 調(diào)試工具分析 工具類實現(xiàn)分析术浪、項目實現(xiàn)
Android 串口通信開發(fā)筆記3:CMake 方式實現(xiàn)和 多對多的實現(xiàn)邏輯

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市寿酌,隨后出現(xiàn)的幾起案子胰苏,更是在濱河造成了極大的恐慌,老刑警劉巖份名,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件碟联,死亡現(xiàn)場離奇詭異,居然都是意外死亡僵腺,警方通過查閱死者的電腦和手機鲤孵,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來辰如,“玉大人普监,你說我怎么就攤上這事。” “怎么了凯正?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵毙玻,是天一觀的道長。 經(jīng)常有香客問我廊散,道長桑滩,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任允睹,我火速辦了婚禮运准,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘缭受。我一直安慰自己胁澳,他們只是感情好,可當我...
    茶點故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布米者。 她就那樣靜靜地躺著韭畸,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蔓搞。 梳的紋絲不亂的頭發(fā)上胰丁,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天,我揣著相機與錄音败明,去河邊找鬼隘马。 笑死,一個胖子當著我的面吹牛妻顶,可吹牛的內(nèi)容都是我干的酸员。 我是一名探鬼主播,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼讳嘱,長吁一口氣:“原來是場噩夢啊……” “哼幔嗦!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起沥潭,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤邀泉,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后钝鸽,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體汇恤,經(jīng)...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年拔恰,在試婚紗的時候發(fā)現(xiàn)自己被綠了因谎。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡颜懊,死狀恐怖财岔,靈堂內(nèi)的尸體忽然破棺而出风皿,到底是詐尸還是另有隱情,我是刑警寧澤匠璧,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布桐款,位于F島的核電站,受9級特大地震影響夷恍,放射性物質(zhì)發(fā)生泄漏魔眨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一酿雪、第九天 我趴在偏房一處隱蔽的房頂上張望冰沙。 院中可真熱鬧,春花似錦执虹、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至当叭,卻和暖如春茬故,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蚁鳖。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工磺芭, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人醉箕。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓钾腺,卻偏偏與公主長得像,于是被迫代替她去往敵國和親讥裤。 傳聞我的和親對象是個殘疾皇子放棒,可洞房花燭夜當晚...
    茶點故事閱讀 45,047評論 2 355

推薦閱讀更多精彩內(nèi)容