1.需要在/system/core/rootdir/init.rc开启节点权限
2.jni层源码如下
#include <jni.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdint.h>
#include <termios.h>
#include <android/log.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <unistd.h>
jint fd_at24cxx;
extern "C" JNIEXPORT jint JNICALL
Java_com_example_srednew_i2c_I2COpen(JNIEnv *env, jobject thiz)
{
fd_at24cxx = open("/dev/i2c-2", O_RDWR);
if (fd_at24cxx < 0) {
__android_log_print(ANDROID_LOG_INFO, "at24cxx", "at24cxx open fail");
return -1;
} else {
__android_log_print(ANDROID_LOG_INFO, "at24cxx", "at24cxx open success");
}
ioctl(fd_at24cxx,I2C_SLAVE,0x50); // 设置从设备地址
ioctl(fd_at24cxx,I2C_TIMEOUT,1); // 设置超时
ioctl(fd_at24cxx,I2C_RETRIES,1); // 设置重试次数
return 1;
}
extern "C" JNIEXPORT jint JNICALL
Java_com_example_srednew_i2c_I2CWrite(JNIEnv *env, jobject thiz, jbyte data, jint high_address, jint low_address)
{
int ret = 0;
jbyte buffer[3];
buffer[0] = (jbyte)high_address;
buffer[1] = (jbyte)low_address;
buffer[2] = data;
if (high_address > 15 || high_address < 0 || low_address > 255 || low_address < 0) {
__android_log_print(ANDROID_LOG_INFO, "at24cxx", "high_address or low_address error");
return -1;
}
ret = write(fd_at24cxx, buffer, 3);
if(ret < 0)//写入数据
{
__android_log_print(ANDROID_LOG_INFO, "at24cxx", "at24cxx write fail");
return -1;
}
usleep(10000);
return ret;
}
extern "C" JNIEXPORT jbyte JNICALL
Java_com_example_srednew_i2c_I2CRead(JNIEnv *env, jobject thiz, jint high_address, jint low_address)
{
int ret;
jbyte buffer[2];
buffer[0] = (jbyte)high_address;
buffer[1] = (jbyte)low_address;
jbyte recive_buffer;
if (high_address > 15 || high_address < 0 || low_address > 255 || low_address < 0) {
__android_log_print(ANDROID_LOG_INFO, "at24cxx", "high_address or low_address error");
return -1;
}
ret = write(fd_at24cxx, buffer, 2);
if(ret < 0)//写入数据
{
__android_log_print(ANDROID_LOG_INFO, "at24cxx", "at24cxx write fail");
return -1;
}
ret = read(fd_at24cxx, &recive_buffer, 1);
if(ret < 0)//读出数据
{
__android_log_print(ANDROID_LOG_INFO, "at24cxx", "at24cxx read fail");
return -1;
}
return recive_buffer;
}
extern "C" JNIEXPORT int JNICALL
Java_com_example_srednew_i2c_I2CClose(JNIEnv *env, jobject thiz)
{
int ret;
ret = close(fd_at24cxx);
if (ret < 0) {
__android_log_print(ANDROID_LOG_INFO, "at24cxx", "at24cxx close fail");
} else {
__android_log_print(ANDROID_LOG_INFO, "at24cxx", "at24cxx close success");
}
return ret;
}