pcf8591.h
#ifndef _PCF8591_H_
#define _PCF8591_H_
#include<reg51.h>
#include<i2c.h>
#ifndef uchar
#define uchar unsigned char
#endif
#ifndef uint
#define uint unsigned int
#endif
//参考电压
#define VREF 5.0
/********************************
_________________________________
|1 0 0 1 | A2 A1 A0 R/W|
| | |
| 固定部分 | 可编程部分 |
| | |
---|-----------|---------------|--
*******************************/
#define WRITEADDR 0x90
#define READADDR 0x91
void pcf8591SetChannel(uchar channel);
uchar pcf8591ReadByte();
float pcf8591Value();
void pcf8591DAConversion(uchar value);
#endif
pcf8591.c
#include<pcf8591.h>
#include<i2c.h>
/*******************************
D7 D6 D5 D4 D3 D2 D1 D0
*******************************
D0,D1,通道选择位
D2,自动增量允许位
D3,特征位,固定为0
D5,D4模拟量输入方式选择位
00:四路单端输入
01:3路差分输入
10:单端与差分输入
11:2路差分输入
D6,模拟量输出允许位
A/D转换时设置为0(地址选择字D0位此时为1)
D/A转换时设置为1(地址选择字D0位此时为0)
D7,特征位,固定为0。
******************************/
void pcf8591SetChannel(uchar channel)
{
I2C_Start();
//设计ack的作用体现在这里
//就是决定是否下次继续发送数据
//当pcf8591的控制字发送完后,
//不再发送了,就将ack设置为0;
I2C_SendByte(WRITEADDR, 1);
I2C_SendByte(0x40|channel, 0);
I2C_Stop();
}
uchar pcf8591ReadByte()
{
uchar dat;
I2C_Start();
I2C_SendByte(READADDR, 1);
dat = I2C_ReadByte();
I2C_Stop();
return dat;
}
float pcf8591Value()
{
uint temp = pcf8591ReadByte() * 2;
float v = temp * VREF /(2 * 256);
return v;
}
/*
void pcf8591DAConversion(uchar value)
{
I2C_Start();
I2C_SendByte(WRITEADDR, 1);
I2C_SendByte(0x40, 1);
I2C_SendByte(value, 0);
I2C_Stop();
}
*/