原创作品,允许转载,转载时请务必以超链接形式标明文章
原始出处 、作者信息和本声明。否则将追究法律责任。
http://ticktick.blog.51cto.com/823160/761830
- struct tvp5158_dev{
- struct cdev cdev;
- int major;
- struct semaphore semLock;
- };
- // global dev object
- struct tvp5158_dev g_tvp5158_dev;
- struct file_operations tvp5158_dev_FileOps = {
- .owner = THIS_MODULE,
- .open = tvp5158_devOpen,
- .release = tvp5158_devRelease,
- .ioctl = tvp5158_devIoctl,
- };
- static int tvp5158_devOpen(struct inode *inode, struct file *filp)
- {
- printk(KERN_INFO "I2C: tvp5158_devOpen, %4d, %2d \n", major, minor);
- filp->private_data = NULL;
- return 0;
- }
- static int tvp5158_devRelease(struct inode *inode, struct file *filp)
- {
- printk(KERN_INFO "I2C: tvp5158_devRelease");
- return 0;
- }
- #define I2C_CMD_READ (0x01)
- #define I2C_CMD_WRITE (0x02)
- struct I2C_Param{
- uint8_t *reg;
- uint8_t *value;
- };
- static int tvp5158_devIoctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg)
- {
- uint8_t reg,data;
- struct I2C_Param param;
- down_interruptible(&g_tvp5158_dev.semLock);
- // get i2c param from userspace
- copy_from_user(¶m, (void *)arg, sizeof(param));
- switch(cmd){
- case I2C_CMD_WRITE:
- {
- copy_from_user(®, param.reg,sizeof(uint8_t));
- copy_from_user(&data,param.value,sizeof(uint8_t));
- tvp5158_i2c_write(&g_tvp5158_obj->client, reg, data);
- break;
- }
- case I2C_CMD_READ:
- {
- copy_from_user(®, param.reg,sizeof(uint8_t));
- tvp5158_i2c_read(&g_tvp5158_obj->client, reg, &data);
- copy_to_user(param.value,&data,sizeof(uint8_t));
- break;
- }
- default:
- break;
- }
- up(&g_tvp5158_dev.semLock);
- return 0;
- }
- static int __init tvp5158_i2c_init(void)
- {
- int result;
- dev_t dev = 0;
- result = alloc_chrdev_region(&dev, 0, 1, “tvp5158_dev”);
- if (result < 0) {
- printk(KERN_WARNING "I2C: can't get device major num \n");
- return result;
- }
- g_tvp5158_dev.major = MAJOR(dev);
- sema_init(&g_tvp5158_dev.semLock, 1);
- cdev_init(&g_tvp5158_dev.cdev, &tvp5158_dev_FileOps);
- g_tvp5158_dev.cdev.owner = THIS_MODULE;
- g_tvp5158_dev.cdev.ops = &tvp5158_dev_FileOps;
- cdev_add(&g_tvp5158_dev.cdev, dev, 1);
- return i2c_add_driver(&tvp5158_i2c_driver);;
- }
- static void __exit tvp5158_i2c_exit(void)
- {
- dev_t devno = MKDEV(g_tvp5158_dev.major, 0);
- i2c_del_driver(&tvp5158_i2c_driver);
- cdev_del(&g_tvp5158_dev.cdev);
- unregister_chrdev_region(devno, 1);
- }
- // 假设生成的模块.ko名称为 tvp5158.ko
- 第一步:insmod tvp5158.ko
- // 假设上面tvp5158_i2c_init函数中 g_tvp5158_dev.major 的值为 74
- 第二步:mknod /dev/tvp5158_dev c 74 0
- #include <stdio.h>
- int main()
- {
- int status;
- struct I2C_Param param;
- unit8_t reg = 0x08;
- unit8_t value = 0;
- int fd = open("/dev/tvp5158_dev", O_RDWR);
- if( fd < 0)
- {
- return -1;
- }
- param.reg = ®
- param.value = &value;
- status = ioctl(fd,I2C_CMD_READ,¶m);
- if( status < 0)
- {
- printf("read fail!\n");
- return -1;
- }
- printf("the 0x80 reg 's value = %d\n",value);
- close(fd);
- return 0;
- }