【PCF8591组件(A/D和D/A转换)】PCF8591.h
#ifndef _PCF8591_H
#define _PCF8591_Huint8_t getADCvalue(uint8_t chn);
void uint8_tToArray(uint8_t * arry, uint8_t val);
#endif
PCF8591.c
#include//检查是否有误
#include "stdint.h"
#include "I2C.h"//需要用到I2C通信协议
#include "PCF8591.h"/* 读取当前的ADC转换值,chn-ADC通道号0~3 */
uint8_t getADCvalue(uint8_t chn) {
uint8_t val;
I2Cstart();
if (I2Cwrite(0x48 << 1) == 0) { //寻址PCF8591,如未应答,则停止操作并返回0
I2Cstop();
return 0;
}
I2Cwrite(0x40 | chn);
//写入控制字节,选择转换通道
I2Cstart();
I2Cwrite((0x48 << 1) | 0x01);
//寻址PCF8591,指定后续为读操作
I2CreadAck();
//先空读一个字节,提供采样转换时间
val = I2CreadNak();
//读取刚刚转换完的值
I2Cstop();
return val;
}
/* ADC转换值转为实际电压值的BCD码形式,arry-数组指针,val-AD转换值 */
void uint8_tToArray(uint8_t * arry, uint8_t val) {
arry[0] = (uint8_t)((uint16_t)val * 25 / 2550);
//10^0
arry[1] = (uint8_t)((uint16_t)val * 25 / 255) % 10;
//10^-1
arry[2] = (uint8_t)((uint16_t)val * 250 / 255) % 10;
//10^-2
}