大家好,这个AD转换不知道老是不行,不知道是不是初始化那里有问题。请问那位有这方面的例程呢,谢谢。
#include <iostm8l152c6.h>
#include <intrinsics.h>
#define uchar unsigned char
#define uint unsigned int
#define led1 PC_ODR_ODR7
#define led2 PE_ODR_ODR7
uint adc_temp,adc_temp1,adc_temp2;
float adc_val;
uchar i;
uchar flag1;
//================================//
void delay_ms(uint k)
{
uint i,j;
for(i=0;i<k;i++)
for(j=0;j<1140;j++);
}
//================================//端口初始化
void port_init(void)
{
PA_DDR=0x00;
PA_CR1=0x00;
PA_CR2=0x00;
PC_DDR=0xff;
PC_CR1=0xff;
PC_CR2=0xff;
PE_DDR=0xf0;
PE_CR1=0xf0;
PE_CR2=0xf0;
PD_DDR=0xff;
PD_CR1=0xff;
PD_CR2=0xff;
PC_ODR=0xff;
led1=0;
led2=0;
}
//=================================//PWM初始化
void adc_init(void)
{
//CLK_PCKENR2=0x01;//开ADC1时钟
ADC1_CR1=0x01;//Fm/8,ADON=1,12 bit resolution
ADC1_CR2=0x01;//Fm/8,ADC 4 cycles
ADC1_CR3=0x00;//ADC 4 cycles,Sel AIN0
}
//================================//ADC 转换
void adc_convert(void)
{
ADC1_CR1_ADON=1;
ADC1_CR1_START=1;
adc_temp1=ADC1_DRH*8;
adc_temp2=ADC1_DRL;
adc_temp=adc_temp1+adc_temp2;
adc_val=adc_temp/4096*3.3;
delay_ms(2);
//ADC1_CR1_ADON=0;
ADC1_CR1_START=0;
}
//================================//
void key_det(void)
{
/*if((adc_val>0.5)&&(adc_val<1)) led1=1;
if((adc_val>1)&&(adc_val<1.5)) led2=1;
if((adc_val>2)&&(adc_val<2.5))
{
led1=0;
led2=0;
}*/
if(adc_val<0.5) led1=1;
}
//================================//TIM1初始化
void tim1_init(void)
{
CLK_PCKENR2=0x03;//开TIM1外设时钟,开ADC1时钟
TIM1_ARRH=2000/256;//1ms
TIM1_ARRL=2000%256;
TIM1_IER=0x01;//控制寄存器:更新中断使能
TIM1_CR1=0x81;//自动加载,计数使能
asm("rim");
}
//===============================//
#pragma vector=TIM1_OVR_UIF_vector
__interrupt void tim1_ovr_uif_vect (void)
{
TIM1_SR1_UIF=0;
i++;
if(i==10)//10mS扫描一次KEY
{
i=0;
adc_convert();
key_det();
//led1=~led1;
}
}
//================================//
void main(void)
{
port_init();
tim1_init();
adc_init();
while(1);
} |