標(biāo)題:
avr單片機(jī)ADC檢測(cè)255次取平均值后依然跳變,代碼如下
[打印本頁(yè)]
作者:
子不語(yǔ)呢
時(shí)間:
2019-4-23 14:34
標(biāo)題:
avr單片機(jī)ADC檢測(cè)255次取平均值后依然跳變,代碼如下
#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,右對(duì)齊,ADC4
}
void uart0_init(void)
{
UCSR0B = 0x00;
UCSR0C = 0x06; //一個(gè)停止位,8個(gè)數(shù)據(jù)位
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); //轉(zhuǎn)換后求和
}
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);
}
}
作者:
子不語(yǔ)呢
時(shí)間:
2019-4-23 14:35
獲取ADC之后通過(guò)串口發(fā)送給主機(jī)
作者:
子不語(yǔ)呢
時(shí)間:
2019-4-23 14:39
12.44V
12.43V
12.43V
12.44V
12.43V
12.44V
12.44V
12.44V
12.43V
12.44V
12.44V
12.44V
接收到的值,實(shí)際值萬(wàn)用表測(cè)量為12.42
作者:
jtpeng01
時(shí)間:
2020-2-27 20:14
dis_val=(dis_val/255); 取整時(shí),即使相差1,也可以導(dǎo)致12.44 和12.43之間,例如:1020/255=4,1019/255=3.雖然取的255次之和,這種機(jī)會(huì)還是有的. 萬(wàn)用表測(cè)得有差別,很正常,0.01V
歡迎光臨 (http://www.torrancerestoration.com/bbs/)
Powered by Discuz! X3.1