ioctl函数:
static long xxx_ioctl(struct file*filp,unsigned int cmd,unsigned long arg);
第二参数:cmd
#define _IOWR(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))
第三个参数:
可以根据cmd的不一样,可以不传参数
a:传整数
b:指针 通过指针传递
例子:
cmd:
- I2C_RDWR, takes pointer to struct i2c_rdwr_ioctl_data
#define I2C_RDWR 0x0707 /* Combined R/W transfer (one STOP only) */
arg:
/* This is the structure as used in the I2C_RDWR ioctl call */
struct i2c_rdwr_ioctl_data {
struct i2c_msg __user *msgs; /* pointers to i2c_msgs */
__u32 nmsgs; /* number of i2c_msgs */
};
struct i2c_msg {
__u16 addr; /* slave address */
__u16 flags;
#define I2C_M_RD 0x0001 /* read data, from slave to master */
/* I2C_M_RD is guaranteed to be 0x0001! */
#define I2C_M_TEN 0x0010 /* this is a ten bit chip address */
#define I2C_M_DMA_SAFE 0x0200 /* the buffer of this message is DMA safe */
/* makes only sense in kernelspace */
/* userspace buffers are copied anyway */
#define I2C_M_RECV_LEN 0x0400 /* length will be first received byte */
#define I2C_M_NO_RD_ACK 0x0800 /* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_IGNORE_NAK 0x1000 /* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_REV_DIR_ADDR 0x2000 /* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_NOSTART 0x4000 /* if I2C_FUNC_NOSTART */
#define I2C_M_STOP 0x8000 /* if I2C_FUNC_PROTOCOL_MANGLING */
__u16 len; /* msg length */
__u8 *buf; /* pointer to msg data */
};
使用例子:
写过程:
struct i2c_rdwr_ioctl_data rdwr;
struct i2c_msg msgs[1] = {0};
unsigned char *pbuf = NULL;
int i = 0;
if (nfds < 0)
{
return -1;
}
pbuf = (uint8_t *)malloc(1 + n);
if (pbuf == NULL) {
return -1;
}
pbuf[0] = nReg_addr & 0xFF;
for (i = 1; i <= n; i++) {
pbuf[i] = pData[i - 1];
}
msgs[0].len = 1 + n;
msgs[0].addr = nSlave_addr;
msgs[0].flags = 0;
msgs[0].buf = pbuf;
rdwr.msgs = msgs;
rdwr.nmsgs = 1;
if (ioctl(nfds, I2C_RDWR, &rdwr) < 0)
{
}
free(pbuf);
读过程:
struct i2c_rdwr_ioctl_data rdwr;
struct i2c_msg msgs[2] = {0};
uint8_t pbuf0[1];
uint8_t *pbuf = NULL;
int i;
if (nfds < 0)
{
return -1;
}
pbuf = (uint8_t *)malloc(n);
if (NULL == pbuf)
{
return -1;
}
pbuf0[0] = nReg_addr & 0xFF;
msgs[0].len = 1;
msgs[0].addr = nSlave_addr;
msgs[0].flags = 0;
msgs[0].buf = pbuf0;
msgs[1].addr = nSlave_addr;
msgs[1].flags |= I2C_M_RD;
msgs[1].buf = pbuf;
msgs[1].len = n;
rdwr.msgs = msgs;
rdwr.nmsgs = 2;
if (ioctl(nfds, I2C_RDWR, &rdwr) < 0)
{
I2C_ERROR((" failed: %s\n", strerror(errno)));
}
for (i = 0; i < n; i++)
{
pData[i] = pbuf[i];
}
free(pbuf);
pbuf = NULL;