linux下通过i2c总线读写EEPROM

本文介绍了如何在Linux系统下通过I2C总线实现对EEPROM的批量读写操作,包括一次性写入大量内容和可选择性地一次性读取大量内容。提供了一个示例程序,演示了读写命令的不同用法,并包含了i2c读写函数的详细实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

by 韩大卫@吉林师范大学

handawei@jusontech.com

转载请务必表明出处。

我的上篇文章《Linux下使用I2C总线读写 EEPROM(读写i2c从设备通用程序)》给出了通过IIC总线,如何读写EEPROM相应位置的内容。

但是有一些功能没有实现:

比如:  只能单独操作一个寄存器地址,不能一次性写入大量内容;
    只能读一个寄存器的数值,不能可选择性地一次读出大量内容;

这是由于为了做到通用化,我们的i2c没有一次性大量读写的功能。 在本程序中针对EEPROM做了一些改进,详细说明可以在help_info() 中找到。

FOR EXAMPLE:

    eep -r  0x08                        Display the contents of EEPROM from 0x00 to 0x08

    eep -ro 0x08                        Display the contents of EEPROM from 0x08

    eep -r  0x02 0x80                    Display the contents of EEPROM from address 0x20 to x080

    eep -s  0x04 "hello world!"                Write "hello world!" to EEPROM from 0x04

    eep -d /dev/i2c-1 -s  0x04 "hello world!"        Write "hello world!" to EEPROM from 0x04 with path"/dev/i2c-1"

*************************************************************

以下是具体代码:

main.c

********************** *******************************

#include "i2c.h"

#define TIMEOUT        4
#define RETRY        2
#define READ_ONLY    1

static int fd ;
static int addr = 0x57;  // EEPROM addr
static int offset;
static int offset_end;

inline int read_data(u16 addr, u8 offset, u8 *val){
    int ret;
   
    ret = i2c_read_data(addr,offset,val);
    if(ret < 0){
        printf("%s error!\n",__FUNCTION__);
        exit(-1);
    }
    return 0;
}

inline int write_data(u16 addr, u8 offset, u8 val){
    int ret;
   
    ret = i2c_write_data(addr,offset,val);
    if(ret < 0){
        printf("%s:error = %s\n",__FUNCTION__,strerror(errno));
        exit(-1);
    }
    usleep(10000);    // 重要!
    return 0;
}

int eep_write(u16 addr,u8 offset,char* argv){
    //u8 data = (u8)strtoul(argv,0,16);

    int i,j,len    = 0;
    char* data    = argv;
   
    while( *data++ ){
        len++;
    }
    data = argv;

    printf("len = %d\n",len);

    for( i = offset ,j = 0;i < offset + len ;i++,j++ ){
        write_data(addr,i,data[j]);
    }
    printf("write success,data = %s\n",argv);
    return 0;
}

int eep_read(u16 addr,u8 offset_start,u8 offset_end,int flags){
   
    int i;
    u8 buf[256] = {0};

    if( flags ){
        read_data(addr,offset_end,&am

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值