题目要求:
串口通信:PC发送一系列字符串(以$为结束符)给单片机,单片机收到数据后,统计A的个数并返回。
本次解题采用keil5,proteus仿真软件。
电路图:
代码:
头文件
#ifndef A_h
#define A_h
#include <reg52.h>
char Dat[100];
unsigned char n=0;
unsigned char i=0;
void SerInit(void);
void SendChar(char);
void SendOut(unsigned char *p);
void output();
void clear();
#endif
主代码
#include "A.h"
void main(void)
{
SerInit();
SendOut("Input ");
while(1)
{
}
}
void SendOut(char *s) //发送字符串
{
char c;
while(1)
{
c = *s++;
SendChar(c);
if(*s=='\0')
break;
}
}
void SendChar(char dat)
{
ES=0;
SBUF=dat;
while(!TI);
TI=0;
ES=1;
}
void SerInit(void)
{
TMOD = 0x20; /* 00100000 */
TH1 = -11059200L / 12 / 16 / 9600L; /* L是长整型数据 */
TL1 = -11059200L / 12 / 16 / 9600L;
TR1 = 1;
ET1 = 0; /* 禁止T1中断 */
ES = 1; /* 允许串行中断 */
EA = 1;
PCON = 0x80;
SCON = 0x50;
}
void SerSev(void) interrupt 4
{
if(RI)
{
Dat[i] = SBUF; //
if(SBUF=='A') //统计A的个数
{
n++;
}
if(SBUF=='$')
{
output();
}
i++;
RI = 0;
}
else
{
TI = 0;
}
}
void output() //输出
{
char ge,shi,bai;
ge=(n%100%10)+'0'; //将int转化为char
shi=(n%100/10)+'0';
bai=(n/100)+'0';
SendOut(" 'A' num is ");
SendChar(bai);
SendChar(shi);
SendChar(ge);
n=0;
clear();
}
void clear()
{
unsigned char i=0;
while(Dat[i]!='\0')
{
Dat[i]=0;
}
}
运行结果:
电路图及代码文件下载:
下载地址