關於安卓設備上使用串口,谷歌官方在github上有提供代碼實例,裏面有JNI的代碼和串口API的java。將谷歌官方串口庫項目下載後發現只支持設置串口號及波特率, 需求須要增長支持校驗位、數據位、中止位、流控等串口配置項,此記錄步驟。java
在native代碼裏添加修改android
/* Check arguments */
{
speed = getBaudrate(baudrate);
if (speed == -1) {
/* TODO: throw an exception */
LOGE("Invalid baudrate");
return NULL;
}
}
複製代碼
/* Opening device */
{
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 | flags);
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);
cfsetispeed(&cfg, speed);
cfsetospeed(&cfg, speed);
複製代碼
cfg.c_cflag &= ~CSIZE;
switch (dataBits) {
case 5:
cfg.c_cflag |= CS5; //使用5位數據位
break;
case 6:
cfg.c_cflag |= CS6; //使用6位數據位
break;
case 7:
cfg.c_cflag |= CS7; //使用7位數據位
break;
case 8:
cfg.c_cflag |= CS8; //使用8位數據位
break;
default:
cfg.c_cflag |= CS8;
break;
}
複製代碼
switch (parity) {
case 0:
cfg.c_cflag &= ~PARENB; //無奇偶校驗
break;
case 1:
cfg.c_cflag |= (PARODD | PARENB); //奇校驗
break;
case 2:
cfg.c_iflag &= ~(IGNPAR | PARMRK); // 偶校驗
cfg.c_iflag |= INPCK;
cfg.c_cflag |= PARENB;
cfg.c_cflag &= ~PARODD;
break;
default:
cfg.c_cflag &= ~PARENB;
break;
}
複製代碼
switch (stopBits) {
case 1:
cfg.c_cflag &= ~CSTOPB; //1位中止位
break;
case 2:
cfg.c_cflag |= CSTOPB; //2位中止位
break;
default:
break;
}
複製代碼
switch (flowCon) {
case 0:
cfg.c_cflag &= ~CRTSCTS; //不使用流控
break;
case 1:
cfg.c_cflag |= CRTSCTS; //硬件流控
break;
case 2:
cfg.c_cflag |= IXON | IXOFF | IXANY; //軟件流控
break;
default:
cfg.c_cflag &= ~CRTSCTS;
break;
}
複製代碼
源碼地址 github.com/xmaihh/Andr… Demo演示APK 下載地址ios