#include "reg52.h"
#include "string.h"
#include "stdlib.h"
#include "stdio.h"
#define uchar unsigned char
#define uint unsigned int
unsigned char flag,c;
uchar receivedata[12] ;
double number1,number2,result1;
uint number3,number4;
uchar number[1][4] ;
uint length,count,i,point,j,k,result2;
uchar yunsuanfu;
uchar senddata[10];
void UsartInit()
{
SCON=0x50;
TMOD=0X20;
PCON=0X80;
TH1=0XF3;
TL0=0XF3;
ES=1;
EA=1;
TR1=1;
}
void Usart() interrupt 4
{
if(RI==1)
{
receivedata[count]=SBUF;
if(receivedata[count]=='=')
{
flag=1;
length=count;
}
count++;
RI=0;
}
}
void main()
{
UsartInit();
while(1)
{
if(flag==1)
{
ES=0;
while(receivedata[i])
{
if(receivedata[i]=='=')
break;
if((receivedata[i]>=48 && receivedata[i]<=57) || receivedata[i]=='.')
{
if(receivedata[i]=='.')
point=1;
number[j][i-k]=receivedata[i];
i++;
}
else
{
yunsuanfu=receivedata[i];
i++;
k=i;
j++;
}
}
if(point==1)
{
number1=atof(number[0]);
number2=atof(number[1]);
switch(yunsuanfu)
{
case '+':result1=number1+number2;break;
case '-':result1=number1-number2;break;
case '*':result1=number1*number2;break;
case '/':result1=number1/number2;break;
default: break;
}
sprintf(senddata,"%.3f",result1);
}
else
{
number3=atoi(number[0]);
number4=atoi(number[1]);
switch(yunsuanfu)
{
case '+':result2=number3+number4;break;
case '-':result2=number3-number4;break;
case '*':result2=number3*number4;break;
case '/':result2=number3/number4;break;
default: break;
}
sprintf(senddata,"%d",result2);
}
for(c=0;c<10;c++)
{
SBUF=senddata[c];
while(!TI);
TI=0;
}
ES=1;
flag=0;
}
}
}
你发送的字符,程序的操作对象其实是它的ASCII码,你可以先用函数转化成整型或者浮点型数
Atof()函数:
其作用是把括号内的一个字符串转化为浮点数:
Atoi()函数:
其作用是把括号内的一个字符串转化为整数;
Sprintf()函数:
其作用是将一个数变成字符串存到一个数组中去;
sprintf(senddata,"%d",result2);例如这个的意思就是把数据result2变成字符串再存到senddata数组中去。
|