我需要一个c语言代码可以实现89C51芯片和PCF8591之间I2C通讯读取光敏电阻输出的电压值并且判断当处于黑暗时将P1.0口置于高电平点亮LED
时间: 2023-11-28 12:47:45 浏览: 63
由2片AT89C51+MAX232+AT89C2051+晶振+电阻电容+三极管+LED灯组成的电路原理图和PCB
以下是一个简单的C语言代码,可以实现89C51芯片和PCF8591之间I2C通讯读取光敏电阻输出的电压值,并且判断当处于黑暗时将P1.0口置于高电平点亮LED。
```c
#include <reg51.h>
#define SDA P2_0
#define SCL P2_1
sbit LED = P1 ^ 0;
void delay(int n)
{
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < 100; j++)
;
}
void i2c_start()
{
SDA = 1;
SCL = 1;
delay(1);
SDA = 0;
delay(1);
SCL = 0;
delay(1);
}
void i2c_stop()
{
SDA = 0;
SCL = 1;
delay(1);
SDA = 1;
delay(1);
}
void i2c_write(unsigned char dat)
{
unsigned char i;
for (i = 0; i < 8; i++)
{
SDA = dat & 0x80;
SCL = 1;
dat <<= 1;
SCL = 0;
}
SDA = 1;
SCL = 1;
delay(1);
SCL = 0;
}
unsigned char i2c_read()
{
unsigned char i, dat = 0;
SDA = 1;
for (i = 0; i < 8; i++)
{
SCL = 1;
dat <<= 1;
dat |= SDA;
SCL = 0;
}
return dat;
}
unsigned char i2c_read_ack()
{
unsigned char dat = i2c_read();
SDA = 0;
SCL = 1;
delay(1);
SCL = 0;
return dat;
}
unsigned char i2c_read_nack()
{
unsigned char dat = i2c_read();
SDA = 1;
SCL = 1;
delay(1);
SCL = 0;
return dat;
}
void init_pcf8591()
{
i2c_start();
i2c_write(0x90); //写器件地址
i2c_write(0x40); //发送控制字节
i2c_stop();
}
unsigned char read_adc(unsigned char ch)
{
unsigned char dat;
i2c_start();
i2c_write(0x90); //写器件地址
i2c_write(0x40 + ch); //发送控制字节
i2c_start(); //重新启动
i2c_write(0x91); //读器件地址
dat = i2c_read_nack(); //读取数据
i2c_stop(); //停止
return dat; //返回数据
}
void main()
{
init_pcf8591();
while (1)
{
unsigned char val = read_adc(0);
if (val < 128)
LED = 1;
else
LED = 0;
}
}
```
注意,这里的代码仅供参考,实际使用需要根据具体硬件和软件环境进行修改。
阅读全文