#include <iom88pv.h>
#include <macros.h>
#define uchar unsigned char
#define uint unsigned int
#define UDRE 5
#define RXC 7
#define xtal 8
long adc_val,dis_val;
uchar e[4];
/*************************************/
void Delay_1ms(void)
{ uint i;
for(i=1;i<(uint)(xtal*143-2);i++);
}
/****************************************/
void Delay_nms(uint n)
{
uint i=0;
while(i<n)
{Delay_1ms();
i++;
}
}
/***********************************************/
void port_init(void)
{
PORTB = 0x01;
DDRB = 0x01;
PORTC = 0x20;
DDRC = 0x20;
PORTD = 0x00;
DDRD = 0x00;
}
/**********************************************/
void adc_init(void)
{
ADCSRA = 0xE6; //64分频
ADMUX =0x06; //AREF,右对齐,ADC4
}
void uart0_init(void)
{
UCSR0B = 0x00;
UCSR0C = 0x06; //一个停止位,8个数据位
UBRR0L = 0x33; //波特率,9600
UBRR0H = 0x00;
UCSR0B = 0x18; //中断使能
}
/*********************************/
void init_devices(void)
{
port_init();
adc_init();
uart0_init();
}
//========================
uint ADC_Convert(void)
{uint temp1,temp2;
temp1=(uint)ADCL;
temp2=(uint)ADCH;
temp2=(temp2<<8)+temp1;
return(temp2);
}
//========================
uint conv(uint i)
{
long x;
uint y;
x=((249*61*(long)i)/1024);
y=(uint)x;
return y;
}
/**************************************/
void uart0_send(unsigned char i)
{
while(!(UCSR0A&(1<<UDRE0)));
UDR0=i;
}
//=====================
void main(void)
{
init_devices();
while(1)
{
uchar i;
adc_val=ADC_Convert(); //取ADC值
for(i=0;i<255;i++)
{
dis_val+=conv(adc_val); //转换后求和
}
dis_val=(dis_val/255); //求平均值
Delay_nms(10);
e[0]=dis_val/10000;
e[1]=(dis_val/1000)%10;
e[2]=(dis_val/100)%10;
e[3]=(dis_val/10)%10;
uart0_send(e[0]+0x30);
uart0_send(e[1]+0x30);
uart0_send('.');
uart0_send(e[2]+0x30);
uart0_send(e[3]+0x30);
uart0_send('V');
uart0_send(0x0d);
uart0_send(0x0a);
Delay_nms(1000);
}
}
|