⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test-iic.c

📁 ARM Linux2.4 IIC总线编程 非常好
💻 C
字号:
/*********************************************************************
* File:		test-iic.c
* Author:	
* Desc:		IIC bus test example, read from or write to EEPROM.
* History:		
*				Original version, 2005.4 Embest
*				Program modify, 2005.06.05 Embest R.X.Huang <hungrx@embedinfo.com> 
*********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <linux/i2c.h>
#include <linux/fcntl.h>

/* control code */
#define I2C_SET_DATA_ADDR	0x0601
#define I2C_SET_BUS_CLOCK	0x0602

/* AT24C04N EEPROM definition */
#define SLAVE_ADDR		0x50
#define PAGE_NUM		1	//32 //--- only one page
#define PAGE_SIZE		16

/* buffer */
char w_buf[PAGE_NUM*PAGE_SIZE];
char r_buf[PAGE_NUM*PAGE_SIZE];

int main(int argc, char** argv)
{
	int i, fd;
	static char *driver = "/dev/i2c/0";
	
	printf(" EEPROM Read/Write Example base on Linux.\n");
	/* open device */
	fd = open(driver, O_RDWR);
	if(fd < 0)
	{
		printf("device open fail\n");
		return -1;
	}
	/* set AT24C04N slave address  (0xa0 >> 1) */
	ioctl(fd, I2C_SLAVE_FORCE, SLAVE_ADDR);
	/* set i2c bus clock 250KHz */
	ioctl(fd, I2C_SET_BUS_CLOCK, 250*1000);

	/* initialize write buffer */
	printf("Write random data...\n");
	srand(time(NULL));
	for(i=0; i<PAGE_NUM*PAGE_SIZE; i++)
	{
		w_buf[i] = rand()%0xff;
	}
	for(i=0; i<PAGE_NUM*PAGE_SIZE; i++)
	{
		printf("%d ", w_buf[i]);
	}
	printf("\n");

	/* write data to AT24C04N EEPROM */
	for(i=PAGE_NUM-1; i>=0; i--)
	{
		/* AT24C04N inner data access address */
		ioctl(fd, I2C_SET_DATA_ADDR, i*PAGE_SIZE);
		write(fd, &w_buf[i*PAGE_SIZE], PAGE_SIZE);
		/* delay some time for write nonvolatile memory. */
		usleep(10*1000);
	}

	/* read data from AT24C04N EERROM */
	printf("Read data...\n");
	for(i=0; i<PAGE_NUM; i++)
	{
		/* AT24C04N inner data access address */
		ioctl(fd, I2C_SET_DATA_ADDR, i*PAGE_SIZE);
		read(fd, &r_buf[i*PAGE_SIZE], PAGE_SIZE);
	}

	/* print data */
	for(i=0; i<PAGE_NUM*PAGE_SIZE; i++)
	{
		printf("%d ", r_buf[i]);
	}
	printf("\n");

	/* compare data */
	if(memcmp(w_buf, r_buf, PAGE_NUM*PAGE_SIZE) == 0)
	{
		printf(" ---- Verify data successful ---- \n");
	}
	else
	{
		printf(" ---- Verify data failed ---- \n");
	}

	printf(" end.\n");
	close(fd);

	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -