Linux使用CLASS_ATTR创建节点

首先创建一个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:/ #
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零意@

您的打赏将是我继续创作的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值