每次
单片机刚上电时采样第一次总是采样到2.5V电压(VCC=5V),然后再次采样时才能采样到正确值。求教原因。源代码如下:
- void main()
- {
-
- uchar vol_1,vol_2,vol_3;
- LCD_Init();
- delay(1000);
- while(1)
- {
- result=read_ad(CH3);
- P1=result;
- vol=result*196;
- if(vol%100>=50) //四舍五入
- vol=vol/100+1;
- else
- vol=vol/100;
- vol_1=vol/100;
- vol_2=vol/10%10;
- vol_3=vol%100%10;
- LCD_Write_String(2,0,"VOL:");
- LCD_Write_Char(8,0,vol_1+48);
- LCD_Write_Char(9,0,'.');
- LCD_Write_Char(10,0,vol_2+48);
- LCD_Write_Char(11,0,vol_3+48);
- LCD_Write_Char(12,0,'V');
- while(P3==0XFF);
- delay(300);
- }
- //
- }
复制代码
一些函数如下:
- #include <mydec.h>
- #include <1602.h>
- #define CH0 0X00
- #define CH1 0X01
- #define CH2 0X02
- #define CH3 0X03
- sbit SCL=P2^1;
- sbit SDA=P2^0;
- sbit LED=P3^7;
- uchar result; //AD读到的结果
- uint vol;
- bit flag_ad_err=0;
- void I2C_start(void)
- {
- SCL=1;
- SDA=1;
- SDA=0;
- SCL=0;
- }
- void I2C_stop(void)
- {
- SCL=1;
- SDA=0;
- SDA=1;
- SCL=0;
- }
- void I2C_write(uchar dat)
- {
- uchar temp,i;
- temp=dat;
- for(i=0;i<8;i++)
- {
- SCL=0;
- SDA=temp&0x80;
- temp<<=1;
- SCL=1;
-
- }
- SCL=0;
- }
- bit get_ack(void)
- {
- bit ack;
- SCL=0;
- SCL=1;
- ack=SDA;
- nop();
- nop();
- SCL=0;
- return ack;
- }
- uchar I2C_read_data(void)
- {
- uchar temp=0,i;
- SCL=0;
- for(i=0;i<8;i++)
- {
- SCL=1;
- temp<<=1;
- temp|=SDA;
- SCL=0;
-
- }
- return temp;
- }
- uchar read_ad(uchar ch)
- {
- uchar value;
- I2C_start();
- I2C_write(0x90);
- if(get_ack())
- {
- flag_ad_err=1;
- I2C_stop();
- }
- I2C_write(ch);
- if(get_ack())
- {
- flag_ad_err=1;
- I2C_stop();
- }
- I2C_start();
- I2C_write(0x91);
- if(get_ack())
- {
- flag_ad_err=1;
- I2C_stop();
- }
- value=I2C_read_data();
- get_ack();
- I2C_stop();
- return value;
- }
- void write_data(uchar addr,uchar dat)
- {
- I2C_start();
- I2C_write(0x90);
- if(get_ack())
- {
- flag_ad_err=1;
- I2C_stop();
- }
- I2C_write(addr);
- if(get_ack())
- {
- flag_ad_err=1;
- I2C_stop();
- }
- I2C_write(dat);
- if(get_ack())
- {
- flag_ad_err=1;
- I2C_stop();
- }
- I2C_stop();
- }
复制代码
5v/255=1/51v,ad转换出来的电压最小单位是1/51v,应该除以51,而不是100
一周热门 更多>