wulin 发表于 2023-4-14 10:12
这是最基本的ADC运用,问题多在硬件电路和程序缺陷。上电路图与代码。
main.c
#include "STC15F2K60S2.h"
#include "LCD1602.h"
#include "ADC.h"
unsigned char str[5];
unsigned int backup=0;
unsigned char aa[]={'L','I','G','H','T',':'};
void main()
{
unsigned int result;
//write_com(0x01);
init();
Init_ADC();
while (1)
{
result=ADC_Chang(7);
result=result*0.0475;
while (result!=backup)
{
str[0]=result/1000+'0';
str[1]=result%1000/100+'0';
str[2]=result%100/10+'0';
str[3]=result%10+'0';
str[4]='\0';
LCD_Write_String(6,1,str);
LCD_Write_String(0,1,aa);
}
}
}
ADC.C
#include "STC15F2K60S2.h"
#include "ADC.h"
#include "LCD1602.h"
unsigned int ADC_DATE1,ADC_DATE2;
bit flag;
void delay(unsigned int sec) //延时函数
{
while(sec--);
}
void Init_ADC() //ADC初始化
{
P1ASF=0X08; //将P1口设为ADC转换功能;
ADC_RES=0X00;
ADC_RESL=0X00; //清除转换结果寄存器
ADC_CONTR|=ADC_Power|ADC_Speed90; //打开ADC电源,ADC转换速率90个机器周期,ADC通道为P1^7;111
delay(5000);
EA=1;
EADC=1;
}
unsigned int ADC_Chang(unsigned char ch)
{
unsigned int result;
EADC=1;
delay(6000);
ADC_CONTR|=ADC_Power|ADC_Speed90|ADC_Start|ch; //启动AD转换
while(flag)
{
ADC_DATE1=ADC_DATE1<<2;
ADC_DATE2=ADC_DATE2&0x03;
result=ADC_DATE1|ADC_DATE2;
flag=0;
}
EADC=0;
return result;
}
void interrupt_ADC() interrupt 5
{
ADC_CONTR&=(~ADC_flag);
ADC_DATE1=ADC_RES;
ADC_DATE2=ADC_RESL;
flag=1;
}
ADC.H
#ifndef _ADC_H_
#define _ADC_H_
#include "STC15F2K60S2.h"
#define ADC_Power 0x80
#define ADC_Speed90 0x60
#define ADC_Speed180 0x40
#define ADC_Speed360 0x20
#define ADC_Speed540 0x00
#define ADC_Start 0x08
#define ADC_flag 0x10
void Init_ADC();
void delay(unsigned int sec);
unsigned int ADC_Chang(unsigned char ch);
void interrupt_ADC();
#endif |