#include "public.h" #include "smg.h" #include "ds18b20.h" #include "reg52.h" #include <stdio.h> void init_uart() { SCON = 0x50; TMOD = 0x20; TH1 = 0xfd; TL1 = 0xfd; TR1 = 1; EA = 1; ES = 1; } void send_byte(unsigned char dat) { SBUF = dat; while(!TI); TI = 0; } void send_string(char *str) { while(*str != '\0') { send_byte(*str++); } } void main() { u8 i=0; int temp_value; u8 temp_buf[5]; char str[10]; init_uart(); // ds18b20_init(); // while(1) { i++; if(i%50==0) // temp_value=ds18b20_read_temperture()*10; if(temp_value<0) { temp_value=-temp_value; temp_buf[0]=0x40; } else temp_buf[0]=0x00; temp_buf[0]=gsmg_code[temp_value/1000]; temp_buf[1]=gsmg_code[temp_value%1000/100]; temp_buf[2]=gsmg_code[temp_value%1000%100/10]|0x80; temp_buf[3]=gsmg_code[temp_value%1000%100%10]; smg_display(temp_buf,1); sprintf(str, "%d.%d\r\n", temp_value/100, temp_value%10); send_string(str); } }请逐行解释代码
时间: 2024-03-25 22:39:32 浏览: 17
好的,我来逐行解释这段代码:
```c
#include "public.h"
#include "smg.h"
#include "ds18b20.h"
#include "reg52.h"
#include <stdio.h>
```
这里是包含了程序所需要的头文件。
```c
void init_uart() {
SCON = 0x50;
TMOD = 0x20;
TH1 = 0xfd;
TL1 = 0xfd;
TR1 = 1;
EA = 1;
ES = 1;
}
```
这个函数是初始化串口的函数,其中 SCON、TMOD、TH1、TL1、TR1、EA 和 ES 都是 8051 的寄存器。SCON 设置串口工作方式,TMOD 设置计时器工作方式,TH1 和 TL1 设置波特率,TR1 开启计时器,EA 和 ES 开启中断。
```c
void send_byte(unsigned char dat) {
SBUF = dat;
while(!TI);
TI = 0;
}
```
这个函数是发送一个字节的函数,其中 SBUF 是串口数据寄存器,TI 是发送中断标志位。这个函数的作用是将 dat 发送出去,并等待发送完成。
```c
void send_string(char *str) {
while(*str != '\0')
{
send_byte(*str++);
}
}
```
这个函数是发送字符串的函数,其中 *str 是指向字符串的指针,'\0' 表示字符串结束符。这个函数的作用是将整个字符串发送出去,调用了上面的 send_byte 函数。
```c
void main() {
u8 i=0;
int temp_value;
u8 temp_buf[5];
char str[10];
init_uart(); // 初始化串口
while(1)
{
i++;
if(i%50==0) // 读取温度
temp_value=ds18b20_read_temperture()*10;
if(temp_value<0)
{
temp_value=-temp_value;
temp_buf[0]=0x40;
}
else
temp_buf[0]=0x00;
temp_buf[0]=gsmg_code[temp_value/1000];
temp_buf[1]=gsmg_code[temp_value%1000/100];
temp_buf[2]=gsmg_code[temp_value%1000%100/10]|0x80;
temp_buf[3]=gsmg_code[temp_value%1000%100%10];
smg_display(temp_buf,1); // 数码管显示温度
sprintf(str, "%d.%d\r\n", temp_value/100, temp_value%10);
send_string(str); // 通过串口发送温度值
}
}
```
这个函数是主函数,其中 i、temp_value、temp_buf 和 str 都是变量。首先调用了 init_uart 函数初始化串口,然后进入一个无限循环。在循环中,每次 i 自增 1,当 i 能被 50 整除时,调用 ds18b20_read_temperture 函数读取温度值,并将其乘以 10。接着判断温度值是否小于 0,如果是,则将其取反,并将 temp_buf[0] 的值设置为 0x40,否则为 0x00。然后将温度值的千位、百位、十位和个位分别存放到 temp_buf 数组中,并调用 smg_display 函数将温度值显示在数码管上。最后,使用 sprintf 函数将温度值转换为字符串格式,再通过 send_string 函数将温度值发送到串口。
希望这些解释能够帮助您理解这段代码。