首先创建一个class结构体指针
static struct class *sensor_class;
然后在module_init的模块加载函数中调用以下接口:
sensor_class = class_create(THIS_MODULE, "sensor_class");
ret = class_create_file(sensor_class, &class_attr_gyro_lsm9ds1);
if (ret) {
printk(KERN_ERR "%s:Fail to creat gyro class file\n", __func__);
return ret;
}
然后调用CLASS_ATTR创建节点,这里是gyro_lsm9ds1:
static CLASS_ATTR(gyro_lsm9ds1, 0664, gyro_lsm9ds1_show, gyro_lsm9ds1_store);
然后创建读写函数(adb使用cat或者echo可以操作节点读写):
1、读函数(cat):
376 static ssize_t gyro_lsm9ds1_show(struct class *class,
377 struct class_attribute *attr, char *buf)
378 {
379 struct sensor_private_data *sensor = g_sensor[SENSOR_TYPE_ACCEL]; // gyro no device, so use SENSOR_TYPE_ACCEL
380
381 if(sensor == NULL)
382 return sprintf(buf, "no gyro sensor find\n");
383
384 if (sensor->status_cur == SENSOR_OFF)
385 dev_err(&sensor->client->dev, "%s: status_cur: off[%d]\n", __func__, SENSOR_OFF);
386
387 if (sensor->status_cur == SENSOR_ON)
388 return sprintf(buf, "[gyro-x-]: %d\n \n[gyro-y-]: %d\n \n[gyro-z-]: %d\n", gyro_lsm9ds1_x, gyro_lsm9ds1_y, gyro_lsm9ds1_z);
389
390 return sprintf(buf, "temhum: read error with SENSOR_OFF\n");
391
392 }
2、写函数(echo):
394 static ssize_t gyro_lsm9ds1_store(struct class *class,
395 struct class_attribute *attr, const char *buf, size_t count)
396 {
397 struct sensor_private_data *sensor = g_sensor[SENSOR_TYPE_GYROSCOPE];
398 int val, ret;
399
400 if (sensor == NULL)
401 return -1;
402
403 ret = kstrtoint(buf, 10, &val);
404 if (ret) {
405 dev_err(&sensor->client->dev, "%s: kstrtoint error return %d\n", __func__, ret);
406 return -1;
407 }
408
409 mutex_lock(&sensor->operation_mutex);
410 if (val == 1) {
411 if (sensor->status_cur == SENSOR_OFF)
412 sensor_enable(sensor, SENSOR_ON);
413 } else if (val == 0) {
414 if (sensor->status_cur == SENSOR_ON)
415 sensor_enable(sensor, SENSOR_OFF);
416 }
417 mutex_unlock(&sensor->operation_mutex);
418
419 dev_err(&sensor->client->dev, "[%s()]check ret[%d] with value[%d]\n", __func__, ret, val);
420
421 return ret ? ret : count;
422
423 }
然后就可以在adb操作节点读到数据:
rk3399_all:/ # cat sys/class/sensor_class/gyro_lsm9ds1
[gyro-x-]: 69
[gyro-y-]: -10
[gyro-z-]: 156
rk3399_all:/ #