I2C bus protocol program
When I was making the program, I found Zhou Ligong's program on the Internet. I felt it was pretty good, so I reposted it. When using it, you must pay attention to the issues of sequence and time.
"i2c.h file"
//I2C bus integrated sending function, sending multiple bytes of data to the slave
bit I2C_Puts(
unsigned char SlaveAddr,
unsigned int SubAddr,
unsigned char SubMod,
char *that,
unsigned int Size
);
//I2C bus integrated receiving function, receiving multiple bytes of data from the slave
bit I2C_Gets
(
unsigned char SlaveAddr,
unsigned int SubAddr,
unsigned char SubMod,
char *that,
unsigned int Size
);
#endif
================================================================================================
"i2c.c file"
#include "I2C.h"
//Define delay variables for use in macro I2C_Delay()
unsigned char I2C_Delay_t;
#define I2C_Delay() {I2C_Delay_t = (I2C_DELAY_VALUE);while ( --I2C_Delay_t != 0 );}
void I2C_Start()
{
I2C_SDA = 1; I2C_Delay();
I2C_SCL = 1; I2C_Delay();
I2C_SDA = 0; I2C_Delay();
I2C_SCL = 0; I2C_Delay();
}
void I2C_Write(char dat)
{
unsigned char t = 8;
do
{
I2C_SDA = (bit)(dat & 0x80);
dat <<= 1;
I2C_SCL = 1; I2C_Delay();
I2C_SCL = 0; I2C_Delay();
} while ( --t != 0 );
}
char I2C_Read()
{
charm that;
unsigned char t = 8;
I2C_SDA = 1; //Before reading data, pull SDA high
do
{
I2C_SCL = 1;
I2C_Delay();
dat <<= 1;
if ( I2C_SDA ) dat |= 0x01;
I2C_SCL = 0;
I2C_Delay();
} while ( --t != 0 );
return that;
}
bit I2C_GetAck()
{
bit ack;
//Bus ready, accept response
I2C_SDA = 1; I2C_Delay();
I2C_SCL = 1; I2C_Delay();
ack = I2C_SDA;
I2C_SCL = 0;
I2C_Delay();
return ack;
}
/******************************************************************************
Function: I2C_PutAck()
Function: The host generates an acknowledge bit or a non-acknowledge bit
parameter:
ack=0: the host generates an acknowledge bit
ack=1: the host generates a non-acknowledge bit
illustrate:
The host should generate an acknowledge bit after receiving each byte of data.
After receiving the last byte of data, the host should generate a non-acknowledge bit.
******************************************************************************/
void I2C_PutAck(bit ack)
{
I2C_SDA = ack; I2C_Delay();
I2C_SCL = 1; I2C_Delay();
I2C_SCL = 0; I2C_Delay();
}
/******************************************************************************
Function: I2C_Stop()
Function: Generate the stop state of the I2C bus
illustrate:
When a rising edge appears on SDA while SCL is at a high level, the I2C bus is stopped.
Regardless of the level of SDA and SCL, this function can always correctly generate the stop state
After this function is executed, the I2C bus is in idle state
******************************************************************************/
void I2C_Stop()
{
unsigned int t = I2C_STOP_WAIT_VALUE;
I2C_SDA = 0; I2C_Delay();
I2C_SCL = 1; I2C_Delay();
I2C_SDA = 1 I2C_Delay();
while ( --t != 0 ); //Add a certain delay before the next Start is generated
}
/******************************************************************************
Function: I2C_Puts()
Function: I2C bus integrated sending function, sending multiple bytes of data to the slave
parameter:
SlaveAddr: slave address (7-bit pure address, excluding read/write bit)
SubAddr: slave subaddress
SubMod: Subaddress mode, 0 - no subaddress, 1 - single-byte subaddress, 2 - double-byte subaddress
*dat: data to be sent
Size: The number of bytes of data
return:
0: Send successfully
1: An exception occurred during the sending process
illustrate:
This function works well with all common I2C devices, whether or not they have subaddresses.
When the slave has no subaddress, the parameter SubAddr is arbitrary, and SubMod should be 0
******************************************************************************/
bit I2C_Puts
( unsigned char SlaveAddr , unsigned int SubAddr , unsigned char SubMod ,
char *dat , unsigned int Size )
{
//Define temporary variables
unsigned char i;
char a[3];
if ( Size == 0 ) return 0; // Check length
a[0] = (SlaveAddr << 1); //Prepare slave address
if ( SubMod > 2 ) SubMod = 2; // Check subaddress mode
//Determine the sub-address
switch ( SubMod )
{
case 0:
break;
case 1:
a[1] = (char)(SubAddr);
break;
case 2:
a[1] = (char)(SubAddr >> 8);
a[2] = (char)(SubAddr);
break;
default:
break;
}
//Send the slave address (a[0]), then send the sub-address (if there is a sub-address) (a[1], a[2])
I2C_Start();
for ( i=0; i<=SubMod; i++ )
{
I2C_Write(a[i]);
if ( I2C_GetAck() )
{
I2C_Stop();
return 1;
}
}
//send data
do
{
I2C_Write(*dat++);
if ( I2C_GetAck() ) break;
} while ( --Size != 0 );
//Sending completed, stop I2C bus, and return the result
I2C_Stop();
if ( Size == 0 )
{
return 0; //Send successfully
}
else
{
return 1; //Exception occurred during sending
}
}
/******************************************************************************
Function: I2C_Gets()
Function: I2C bus integrated receiving function, receiving multiple bytes of data from the slave
parameter:
SlaveAddr: slave address (7-bit pure address, excluding read/write bit)
SubAddr: slave subaddress
SubMod: Subaddress mode, 0 - no subaddress, 1 - single-byte subaddress, 2 - double-byte subaddress
*dat: save the received data
Size: The number of bytes of data
return:
0: Received successfully
1: An exception occurred during the receiving process
illustrate:
This function works well with all common I2C devices, whether or not they have subaddresses.
When the slave has no subaddress, the parameter SubAddr is arbitrary, and SubMod should be 0
******************************************************************************/
bit I2C_Gets
( unsigned char SlaveAddr , unsigned int SubAddr , unsigned char SubMod ,
char *dat , unsigned int Size )
{
//Define temporary variables
unsigned char i;
char a[3];
if ( Size == 0 ) return 0; // Check length, received successfully
a[0] = (SlaveAddr << 1); //Prepare slave address
if ( SubMod > 2 ) SubMod = 2; // Check subaddress mode
//If it is a slave with a sub-address, send the slave address and sub-address first
if ( SubMod != 0 )
{
//Determine the sub-address
if ( SubMod == 1 )
{
a[1] = (char)(SubAddr);
}
else
{
a[1] = (char)(SubAddr >> 8);
a[2] = (char)(SubAddr);
}
//Send the slave address write, then send the sub address
I2C_Start();
for ( i=0; i<=SubMod; i++ )
{
I2C_Write(a[i]);
if ( I2C_GetAck() )
{
I2C_Stop();
return 1;
}
}
}
//The I2C_Start() here is a repeated start state for the slave with a sub-address
//For a slave without a sub-address, it is a normal starting state
I2C_Start();
//Send slave address to read
I2C_Write(a[0]+1);
if ( I2C_GetAck() )
{
I2C_Stop();
return 1;
}
//Receive data
for (;;)
{
*dat++ = I2C_Read();
if ( --Size == 0 )
{
I2C_PutAck(1);
break;
}
I2C_PutAck(0);
}
//Receiving completed, stop I2C bus, and return the result
I2C_Stop();
return 0;
}
I2C read and write EEPROM flow chart
Previous article:STM32 FLASH erase, write and prevent accidental erasure program code
Next article:C51 queue mode interrupt receive query send
- Popular Resources
- Popular amplifiers
Professor at Beihang University, dedicated to promoting microcontrollers and embedded systems for over 20 years.
- Innolux's intelligent steer-by-wire solution makes cars smarter and safer
- 8051 MCU - Parity Check
- How to efficiently balance the sensitivity of tactile sensing interfaces
- What should I do if the servo motor shakes? What causes the servo motor to shake quickly?
- 【Brushless Motor】Analysis of three-phase BLDC motor and sharing of two popular development boards
- Midea Industrial Technology's subsidiaries Clou Electronics and Hekang New Energy jointly appeared at the Munich Battery Energy Storage Exhibition and Solar Energy Exhibition
- Guoxin Sichen | Application of ferroelectric memory PB85RS2MC in power battery management, with a capacity of 2M
- Analysis of common faults of frequency converter
- In a head-on competition with Qualcomm, what kind of cockpit products has Intel come up with?
- Dalian Rongke's all-vanadium liquid flow battery energy storage equipment industrialization project has entered the sprint stage before production
- Allegro MicroSystems Introduces Advanced Magnetic and Inductive Position Sensing Solutions at Electronica 2024
- Car key in the left hand, liveness detection radar in the right hand, UWB is imperative for cars!
- After a decade of rapid development, domestic CIS has entered the market
- Aegis Dagger Battery + Thor EM-i Super Hybrid, Geely New Energy has thrown out two "king bombs"
- A brief discussion on functional safety - fault, error, and failure
- In the smart car 2.0 cycle, these core industry chains are facing major opportunities!
- The United States and Japan are developing new batteries. CATL faces challenges? How should China's new energy battery industry respond?
- Murata launches high-precision 6-axis inertial sensor for automobiles
- Ford patents pre-charge alarm to help save costs and respond to emergencies
- New real-time microcontroller system from Texas Instruments enables smarter processing in automotive and industrial applications
- Talk about differential signal
- DSP code optimization instructions in CCS
- Help, what kind of lights are these? I see them for the first time.
- Analysis and improvement of errors in making circuit board laminate structure drawings
- RL78 MCU big and small end problem
- Share a flash tool for esp32-c3
- [Mil MYD-YA15XC-T Review] + USB UVC Camera Test
- Share: Several questions about the battery monitor bq76pl455a
- 【Repair】Fire emergency light fault inspection and repair
- EEWORLD University - Multi-Camera System with DS90UB960 Deserializer Hub and TDA SoC: Training Series