uboot eeprom读写实例

例子1

读取eeprom里的内容:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    if (argc!= 2) {
        printf("Usage: %s <address>\n", argv[0]);
        return -1;
    }

    int fd;
    int address = (int)strtol(argv[1], NULL, 0);
    char buf[1024] = {0};

    fd = open("/sys/bus/i2c/devices/0-0056/eeprom", O_RDWR);
    if (fd < 0) {
        printf("####i2c test device open failed####\n");
        return -1;
    }

    if (lseek(fd, address, SEEK_SET) < 0) {
        printf("Failed to seek to address 0x%x.\n", address);
        close(fd);
        return 1;
    }

    ssize_t size = read(fd, buf, sizeof(buf));
    if (size < 0) {
        printf("read error at address 0x%x\n", address);
        close(fd);
        return 1;
    }

    printf("Data at address 0x%x:\n", address);
    for (int i = 0; i < size; i++) {
        printf("%02x ", buf[i]);
    }
    printf("\n");

    close(fd);

    return 0;
}

./test  0x4

例子2:

可以读出16进制数据 还以要转话成字符串:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <ctype.h>

int main(int argc, char *argv[]) {
    if (argc!= 2) {
        printf("Usage: %s <address>\n", argv[0]);
        return -1;
    }

    int fd;
    int address = (int)strtol(argv[1], NULL, 0);
    char buf[1024] = {0};

    fd = open("/sys/bus/i2c/devices/0-0056/eeprom", O_RDWR);
    if (fd < 0) {
        printf("####i2c test device open failed####\n");
        return -1;
    }

    if (lseek(fd, address, SEEK_SET) < 0) {
        printf("Failed to seek to address 0x%x.\n", address);
        close(fd);
        return 1;
    }

    ssize_t size = read(fd, buf, sizeof(buf));
    if (size < 0) {
        printf("read error at address 0x%x\n", address);
        close(fd);
        return 1;
    }

    // 找到第一个 null 字符并截断字符串
    for (int i = 0; i < size; i++) {
        if (buf[i] == '\0') {
            size = i;
            break;
        }
    }

    // 将缓冲区转换为字符串并打印
    char *str = (char *)malloc(size + 1);
    memcpy(str, buf, size);
    str[size] = '\0';
    printf("Data at address 0x%x as string: %s\n", address, str);
    free(str);

    close(fd);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值