用单片机做一个计算器
硬件电路
程序
【用单片机做一个计算器】#include T89X51.H>
#define DIN P1_0
#define CLK P1_2
#define LOAD P1_1
unsigned char key_h,key_l,key_code;
unsigned char ADS,i,j,m,n;
unsigned char n_bit=0;
unsigned char flag=0;
unsigned char key_num[16]={7,8,9,'/',4,5,6,'*',1,2,3,'-','c',0,'=','+'};
unsigned char data1[6]={0};
unsigned char data2[6]={0};
unsigned int result;
void delay(unsigned int n)
{
while(n--);
}
void send(unsigned char addr,unsigned char dat)
{
LOAD=0;
i=0;
while(i<16)
{
if(i<8) ADS=addr;
else
ADS=dat;
for(j=8;j>=1;j--)
{
DIN=ADS&0x80;
ADS<<=1;
CLK=1;
CLK=0;
}
i+=8;
}
LOAD=1;
}
void clear()
{
for(m=1;m<=5;m++)
send(m,0xff);
send(0x06,0);
n_bit=6;
}
void calc()
{
unsigned int temp1;
unsigned int tmep2;
unsigned char temp;
temp1=data1[5]+data1[4]*10+data1[3]*100+data1[2]*1000+data1[1]*10000;
tmep2=data2[5]+data2[4]*10+data2[3]*100+data2[2]*1000+data2[1]*10000;
switch(flag)
{
case 1: result=temp1+tmep2; break;
case 2: result=temp1-tmep2; break;
case 3: result=temp1*tmep2; break;
case 4: result=temp1/tmep2; break;
}
clear();
for(n=6;n>1;n--)
{
temp=(unsigned char)result%10;
if(temp) send(n,temp);
result/=10;
data2[n-1]=data1[n-1]=0;
}
flag=0;
while((P2&0xf0)!=0xf0);
}
void keyScan()//键盘扫描程序
{
if((P2&0xf0)!=0xf0)
delay(20);
if((P2&0xf0)!=0xf0)
{
key_h=P2&0xf0;
P2=0xf0|0x01;
if((P2&0xf0)==0xf0) key_l=0;
P2=0xf0|0x02;
if((P2&0xf0)==0xf0) key_l=1;
P2=0xf0|0x04;
if((P2&0xf0)==0xf0) key_l=2;
P2=0xf0|0x08;
if((P2&0xf0)==0xf0) key_l=3;
P2=0xf0;
switch((~P2)&0xf0)
{
case 0x10: key_h=0x0; break;
case 0x20: key_h=0x1; break;
case 0x40: key_h=0x2; break;
case 0x80: key_h=0x3; break;
}
key_code=key_l*4+key_h;
switch(key_code)
{
case 3: flag=4;n_bit=7;break;//+
case 7: flag=3;n_bit=7;break;//-
case 11: flag=2;n_bit=7;break;//*
case 15: flag=1;n_bit=7;break;///
case 14: calc();n_bit=7;return;//=
case 12: clear();break;//C
default:
if(n_bit>1)
{
if(n_bit==7)
{
clear();
}
send(n_bit--,key_num[key_code]);
if(!flag)
data1[n_bit]=key_num[key_code];
else
data2[n_bit]=key_num[key_code];
}
}
while((P2&0xf0)!=0xf0);
}
}
void main(void)
{
P2=0xf0;
send(0x0c,0x01);
send(0x0b,0x05);
send(0x0a,0xf5);
send(0x09,0xff);
//
// send(0x01,0x8f);
// send(0x02,0x82);
// send(0x03,0x83);
// send(0x04,0x84);
// send(0x05,0x85);
// send(0x06,0x86);
// send(0x07,0x87);
// send(0x08,0x08);
clear();
n_bit=6;
while(1)
{
keyScan();
}
}
推荐阅读
- 海苔是什么原料做的「海苔的种类和区别」
- 科勒智能马桶好不好用
- 地板漆哪个牌子好浅解地板漆的3大作用
- 2016热门电磁炉排名
- 购买橱柜 需要做哪些准备工作?
- 常用的dc插座种类及型号规格有哪些
- 浅析流量传感器在医疗器械中的技术应用
- 未来手术机器人中多种传感器技术的精确应用
- 如何打造日式实用主义家 日式实用主义家装设计
- 客厅的窗帘用全遮光的好还是用半遮光的好?