通过sysfs来写at24c02

在开发过程中需要一些寄存器的值需要在线修改验证效果,动态调整芯片的配置参数。通过sysfs来修改比较方便。这样不用专门写一个应用程序了。还是省略了头文件和出错处理部分。设备树部分I2C的配置也省略了。
代码只实现了写,没有实现读。格式是 echo 0x02=0x33 > /sys/下的节点。代码参考了100ask的i2c部分 和网上其他网友代码,只是用sysfs代替专门的app来写,不好的部分是我改的:)。


static struct i2c_client *at24c02_client;
static struct class *at24c02_class;
static struct device *my_at24c02;

static ssize_t eeprom_write(struct device* dev,
                                   struct device_attribute* attr,
                                   const char* buf,
                                   size_t count)
{
    unsigned char addr;
	unsigned char data;
	int result = 0;
	unsigned char byte_buf[2];
	struct i2c_msg msgs[1];
	int ret = 0;
	
	printk("the input is %s\n",buf);
	result = sscanf(buf, "0x%hhx=0x%hhx", &addr, &data);
	if (result != 2) {
    	printk("Invalid input format: %s\n", buf);
    	return -EINVAL;
	}	
	//dev_info(dev, "Writing addr 0x%02x = 0x%02x\n", addr, data);
	
	byte_buf[0] = addr;
	byte_buf[1] = data;
			
	msgs[0].addr  = at24c02_client->addr;
	msgs[0].flags = 0; /* 写 */
	msgs[0].len   = 2;
	msgs[0].buf   = byte_buf;

	ret = i2c_transfer(at24c02_client->adapter, msgs, 1);

	mdelay(20);
	return count;
}

static DEVICE_ATTR(at24reg, S_IWUSR | S_IWGRP, NULL, eeprom_write);



static int at24c02_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
	int result ;
	printk("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);

	at24c02_client = client;


	/* class_create */
	at24c02_class = class_create(THIS_MODULE, "at24c02_class");

	/* device_create */
	my_at24c02 = device_create(at24c02_class, NULL,0, NULL, "my_at24c02"); 
	
	result = device_create_file(my_at24c02, &dev_attr_at24reg);
	
	return 0;
}

static int at24c02_remove(struct i2c_client *client)
{
	printk("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);

	device_remove_file(my_at24c02 , &dev_attr_at24reg);
	device_destroy(at24c02_class, 0);
	class_destroy(at24c02_class);
	
	
	return 0;
}

static const struct of_device_id at24c02_of_match[] = {
	{.compatible = "100ask,at24c02"},
	{}
};

static const struct i2c_device_id at24c02_ids[] = {
	{ "xxxxyyy",	(kernel_ulong_t)NULL },
	{ /* END OF LIST */ }
};

static struct i2c_driver at24c02_drv = {
	.driver = {
		.name = "my24c02",
		.of_match_table	 = at24c02_of_match,
	},
	.probe = at24c02_probe,
	.remove = at24c02_remove,
	.id_table = at24c02_ids,
};

static int at24c02_init(void)
{
	int err;
	err = i2c_add_driver(&at24c02_drv);
	printk("%s %s %d, err = %d\n", __FILE__, __FUNCTION__, __LINE__, err);
	return err;
}

static void at24c02_exit(void)
{
	i2c_del_driver(&at24c02_drv);
}

module_init(at24c02_init);
module_exit(at24c02_exit);

MODULE_LICENSE("GPL");
posted @ 2026-03-09 23:17  michael2025  阅读(1)  评论(0)    收藏  举报