打開串口
定義的JNI方法

image.png
c代碼

image.png
- 設(shè)置波特率方法
int set_opt(int fb,int nSpeed,int nBits,char nEvent,int nStop)
{
struct termios newtio,oldtio;
if(tcgetattr(fb,&oldtio)!=0)
{
perror("error:SetupSerial 3\n");
return -1;
}
bzero(&newtio,sizeof(newtio));
//使能串口接收
newtio.c_cflag |= CLOCAL | CREAD;
newtio.c_cflag &= ~CSIZE;
newtio.c_lflag &=~ICANON;//原始模式
//newtio.c_lflag |=ICANON; //標(biāo)準(zhǔn)模式
//設(shè)置串口數(shù)據(jù)位
switch(nBits)
{
case 7:
newtio.c_cflag |= CS7;
break;
case 8:
newtio.c_cflag |=CS8;
break;
}
//設(shè)置奇偶校驗(yàn)位
switch(nEvent)
{
case 'O':
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= (INPCK | ISTRIP);
break;
case 'E':
newtio.c_iflag |= (INPCK | ISTRIP);
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'N':
newtio.c_cflag &=~PARENB;
break;
}
//設(shè)置串口波特率
switch(nSpeed)
{
case 2400:
cfsetispeed(&newtio,B2400);
cfsetospeed(&newtio,B2400);
break;
case 4800:
cfsetispeed(&newtio,B4800);
cfsetospeed(&newtio,B4800);
break;
case 9600:
cfsetispeed(&newtio,B9600);
cfsetospeed(&newtio,B9600);
break;
case 115200:
cfsetispeed(&newtio,B115200);
cfsetospeed(&newtio,B115200);
break;
case 460800:
cfsetispeed(&newtio,B460800);
cfsetospeed(&newtio,B460800);
break;
default:
cfsetispeed(&newtio,B9600);
cfsetospeed(&newtio,B9600);
break;
}
//設(shè)置停止位
if(nStop == 1)
newtio.c_cflag &= ~CSTOPB;
else if(nStop == 2)
newtio.c_cflag |= CSTOPB;
newtio.c_cc[VTIME] = 5;
newtio.c_cc[VMIN] = 0;
tcflush(fb,TCIFLUSH);
if(tcsetattr(fb,TCSANOW,&newtio)!=0)
{
perror("com set error\n");
return -1;
}
return 0;
}
關(guān)閉串口
定義的JNI方法

image.png
c代碼

image.png
讀取串口數(shù)據(jù)
定義的JNI方法

image.png
c代碼

image.png
寫數(shù)據(jù)到串口
定義的JNI方法

image.png
c代碼

image.png
獲取串口描述符
定義的JNI方法

image.png
c代碼
JNIEXPORT jobject JNICALL Java_com_uniubi_uface_ether_outdevice_serialport_OutDeviceSerialPort_getFileDescriptor
(JNIEnv * env, jobject object, jint fd ){
jobject mFileDescriptor;
{
struct termios cfg;
if (tcgetattr(fd, &cfg))
{
LOGI("tcgetattr() failed");
close(fd);
/* TODO: throw an exception */
return NULL;
}
cfmakeraw(&cfg);
if (tcsetattr(fd, TCSANOW, &cfg))
{
LOGI("tcsetattr() failed");
close(fd);
/* TODO: throw an exception */
return NULL;
}
}
{
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;
}
寫韋根
定義的JNI方法

image.png
c代碼

image.png