i2c.c
来自「AVR,系列单片机MEGA48应用例程,包括原理图,代码基本包括全部资源的配置应」· C语言 代码 · 共 86 行
C
86 行
#include"I2C.H"
#ifdef IAR_DEMO
#include <iom48.h>
#include <ioavr.h>
#include <inavr.h>
#else
#include <iom48v.h>
#include <macros.h>
#endif
unsigned char i2c_Write(unsigned char Addr,unsigned char Write_Byte)
{
// PORTC|=0x30;
Start();//I2C启动
Wait();
if(TestAck()!=START)
goto end_i2c_write;
Write8Bit(wr_device_add);//写I2C从器件地址和写方式
Wait();
if(TestAck()!=MT_ADDR_ACK)
goto end_i2c_write;
Write8Bit(Addr); //写24C02的ROM地址
Wait();
if(TestAck()!=MT_DATA_ACK)
goto end_i2c_write;
Write8Bit(Write_Byte);//写数据到24C02的ROM
Wait();
if(TestAck()!=MT_DATA_ACK)
goto end_i2c_write;
Stop();//I2C停止
return 1;
end_i2c_write:
Stop();//I2C停止
return 0;
}
/******************************************
I2C总线读一个字节(Mega8 as Master)
如果读失败也返回0
*/
unsigned char i2c_Read(unsigned char Addr, unsigned char * Read_Byte) //this is a sample of reading 24c01(EEPROM)
{
// PORTC|=0x30;
Start();//I2C启动
Wait();
if (TestAck()!=START)
goto end_i2c_read;//ACK
Write8Bit(wr_device_add);//写I2C从器件地址和写方式
Wait();
if (TestAck()!=MT_ADDR_ACK)
goto end_i2c_read;//ACK
Write8Bit(Addr);//写24C02的ROM地址
Wait();
if (TestAck()!=MT_DATA_ACK)
goto end_i2c_read;;
Start();//I2C重新启动
Wait();
if (TestAck()!=RE_START)
goto end_i2c_read;
Write8Bit(rd_device_add);//写I2C从器件地址和读方式
Wait();
if(TestAck()!=MR_ADDR_ACK)
goto end_i2c_read;
Twi();//启动主I2C读方式
Wait();
if(TestAck()!=MR_DATA_NOACK)
goto end_i2c_read;
*Read_Byte=TWDR;//读取I2C接收数据
Stop();//I2C停止
return 1;
end_i2c_read:
Stop();//I2C停止
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?