一. 程序功能
用AD以1HZ的频率采集模拟信号,然后转换成数字量,显示在数码管上,再将其以1200bps发送到计算机,在计算机上显示.
二. 程序源码
#include
#include //需要用到_nop_()函数
#define uchar unsigned char
#define uint unsigned int
sbit dula = P2 ^ 6; //申明U1锁存器的锁存端
sbit wela = P2 ^ 7; //申明U2锁存器的锁存端
sbit adwr = P3 ^ 6; //申明AD的WR端口
sbit adrd = P3 ^ 7; //申明AD的RD端口
uint g_iNum; //申明变量获取AD转换后的数字量
uchar g_cT0; //申明变量便于定时器0计数
uchar g_cFlag; //申明变量实现AD转换函数与主函数间的通信
uchar code table[] = { //数码管的编码定义(0,1,...,9,A,B,C,D,E,F)
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71
};
void serial_com(uint i_num); //申明串口数据送计算机的函数
void delayms(uint xms); //申明延时xms ms函数
void tude_display(uint i_num); //申明数码管显示函数
void init(); //申明串口,中断,定时器0初始化函数
void main()
{
uchar i;
//串口, 中断, 定时器初始化
init();
//主循环(反复执行)
while (1)
{
if (g_cFlag == 1) //检测AD是否发生
{
for (i = 100; i > 0; i--)
tude_display(g_iNum); //将ad转换的数字量显示在数码管
serial_com(g_iNum); //将ad转换数字量对应的模拟量发送到计算机
}
}
}
//延时ms函数
void delayms(uint xms)
{
uint i, j;
for (i = xms; i > 0; i--)
for (j = 110; j > 0; j--)
;
}
//数码管显示函数
void tude_display(uint i_num)
{
uchar bai, shi, ge;
bai = i_num / 100;
shi = i_num % 100 / 10;
ge = i_num % 10;
dula = 1;
P0 = table[bai];
dula = 0;
//P0 = 0xff; //ADC0804的CS端连接在U2锁存器的Q7上,所以Q7位需要为0, 所以不能做清影动作
wela = 1;
P0 = 0x7e; //ADC0804的CS端连接在U2锁存器的Q7上,所以Q7位需要为0, 下同
wela = 0;
delayms(5);
dula = 1;
P0 = table[shi];
dula = 0;
//P0 = 0xff;
wela = 1;
P0 = 0x7d;
wela = 0;
delayms(5);
dula = 1;
P0 = table[ge];
dula = 0;
//P0 = 0xff;
wela = 1;
P0 = 0x7b;
wela = 0;
delayms(5);
//每次显示数据后将数码管全灭
dula = 1;
P0 = 0x00;
dula = 0;
wela = 1;
P0 = 0x00;
wela = 0;
}
void T0_timer() interrupt 1
{
TH0 = (65536 - 50000) / 256;
TL0 = (65536 - 50000) % 256;
g_cT0++;
if (g_cT0 == 20)
{
g_cT0 = 0;
adwr = 1;
_nop_();
adwr = 0;
_nop_();
adwr = 1;
P1 = 0xff;
adrd = 1;
_nop_();
adrd = 0;
_nop_();
g_iNum = P1; //获取Ad转换的数字量
g_cFlag = 1; //标志位置位, AD与主函数间通信
}
}
void init()
{
//选通AD的CS端, ADC0804的CS端与U2锁存器的Q7端连接
wela = 1;
P0 = 0x7f;
wela = 0;
//串口工作方式
SM0 = 0;
SM1 = 1;
TMOD = 0x21;
//波特率为1200bsp
TH1 = 0xE8;
TL1 = 0xE8;
//启动定时器1
TR1 = 1;
//开启总中断
EA = 1;
//开启定时器0中断
ET0 = 1;
//启动定时器0
TR0 = 1;
}
void serial_com(uint i_num)
{
long temp;
uchar sCom[7];
uchar i;
//将AD转换的数字量转化为对于的模拟量
temp = (i_num * 500000) / 256;
sCom[0] = temp / 100000;
sCom[1] = .;
sCom[2] = temp / 1000 % 10;
sCom[3] = temp / 1000 % 10;
sCom[4] = temp / 100 % 10;
sCom[5] = temp / 10 % 10;
sCom[6] = temp % 10;
//发送三个空格
for (i = 0; i < 3; i++)
{
SBUF = 0x20; //0x20为空格的ascii码
while (!TI);
TI = 0;
}
//将AD数字量对于模拟量发送到计算机
for (i = 0; i < 7; i++)
{
if (i != 1)
SBUF = sCom[i] + 0x30; //0x30为0的ascii码
else
SBUF = sCom[i]; //.不需要加0的ascii码
while (!TI);
TI = 0;
}
}