打开串口
定义的JNI方法
image.png
c代码
image.png
- 设置波特率方法
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; //标准模式
//设置串口数据位
switch(nBits)
{
case 7:
newtio.c_cflag |= CS7;
break;
case 8:
newtio.c_cflag |=CS8;
break;
}
//设置奇偶校验位
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;
}
//设置串口波特率
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;
}
//设置停止位
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;
}
关闭串口
定义的JNI方法
image.png
c代码
image.png
读取串口数据
定义的JNI方法
image.png
c代码
image.png
写数据到串口
定义的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