Keil AT89C51单片机接收串口助手发送的字符串并转化为整数然后显示在数码管上的代码
时间: 2024-03-07 17:47:12 浏览: 91
以下是基于 Keil C51 编写的代码,实现了 AT89C51 单片机接收串口助手发送的字符串并转化为整数,最后将整数显示在数码管上:
```c
#include <reg51.h>
#define FOSC 11059200L
#define BAUD 9600
#define TH1 256 - FOSC / 12 / BAUD
sbit SDA = P1 ^ 0;
sbit SCL = P1 ^ 1;
sbit D1 = P2 ^ 0;
sbit D2 = P2 ^ 1;
sbit D3 = P2 ^ 2;
sbit D4 = P2 ^ 3;
void delay(unsigned int t)
{
while (t--);
}
void start()
{
SDA = 1;
delay(1);
SCL = 1;
delay(1);
SDA = 0;
delay(1);
SCL = 0;
delay(1);
}
void stop()
{
SDA = 0;
delay(1);
SCL = 1;
delay(1);
SDA = 1;
delay(1);
SCL = 0;
delay(1);
}
void ack()
{
SDA = 0;
delay(1);
SCL = 1;
delay(1);
SCL = 0;
delay(1);
SDA = 1;
delay(1);
}
void nack()
{
SDA = 1;
delay(1);
SCL = 1;
delay(1);
SCL = 0;
delay(1);
}
unsigned char read()
{
unsigned char i, dat = 0;
SDA = 1;
for (i = 0; i < 8; i++)
{
SCL = 1;
delay(1);
dat <<= 1;
dat |= SDA;
SCL = 0;
delay(1);
}
return dat;
}
void write(unsigned char dat)
{
unsigned char i;
for (i = 0; i < 8; i++)
{
SDA = dat & 0x80;
dat <<= 1;
delay(1);
SCL = 1;
delay(1);
SCL = 0;
}
ack();
}
void init_uart()
{
TMOD = 0x20;
TH1 = TH1;
SCON = 0x50;
TR1 = 1;
}
unsigned char get_byte()
{
while (!RI);
RI = 0;
return SBUF;
}
void put_byte(unsigned char dat)
{
SBUF = dat;
while (!TI);
TI = 0;
}
void put_string(char *str)
{
while (*str)
{
put_byte(*str++);
}
}
void main()
{
char buf[16];
unsigned int num;
unsigned char i, len;
init_uart();
while (1)
{
i = 0;
while (1)
{
buf[i++] = get_byte();
if (buf[i - 1] == '\r')
{
buf[i - 1] = '\0';
break;
}
}
num = 0;
len = strlen(buf);
for (i = 0; i < len; i++)
{
num = num * 10 + buf[i] - '0';
}
D1 = num % 10;
D2 = num / 10 % 10;
D3 = num / 100 % 10;
D4 = num / 1000;
}
}
```
这段代码首先定义了几个宏,包括晶振频率、波特率以及定时器 TH1 的值。接着定义了一些函数,包括启动信号、停止信号、应答信号、非应答信号、读取数据和写入数据等。然后实现了串口初始化函数、读取一个字节、发送一个字节和发送字符串等。最后在主函数中循环读取串口数据,并将读取到的字符串转化为整数,最后将整数显示在数码管上。
阅读全文