|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 怪兽同学 于 2022-10-18 10:01 编辑
输入:
root@firefly:/usr/local# gcc test.c -o i2c-test
root@firefly:/usr/local# ./i2c-test 107 /dev/i2c-1 1
预计输出:
Device addr: 0x6b
Device name: /dev/i2c-1
Bit select: 10 bit
Received data: 0x69 0x00 0x00 0x04 0x00 0x00 0x00 0x00
End
实际输出:
Device addr: 0x6b
Device name: /dev/i2c-1
Bit select: 10 bit
####i2c test device open failed####
问题:
fd_open失败,在/usr/local路径下未找到/dev文件夹,不知道该如何运行此代码,求大神指教
//fd = open(argv[2], O_RDWR);// I2C_DEV /dev/i2c-0
原文地址:blog.chinaunix.net/uid-15732309-id-5818382.html
代码如下:
#include <stdio.h>
2.#include <fcntl.h>
3.#include <unistd.h>
4.#include <stdlib.h>
5.#include <sys/types.h>
6.#include <sys/ioctl.h>
7.#include <linux/i2c.h>
8.#include <linux/i2c-dev.h>
9.
10.
11.#define I2C_DEV "/dev/i2c-1"
12.#define CHIP_ADDR 0xD6
13.
14.
15. int main(int argc, char *argv[])
16. {
17. int i = 0, fd = -1;
18. int bits = 0;
19. int chipAddr = 0xd6;
20. unsigned char buf[1]={0x0f};
21. unsigned char recbuf[8];
22.
23.
24. if(argc <= 1)
25. {
26. printf("Usage: i2ctest device_addr device_name bitsel \n");
27. return -1;
28. }
29.
30.
31. chipAddr = atoi(argv[1]);
32. printf("Device addr: 0x%x \n", chipAddr);
33.
34.
35. printf("Device name: %s \n", argv[2]);
36.
37.
38. bits = atoi(argv[3]);
39. if(bits == 0 || bits == 1)
40. printf("Bit select: %s \n", bits == 0? "7 bit": "10 bit" );
41. else
42. {
43. printf("bits error \n");
44. return -1;
45. }
46.
47. fd = open(argv[2], O_RDWR);// I2C_DEV /dev/i2c-0
48. if(fd < 0)
49. {
50. printf("####i2c test device open failed####\n");
51. return -1;
52. }
53.
54.
55. // I2C_TENBIT:对应的arg取值为0:从机地址为7 bit;对应的arg取值为1:从机地址为10bit
56. ioctl(fd, I2C_TENBIT, bits); //not 10bit
57. ioctl(fd, I2C_SLAVE, chipAddr); //设置I2C从设备地址[6:0]
58.
59.
60. write(fd,buf,1); /* 发送子地址0 */
61. usleep(200000);
62. read(fd, recbuf, 8);
63.
64.
65. printf("\nReceived data: ");
66. for(i = 0; i < 8; i++)
67. {
68. printf("0x%02x ", recbuf[i]);
69. }
70. printf("\nEnd \n");
71. return 0;
72. }
|
|