欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

【蓝桥之路——无bug代码】PCF8591——AD转换部分代码解析

时间:2023-05-28

读取Rb2的电压值并显示在数码管上,范围0.00~5.00V,通过改变滑动变阻器Rb2的阻值可以改变电压值

main.c

#include"stc15f2k60s2.h"#include"iic.h"#include"intrins.h"typedef unsigned char uchar;typedef unsigned int uint;uchar dsp_code[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};uchar dsp_ADC[8]={0xff,0xff,0xff,0xff,0xff,0xff};uint value;uchar count_adc;void Timer_Init(){AUXR|= 0x80;TMOD&= 0xf0;TL0=0xcd;TH0=0xd4;TR0=1;ET0=1;EA=1;}void serviceTimer() interrupt 1{static uchar dsp_com=0;P0=0;P2=0xc0;P2=0;P0=dsp_ADC[dsp_com];P2=0xe0;P2=0;P0=1<199){count_adc=0;EA=0;value=read_adc(0x03)*1.96+0.5;EA=1;}dsp_ADC[5]=dsp_code[value/100]&0x7f;dsp_ADC[6]=dsp_code[value/10%10];dsp_ADC[7]=dsp_code[value%10];}}

iic.c

#include "reg52.h"#include "intrins.h"#define DELAY_TIME 5 #define SlaveAddrW 0xA0#define SlaveAddrR 0xA1//总线引脚定义sbit SDA = P2^1; sbit SCL = P2^0; void IIC_Delay(unsigned char i){do{_nop_();}while(i--);}//总线启动条件void IIC_Start(void){SDA = 1;SCL = 1;IIC_Delay(DELAY_TIME);SDA = 0;IIC_Delay(DELAY_TIME);SCL = 0;}//总线停止条件void IIC_Stop(void){SDA = 0;SCL = 1;IIC_Delay(DELAY_TIME);SDA = 1;IIC_Delay(DELAY_TIME);}//等待应答bit IIC_WaitAck(void){bit ackbit;SCL=1;IIC_Delay(DELAY_TIME);ackbit=SDA;SCL=0;IIC_Delay(DELAY_TIME);return ackbit;}//通过I2C总线发送数据void IIC_SendByte(unsigned char byt){unsigned char i;for(i=0;i<8;i++){ SCL=0;IIC_Delay(DELAY_TIME);if(byt&0x80) {SDA = 1;}else {SDA = 0;}IIC_Delay(DELAY_TIME);SCL = 1;byt <<= 1;IIC_Delay(DELAY_TIME);}SCL = 0;IIC_WaitAck();}//从I2C总线上接收数据unsigned char IIC_RecByte(void){unsigned char da;unsigned char i;for(i=0;i<8;i++){ SCL = 1;IIC_Delay(DELAY_TIME);da <<= 1;if(SDA) da |= 0x01;SCL = 0;IIC_Delay(DELAY_TIME);}IIC_WaitAck();return da;}void IIC_SendAck(bit ackbit){SCL=0;SDA=ackbit;IIC_Delay(DELAY_TIME);SCL=1;IIC_Delay(DELAY_TIME);SCL=0;IIC_Delay(DELAY_TIME);SDA=1;IIC_Delay(DELAY_TIME);}unsigned char read_adc(unsigned char add){unsigned char val;IIC_Start();IIC_SendByte(0x90);IIC_SendByte(add);IIC_Start();IIC_SendByte(0x91);val=IIC_RecByte();IIC_Stop();return val;}

iic.h

#ifndef _IIC_H#define _IIC_H//函数声明void IIC_Start(void); void IIC_Stop(void); void IIC_SendAck(bit ackbit); void IIC_SendByte(unsigned char byt); bit IIC_WaitAck(void); unsigned char IIC_RecByte(void); unsigned char read_adc(unsigned char add);#endif

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。