您的位置:首页 > 移动开发

Writing I2C application code on NuttX

2018-02-11 14:33 1606 查看

Writing I2C application code on NuttX

Here is an I2C example code on NuttX, I have tested it on Atmel SAMV71 XPlained Pro Ultra:

int i2c_demo(int argc, char *argv[])
{
int fd;
uint8_t mac_offset;
uint8_t mac[6];
struct i2c_msg_s i2c_msg[2];
struct i2c_transfer_s i2c_transfer;
int ret;
char i2c_path[] = "/dev/i2c0";
uint32_t trytime = 0;

begin:
fd = open(i2c_path, O_RDONLY);

if (fd < 0)
{
ret = -errno;
goto outs;
}

/************************************************************************/
/* AT24MAC402 Sequence Read - Reading address 0x9A                      */
/* (AT24MAC402 Address + Write) + (0x9A) + (AT24MAC402 Address + Read)  */
/************************************************************************/
mac_offset = AT24XX_MACADDR_OFFSET;
i2c_msg[0].addr   = CONFIG_AT24XX_ADDR;
i2c_msg[0].flags  = 0;
i2c_msg[0].buffer = &mac_offset;
i2c_msg[0].length = 1;  /* Write address of where we want to read to AT24 */
i2c_msg[0].frequency = 400000;  /* 400K bsp */

i2c_msg[1].addr   = CONFIG_AT24XX_ADDR;
i2c_msg[1].flags  = I2C_M_READ; /* Write command then sequence read data */
i2c_msg[1].buffer = mac;
i2c_msg[1].length = 6;
i2c_msg[1].frequency = 400000;  /* 400K bsp */

i2c_transfer.msgv = (struct i2c_msg_s *)i2c_msg;
i2c_transfer.msgc = 2;

for (trytime = 0; trytime < 20; trytime++)
{
memset(mac,0,6);

/* Read the MAC address */
ret = ioctl(fd, I2CIOC_TRANSFER, (unsigned long)&i2c_transfer);
if (ret < 0)
{
fprintf(stderr, "ERROR: AT24 ioctl(I2CIOC_TRANSFER) failed: %d\n", ret);
goto finish;
}

printf("MAC in EEPROM: %02x:%02x:%02x:%02x:%02x:%02x\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

sleep(2);
}

finish:
ret = close(fd);
outs:
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  NuttX I2C
相关文章推荐