android - 在 JNI 共享库中使用时,I2C_SLAVE ioctl() 因 ENOTTY 而失败

标签 android java-native-interface

我在尝试通过 JNI 在 Android (Gingerbread) 中使用 I2C 设备时遇到问题。

问题出在 I2C_SLAVE ioctl 调用上。以下代码在编译为独立程序时有效:

    int main(int argc, char *argv[])
{
    int fd = -1;
    long rc;
    int addr = 0x22;


  if ( fd  < 0 ) {
      fd = open(radio_device, O_RDWR);
  }

#define I2C_SLAVE 0x0703

  if ( (rc = ioctl(fd, I2C_SLAVE, addr)) < 0 ) {
      printf("RadioService: I2C slave addr failed! rc=%d errno= %d [%s]\n", rc, errno, strerror(errno));
  }
  else {
      printf("RadioService: I2C slave addr 0x%x set\n", addr);
  }

  return 0;

}

运行时的输出(通过 adb shell ):

~ # testi2c
RadioService: I2C slave addr 0x22 set

但是,相同的代码不能作为 JNI 库的一部分工作:

void Java_biz_lectronix_android_radio_RadioService_nativeInit(JNIEnv* env, jclass clazz)
{
    long rc;
    int addr1 = 0x22;
    int addr2 = 0x18;

    if ( fd = open(radio_device, O_RDWR) < 0 ) {
        __android_log_print(ANDROID_LOG_ERROR, "RadioService", "I2C open failed! %s", strerror(errno));
    }
    else {
        __android_log_write(ANDROID_LOG_WARN, "RadioService", "Opened fd");
    }

    __android_log_print(ANDROID_LOG_ERROR, "RadioService", "I2C_SLAVE [0x%x], addr = %d (0x%x)", I2C_SLAVE, addr1, addr1 );

    if ( (rc = ioctl(fd, I2C_SLAVE, addr1)) < 0 ) {
        __android_log_print(ANDROID_LOG_ERROR, "RadioService", "I2C slave addr1 failed! rc=%d errno= %d [%s]", rc, errno, strerror(errno));
    }
    else {
        __android_log_print(ANDROID_LOG_WARN, "RadioService", "I2C slave addr1 %d set", addr1);
    }

    if ( (rc = ioctl(fd, I2C_SLAVE, addr2)) < 0 ) {
        __android_log_print(ANDROID_LOG_ERROR, "RadioService", "I2C slave addr2 failed! rc=%d errno= %d [%s]", rc, errno, strerror(errno));
    }
    else {
        __android_log_print(ANDROID_LOG_WARN, "RadioService", "I2C slave addr2 %d set", addr2);
    }

    return;
}

Logcat 输出:

01-02 03:03:10.904: E/RadioService(1602): I2C_SLAVE [0x703], addr = 34 (0x22)
01-02 03:03:10.904: E/RadioService(1602): I2C slave addr1 failed! rc=-1 errno= 25 [Not a typewriter]
01-02 03:03:10.904: E/RadioService(1602): I2C slave addr2 failed! rc=-1 errno= 25 [Not a typewriter]

有谁知道这里可能出了什么问题吗?

最佳答案

实际上根本不是 I2C 接口(interface)的问题。问题是这一行:

if ( fd = open(radio_device, O_RDWR) < 0 ) {

应该是这样的(注意括号):

if ( ( fd = open(radio_device, O_RDWR) ) < 0 ) {

所以,I2C设备打开了,但是比较优先级高于C中的赋值,比较失败,将0赋值给fd——即stdin . ioctl()然后调用失败,因为 I2C_SLAVE 是一个不适合设备的 ioctl 命令。

关于android - 在 JNI 共享库中使用时,I2C_SLAVE ioctl() 因 ENOTTY 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17558382/

相关文章:

java - 不幸的是,与服务器的连接出现错误

java - 在 java 类上生成 C++ 包装器的工具

android - 如何解决 Late-enabling CheckJNI?

java - JNI获取ConcurrentHashMap

android - 在 JNI 共享库中查找函数?

java - 需要帮助来理解 Java 字节码指令

java - Android fragment 页面上的 java.lang.NullPointerException

android - 无法让 Android 文档中的相机代码正常工作

android.view.WindowManager$BadTokenException 异常。任何指针?

android - AppNotIdleException 由于 AnimatedVectorDrawableCompat