linux I2c FM24C256应用层代码

由于机器挂了两个I2C所以应用层也需要操作两个


#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <fcntl.h>

#include <termios.h>

#include <string.h>

#include <sys/ioctl.h>

#include <linux/i2c-dev.h>

#include "log/log.h"

#include "include/root.h"

#include "24c256.h"

int fd_eeprom[MAXNUM_E2P] = {-1, -1};

int i2c_init(unsigned int port)

{

    int fd;

    int addr=0x52;

    if(port >= MAXNUM_E2P)

        return 1;



    if(-1 != fd_eeprom[port])

        close(fd_eeprom[port]);

    fd = open("/dev/i2c-0",O_RDWR);

    if(fd==-1)

    {

        print_log(LOGLVL_ERROR,"cann't open i2c device");

        return 1;

    }

    print_log(LOGLVL_DEBUG,"open i2c device\n");

    fd_eeprom[port] = fd;

    eep_rcvst[port].len = 0;

    memset(&eep_rcvst[port].buf[0],0,SIZE_I2C_RCVBUF);

    if(ioctl(fd,I2C_SLAVE_FORCE,addr)<0 ) printf("error\n");

    if(ioctl(fd,I2C_TIMEOUT,1)<0)   printf("error\n");

    if(ioctl(fd,I2C_RETRIES,10)<0)   printf("error\n");

    return 0;

}

void appi2c_close(unsigned int port)

{

    if((port >= MAXNUM_E2P) || (-1 == fd_eeprom[port]))

        return;



    close(fd_eeprom[port]);

    fd_eeprom[port] = -1;

}

//buf[0] address message

//buf[1]开始是真正的内容

int appi2c_write(unsigned int port,int addr, unsigned char *buf, int len)

{

    int fd;

    unsigned char write_buf[SIZE_I2C_RCVBUF];

    memset(write_buf,0,sizeof(write_buf));

    if(port >= MAXNUM_E2P)

        return 1;

    fd = fd_eeprom[port];

    if(fd< 0)

        return 1;

    write_buf[0]=(addr>>8)&0xff;

    write_buf[1]=addr&0xff;

    memcpy(&write_buf[2],buf,len);

    if( write(fd,write_buf,len+2)!=len+2)

    {

        printf("error,i2c write\n");

    }

    return 0;

}



int appi2c_recv(unsigned int port, int addr, int len)

{

    int fd, rtn;

    char address[2];

    if(port >= MAXNUM_E2P)

        return -1;

    fd = fd_eeprom[port];

    if(fd < 0)

        return -1;

    memset(&eep_rcvst[port].buf[0],0,SIZE_I2C_RCVBUF);

    address[0]=(addr>>8)&0xff;

    address[1]=addr&0xff;

    if(write(fd,address,2)!=2)

    {

        printf("error,i2c write\n");

    }

    if(eep_rcvst[port].len>= 0)

    {

        eep_rcvst[port].len = 0;

        rtn = read(fd,eep_rcvst[port].buf,len);

        if((rtn<0)||(rtn > SIZE_I2C_RCVBUF))

        {

            printf("error,i2c read,rtn=%d\n",rtn);

            return 0;

        }

        eep_rcvst[port].len = rtn;

    }

    if(eep_rcvst[port].len > len)

        rtn = len;

    else

        rtn = eep_rcvst[port].len;

    // memcpy(buf, &eep_rcvst[port].buf[eep_rcvst[port].head], rtn);

 //   app_sleep(200);

    return rtn;

}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值