Microcontroller I2C driver

Publisher:知识智慧Latest update time:2016-12-31 Source: eefocus Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

void delay()

{; ;}

void delay1ms ( uint z )
{
uint x, y;
for ( x = z; x >
0; x -- ) for ( y = 110; y > 0; y -- );
}

I2C startup: falling edge on SDA while SCL is high

 

void start_I2C ( ) /
{
sda = 1;
delay ();
scl = 1;
delay ();
sda = 0;
delay ();
}

 

I2C stop: A rising edge occurs on SDA during SCL high level

void stop_I2C () //Stop
{
sda = 0;
delay ();
scl = 1;
delay ();
sda = 1;
delay ();
}

 

Bus initialization: pull the bus high to release the bus

void init_I2C ()
{
sda = 1;
delay ();
scl = 1;
delay ();
}

 

Answer signal: During the high level of SCL, SDA is pulled low by the slave device to indicate the answer.

void response ()//Response
{
uchar i;
scl = 1;
delay ();
while ( ( sda == 1 ) && ( i < 250 ) ) i ++; // i < 255 here only means that there is no response, If i > 255, exit directly to avoid an infinite loop.
scl = 0;
delay ();
}

 

Write a byte: the high or low level on SDA can only change during the low period of SCL

void write_byte (uchar date)
{
uchar i, temp;
temp = date;
for ( i = 0; i < 8; i ++ )
{
temp = temp << 1; //Move the highest bit into CY
scl = 0;
delay ();
sda = CY;
delay ();
scl = 1;
delay ();
}

scl = 0;
delay ();
sda = 1;
delay ();

}

 

Read a byte:

uchar read_byte ()
{
uchar i, k;
scl = 0;
delay ();
sda = 1;
delay ();
for ( i = 0; i < 8; i ++ )
{
scl = 1;
delay ();
k = ( k << 1 ) | sda; // Also read from the highest bit
scl = 0;
delay ();
}
return k;

}


Reference address:Microcontroller I2C driver

Previous article:Various working registers (timer/interrupt)
Next article:A little knowledge about MCU

Latest Microcontroller Articles
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号