文档介绍:单片机原理及应用实验
基于 51 单片机的计算器
设计性实验
2008112020338 王加元
电子信息科学与技术
物理与电子科学学院
2010 年 6 月 20 日
实验基于 51 单片机的计算器
一、实验目的
1、学会用程序来检测 4×5 矩阵键盘,并且在仿真软件中实现。
2、学会处理按键数据,以及数据显示,数据的小数点问题。
二、实验环境
Keil 软件和 protus 软件
三、实验内容
计算器中存在很多数据,数据的输入需要很多按键,那么这就
要涉及到按键的检测问题,同时产生的数据要送到单片机中进行处
理,处理完的数据要送到数码管上显示出来。
实验仿真图如下:
图 1 实验仿真图
(由于我的开发板上面 P2^3 脚接的蜂鸣器,仿真图中就没有用到
P2^3)
实验代码如下:
#include<>
#include<>
#include<>
#define uchar unsigned char
#define uint unsigned int
uchar code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
uchar code led[8]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};
uchar xx[8];
sbit dula=P2^6;
sbit wela=P2^7;
void displaypro(double h)
{
uchar point=8,m;
bit symbol;
char i;
double proh;
symbol=0;
if(h<0)
{
symbol=1;
h=-h;
}
if(h>=0&&h<10){point=1;proh=h*10000000;}
if(h>=10&&h<100){point=2;proh=h*1000000;}
if(h>=100&&h<1000){point=3;proh=h*100000;}
if(h>=1000&&h<10000){point=4;proh=h*10000;}
if(h>=10000&&h<100000){point=5;proh=h*1000;}
if(h>=100000&&h<1000000){point=6;proh=h*100;}
if(h>=1000000&&h<10000000){point=7;proh=h*10;}
if(h>=10000000&&h<100000000){point=8;proh=h;}
if(h<100000000)
{
for(i=7;i>=0;i--)
{
m=proh/pow(10,i);
xx[7-i]=table[m];
proh=proh-(m*pow(10,i));
if(proh<0)
proh=0;
}
if(h>=1)//由于 keil 中单精度和双精度是一样的,只能表示六位数,如不把后面两位清零,将会出现乱码。
{
xx[6]=0x3f;
xx[7]=0x3f;
}
else xx[7]=0x3f;
xx[point-1]+=128;// 显示小数点
}
else //超过八位数时,计算器报错显示 E
{
for(i=6;i>=0;i--)
xx[i]=0x00;
xx[7]=0x79;
}
while(xx[7]==0x3f)// 去除 显示的问题,即把 显示成 0.
{
for(i=7;i>0;i--)
xx[i]=xx[i-1];
xx[0]=0x00;
}
if(symbol==1)//若为负数时,将数组中的数据后移
{
for(i=6;i>=0;i--)
{
if(xx[i]==0x00)
{
xx[i]=0x40;
break;
}
}
}
}
void delay(unsigned char x)
{
unsigned char i,j;
for(i=0;i<x;i++)
for(j=0;j<x;j++);
}
unsigned char keyscan()//key 为按键返回值
{
uchar temp,row=0,col=0,key;
uint add;
P2&=0xe8;
P1|=0x1f;
temp=P1;
te