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

📄 oc_i2c.c

📁 nios ii sopc关于ISP1362和DM9000A的工程
💻 C
字号:
#include "system.h"
#include "oc_i2c_regs.h"
#include "alt_types.h"

void I2CWaitTIP(alt_u32 base);

void InitI2C(alt_u32 base, alt_u32 freq, alt_u8 IEN)
{
	alt_u32 prescale;
	// Calculate the prescale value
	prescale = ALT_CPU_FREQ/((freq<<2) + freq);
  // Setup prescaler for the freq of SCL with sysclk of ALT_CPU_FREQ
  IOWR_OC_I2C_PRERLO(base, prescale & 0xff);
  IOWR_OC_I2C_PRERHI(base,(prescale & 0xff00)>>8);
  // Enable core
  if(IEN == 1) // Enable interrupt
  {
  	IOWR_OC_I2C_CTR(base, 0xC0);
  }
  else // Enable core while disable interrupt
  {
  	IOWR_OC_I2C_CTR(base, 0x80);
  }
}


void I2CWaitTIP(alt_u32 base)
{
  while ((IORD_OC_I2C_SR(base) & I2C_SR_TIP) > 0) {}
}


void I2CWrite(alt_u32 base, alt_u8 address, alt_u8 reg, alt_u8 *buf, alt_u16 num)
{
	alt_u16 i,tmp;
	// Wait for the completion of transfer
	I2CWaitTIP(base);
 
  // write address of I2C slave device
  // and generate START & WR command
  IOWR_OC_I2C_TXR(base, address);
  IOWR_OC_I2C_CR(base, I2C_CR_STA | I2C_CR_WR);
  I2CWaitTIP(base);

  // write register address
  IOWR_OC_I2C_TXR(base, reg);
  IOWR_OC_I2C_CR(base, I2C_CR_WR);
  I2CWaitTIP(base);

  // write data
  if(num > 0) 
  {
  	tmp = num - 1;
  	for(i=0; i<tmp; i++)
  	{
  		 IOWR_OC_I2C_TXR(base,*buf++);
       IOWR_OC_I2C_CR(base, I2C_CR_WR);
       I2CWaitTIP(base);
  	}
  }

  // write data with STOP signal
  IOWR_OC_I2C_TXR(base, *buf);
  IOWR_OC_I2C_CR(base, I2C_CR_WR | I2C_CR_STO);
  I2CWaitTIP(base);
}


void I2CRead(alt_u32 base, alt_u8 address, alt_u8 reg, alt_u8 *buf, alt_u16 num)
{
	alt_u16 i,tmp;
	// Wait for the completion of transfer
	I2CWaitTIP(base);
 
  // write address of I2C slave device
  // and generate START & WR command
  IOWR_OC_I2C_TXR(base, address);
  IOWR_OC_I2C_CR(base, I2C_CR_STA | I2C_CR_WR);
  I2CWaitTIP(base);

  // write register address
  IOWR_OC_I2C_TXR(base, reg);
  IOWR_OC_I2C_CR(base, I2C_CR_WR);
  I2CWaitTIP(base);

  // write address of I2C slave device
  // and RD command
  IOWR_OC_I2C_TXR(base, address|1);
  IOWR_OC_I2C_CR(base, I2C_CR_STA | I2C_CR_WR);
  I2CWaitTIP(base);
  // Read data
  if(num > 0) 
  {
  	tmp = num - 1;
  	for(i=0; i<tmp; i++)
  	{
  		 IOWR_OC_I2C_CR(base,I2C_CR_RD);// | I2C_CR_ACK); 
       I2CWaitTIP(base);
       *buf++ = IORD_OC_I2C_RXR(base);
  	}
  }

  // Read data with STOP signal
  IOWR_OC_I2C_CR(base,I2C_CR_RD | I2C_CR_ACK | I2C_CR_STO); 
  I2CWaitTIP(base);
  *buf++ = IORD_OC_I2C_RXR(base);
}


⌨️ 快捷键说明

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