// Khai bao cac file header
#include <AT89X52.H>
#include <Kit8051.h>
// Khai bao cac bien toan cuc
unsigned char code string1[] = "8051 Starter Kit";
unsigned char code string2[] = "Dien ap = ";
unsigned char voltage,digit1,digit2;
// Khai bao cac ham
void InitSystem(void);
void Delay(unsigned int n);
void DelayShort(void);
void InitLCD(void);
void WriteCommand(unsigned char command);
void WriteCharacter(unsigned char character);
void WriteLCD(unsigned char x);
void SendString2LCD(unsigned char code *p);
void DisplayText(void);
void DisplayVoltage(void);
void Convert();
void Calculate();
// Dinh nghia cac ham
void InitSystem(void)
{
// Cam LCD
LCD_E = 0;
// Sang den backlight
LCD_BL = 0;
// Tre de LCD tu khoi tao ben trong (it nhat 15ms)
Delay(100);
// Tat den backlight
LCD_BL = 1;
InitLCD();
}
void Delay(unsigned int n)
{
unsigned int i,j;
for(i=0;i<n;i++)
for(j=0;j<100;j++);
}
void DelayShort(void)
{
unsigned char i;
for(i=0;i<10;i++);
}
void InitLCD(void)
{
WriteCommand(0x30);
WriteCommand(0x30);
WriteCommand(0x30);
// 8 bit, 2 lines, font 5x7
WriteCommand(0x38);
// Display on, hide cursor
WriteCommand(0x0C);
// Xoa man hinh
WriteCommand(0x01);
}
void DisplayText(void)
{
// Dich con tro den dau dong thu nhat
WriteCommand(0x80);
SendString2LCD(string1);
// Dich con tro den dau dong thu hai
WriteCommand(0xC1);
SendString2LCD(string2);
// Dich con tro den vi tri don vi do
WriteCommand(0xCE);
WriteCharacter('V');
}
void WriteLCD(unsigned char x)
{
LCD_RW = 0;
LCD_DATA = x;
LCD_E = 1;
LCD_E = 0;
Delay(5);
}
void WriteCommand(unsigned char command)
{
LCD_RS = 0;
WriteLCD(command);
}
void WriteCharacter(unsigned char character)
{
LCD_RS = 1;
WriteLCD(character);
}
void SendString2LCD(unsigned char code *p)
{
unsigned char i=0;
while(p[i]!=0)
{
WriteCharacter(p[i]);
i++;
Delay(50);
}
}
void Convert(void)
{
// Ra lenh chuyen doi
ADC_RD = 1;
ADC_CS = 0;
DelayShort();
ADC_WR = 0;
DelayShort();
ADC_WR = 1;
DelayShort();
ADC_CS = 1;
// Cho chuyen doi xong
// Delay(10);
while(ADC_DONE==1);
// Chuyen Port thanh cong vao de chuan bi doc du lieu
ADC_DATA = 0xFF;
ADC_CS = 0;
DelayShort();
ADC_RD = 0;
DelayShort();
// Doc du lieu vao
voltage = ADC_DATA;
ADC_RD = 1;
DelayShort();
ADC_CS = 1;
}
void Calculate(void)
{
unsigned int temp;
temp = (voltage*10);
temp = temp/52;
// tinh ra dien ap tu gia tri ADC dua ve
// tach phan nguyen va phan thap phan
digit1 = (unsigned char) (temp/10);
digit2 = (unsigned char)(temp%10);
// chuyen sang ma ASCII
digit1 = digit1 + 0x30;
digit2 = digit2 + 0x30;
}
void DisplayVoltage(void)
{
// Dua con tro den vi tri can hien thi
WriteCommand(0xCB);
WriteCharacter(digit1);
WriteCharacter('.');
WriteCharacter(digit2);
}
// Chuong trinh chinh
void main(void)
{
// Khoi tao he thong
InitSystem();
DisplayText();
// Vong lap vo tan
while(1)
{
Convert();
Calculate();
DisplayVoltage();
}
}