📄 8574.c
字号:
#include <reg52.h>
#include <stdio.h>
sbit SCL=P3^7;
sbit SDA=P3^6;
typedef unsigned char byte;
byte in_patt(byte device);
void out_patt(byte device, byte dirs, byte patt);
void out_byte(byte o_byte);
byte in_byte(void);
byte nack(void);
void start(void);
void stop(void);
void delay(int a)
{
for (;a>0;a--)
;
}
void DelayMs(unsigned char t)
{
unsigned char i;
if(t>0)
{
for(i=0;i<=10;i++)
;
t--;
}
}
void main(void)
{
byte i_patt, device;
byte dirs = 0x80; /* define most significant bit as an input */
device = 0x00; /* determined by strapping of A2, A1, A0 */
out_patt(device, dirs, 0xff);
/* initialize all outputs to logic one */
while(1)
{
i_patt=in_patt(device); /* fetch from 8574 */
if ((i_patt && 0x80)==0) /* if switch at zero, flash LED */
{
out_patt(device, dirs, 0x00); /* LED on */
DelayMs(250);
out_patt(device, dirs, 0x01); /* LED off */
DelayMs(250);
}
else
{
out_patt(device, dirs, 0x01); /* turn LED off */
}
}
}
byte in_patt(byte device)
/* fetches byte from 8574 at specified addresss */
{
byte o_byte, i_patt;
start();
o_byte=0x40 | (device << 1) | 0x01;
out_byte(o_byte);
nack();
i_patt=in_byte();
stop();
return(i_patt);
}
void out_patt(byte device, byte dirs, byte patt)
/* outputs specified pattern on specified 8574. Note that
** inputs specified by "dirs" are maintained at a logic one */
{
byte o_byte;
start();
o_byte=0x40 | (device << 1);
out_byte(o_byte);
nack();
o_byte = patt | dirs;
out_byte(o_byte);
nack();
stop();
}
void out_byte(byte o_byte)
/* shift out byte, beginning with most significant bit */
{
int n;
for(n=7; n>=0; n--)
{ /* note SCL is low during transitions on SDA */
if (((o_byte >>n) & 0x01) == 0)
{
SDA=0;
}
else
{
SDA=1;
}
delay(4);
SCL=1;
delay(4);
SCL=0;
delay(4);
}
}
byte in_byte(void)
/* fetch byte, most significant byte first */
{
byte i_byte=0x00;
int n;
SDA=1;
delay(4);
for (n=0; n<8; n++)
{
SCL=1;
delay(4);
i_byte=(i_byte << 1) | SDA;
delay(4);
SCL=0;
}
return(i_byte);
}
byte nack(void)
{
byte ack_bit;
SDA=1;
delay(4);
SCL=1;
delay(4);
if (SDA==0)
{
ack_bit=0;
}
else
{
ack_bit=1;
}
SCL=0;
delay(4);
return(ack_bit);
}
void start(void)
/* bring SDA high to low while SCL is high */
{
SDA=1;
delay(4);
SCL=1;
delay(4);
SDA=0;
delay(4);
SCL=0;
delay(4);
}
void stop(void)
/* bring SDA low to high while SCL is high */
{
SDA=0;
delay(4);
SCL=1;
delay(4);
SDA=1;
delay(4);
SCL=0;
delay(4);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -