博客專欄

        EEPW首頁 > 博客 > Linux 下測(cè)試 I2C 通訊

        Linux 下測(cè)試 I2C 通訊

        發(fā)布人:電子禪石 時(shí)間:2024-01-28 來源:工程師 發(fā)布文章
        #include <stdio.h>
        #include <fcntl.h>
        #include <unistd.h>
        #include <stdlib.h>
        #include <sys/types.h>
        #include <sys/ioctl.h>
        #include <linux/i2c.h>
        #include <linux/i2c-dev.h>
        
        
        #define I2C_DEV "/dev/i2c-1"
        #define CHIP_ADDR 0xD6
        
        
        int main(int argc, char *argv[])
        {
            int i = 0, fd = -1;
            int bits = 0;
            int chipAddr = 0xd6;
            unsigned char buf[1]={0x0f};
            unsigned char recbuf[8];
        
        
            if(argc <= 1)
            {
                printf("Usage: i2ctest device_addr device_name bitsel \n");
                return -1;
            }
        
        
            chipAddr = atoi(argv[1]);
            printf("Device addr: 0x%x \n", chipAddr);
        
        
            printf("Device name: %s \n", argv[2]);
        
        
            bits = atoi(argv[3]);
            if(bits == 0 || bits == 1)
                printf("Bit select: %s \n", bits == 0? "7 bit": "10 bit" );
            else
            {
                printf("bits error \n");
                return -1;
            }
        
            fd = open(argv[2], O_RDWR);// I2C_DEV /dev/i2c-0
            if(fd < 0)
            {
                printf("####i2c test device open failed####\n");
                return -1;
            }
        
        
            // I2C_TENBIT:對(duì)應(yīng)的arg取值為0:從機(jī)地址為7 bit;對(duì)應(yīng)的arg取值為1:從機(jī)地址為10bit
            ioctl(fd, I2C_TENBIT, bits); //not 10bit
            ioctl(fd, I2C_SLAVE, chipAddr); //設(shè)置I2C從設(shè)備地址[6:0]
        
        
            write(fd,buf,1); /* 發(fā)送子地址0 */
            usleep(200000);
            read(fd, recbuf, 8);
        
        
            printf("\nReceived data: ");
            for(i = 0; i < 8; i++)
            {
                printf("0x%02x ", recbuf[i]);
            }
            printf("\nEnd \n");
            return 0;
        }

        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

        *博客內(nèi)容為網(wǎng)友個(gè)人發(fā)布,僅代表博主個(gè)人觀點(diǎn),如有侵權(quán)請(qǐng)聯(lián)系工作人員刪除。



        關(guān)鍵詞: I2C

        相關(guān)推薦

        技術(shù)專區(qū)

        關(guān)閉
        主站蜘蛛池模板: 营山县| 郓城县| 云林县| 伊金霍洛旗| 扎赉特旗| 文安县| 古丈县| 治县。| 嵊州市| 华阴市| 武义县| 长泰县| 麻城市| 广东省| 云阳县| 裕民县| 建宁县| 遂川县| 陈巴尔虎旗| 荥阳市| 铁力市| 台东市| 陕西省| 耒阳市| 乌海市| 于田县| 鹿邑县| 大洼县| 洛川县| 苍南县| 遵义市| 阿鲁科尔沁旗| 清丰县| 沙田区| 泌阳县| 宝兴县| 大庆市| 霍山县| 乐陵市| 团风县| 丰都县|