专栏中心

EEPW首页 > 专栏 > Linux 下测试 I2C 通讯

Linux 下测试 I2C 通讯

发布人:电子禅石 时间:2024-01-28 来源:工程师 发布文章
#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:对应的arg取值为0:从机地址为7 bit;对应的arg取值为1:从机地址为10bit
    ioctl(fd, I2C_TENBIT, bits); //not 10bit
    ioctl(fd, I2C_SLAVE, chipAddr); //设置I2C从设备地址[6:0]


    write(fd,buf,1); /* 发送子地址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

*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。

关键词: I2C

相关推荐

用示波器对单片机I2C时序进行图形波形分析的试验小结

嵌入式系统 2024-01-17

低速串行总线调试-I2C译码

视频 2010-01-13

看时序图写I2C驱动,教你如何自己手撸非标I2C驱动函数

嵌入式系统 2025-08-18

数字温度传感器系统接口:SPI、I2C 、SMBus如何选

在Linux环境下I2C总线EEPROM驱动程序应该如何设计

嵌入式系统 2018-07-30

Nexperia推出先进的I2C GPIO扩展器产品组合

学前班第1课第2.2节_怎么看原理图之协议类接口之I2C

视频 2013-10-14

MSP430与液晶显示器的串行接口方案

I2C总线协议V2.1

LED驱动器中I2C的LED控制方式

光电显示 2023-06-08

浅析嵌入式总线技术的原理、分类及技术指标

嵌入式系统 2018-07-31

I2C规格

STM32视频-Inter Integrated Circuit(I2C)

视频 2013-03-06

I2C Manual AN10216-01

I2C通讯不了?是不是硬件有问题?

2024-03-28

I2C Logic Selection Guide

集成电路(I2C)总线市场趋势、需求和创新2025-2035

Microchip温度传感器系列产品

更多 培训课堂
更多 焦点
更多 视频

技术专区