1 . 串口是指一种应用十分广泛的通讯接口,串口成本低、容易使用,可实现两个设备的互相通信。
51单片机内部自带 UART ( Universal Asynchronous Receiver Transmitter 通用异步收发器 ) ,可实现单片机的串口通讯。
发送端TXD(transmit exchange date);接收端RXD(receive exchange date);

2.电平标准:
电平标准 是 数据 1 和 数据 0 的表达方式;常用的标准有如下三种:
TTL电平:+5V表示1,0V表示0;--------单片机用的就是TTL电平;
RS232电平:-3~-15V表示1,+3~+15V表示0;
RS485电平:两线压差+2~+6V表示1,-2~-6V表示0(差分信号);
3.相关术语:
全双工:通信双方在同一时刻互相传输数据;
半双工:通信双方可以互相传输数据,但必须分时复用一根数据线;(不能既传输数据的同时又接受数据)
波特率:串口通信的速率;发送和接收各数据位的间隔时间;
串口模式图:

串口通讯:
#include <REGX52.H>
#include <Delay.h>
unsigned char Sec;
void UART_Init()//4800波特率12.000MHZ
{
SCON=0x40;
PCON |=0x80;
TMOD &=0x0F;//设置定时器模式
TMOD |=0x20;//设置定时器模式
TL1=0xF3;//设定定时初值
TH1=0xF3;//设定定时器重装值
ET1=0;//禁止定时器1中断
TR1=1;//启动定时器1
EA=1;
ES=1;
}
void UART_SendByte(unsigned char Byte)
{
SBUF=Byte;
while(T1==0);
T1=0;
}
void UART_Routine() interrupt 4
{
if(RI==1)
{
P2=~SBUF;
RI=0;
}
}
void main()
{
UART_Init();
while(1)
{
UART_SendByte(Sec);
Sec++;
Delay(1000);
}
}
按照寄存器进行初始化配置----------》》》

3.串口通讯发送:
main.c
#include <REGX52.H>
#include "Delay.h"
#include "UART.h"
unsigned char Sec;
void main()
{
UART_Init();
while(1)
{
UART_SendByte(Sec);
Sec++;
Delay(1000);
}
}
Delay.c
#include <REGX52.H>
void Delay(unsigned int xms)
{
unsigned char i,j;
while(xms)
{
i=2;
j=239;
do
{
while(--j);
}
while(--i);
xms--;
}
}
Delay.h
#ifndef __DELAY_H__
#define __DELAY_H__
void Delay(unsigned int xms);
#endif
UART.c
#include <REGX52.H>
void UART_Init()
{
SCON=0x40;
PCON|=0x80;
TMOD&=0x0F; //设置定时器模式
TMOD|=0x20; //设置定时器模式
TL1=0xF3; //设定定时初值
TH1=0xF3; //设定定时器重装值
ET1=0; //禁止定时器1中断
TR1=1; //启动定时器1
}
void UART_SendByte(unsigned char Byte)
{
SBUF=Byte;//SBUF----寄存器中储存的空间
while(TI==0);//TI----发送控制器
TI=0;
}
UART.h
#ifndef __UART_H__
#define __UART_H__
void UART_Init();
void UART_SendByte(unsigned char Byte);
#endif
4.串口通讯接收:
中端号:

main.c
#include <REGX52.H>
#include "Delay.h"
#include "UART.h"
void main()
{
UART_Init();
while(1)
{
}
}
void UART_Routine() interrupt 4
{
if(RI==1)//RI接收控制器
{
P2=SBUF;
UART_SendByte(SBUF);
RI=0;
}
}
UART.c
#include <REGX52.H>
void UART_Init()
{
SCON=0x50;
PCON|=0x80;
TMOD&=0x0F; //设置定时器模式
TMOD|=0x20; //设置定时器模式
TL1=0xF3; //设定定时初值
TH1=0xF3; //设定定时器重装值
ET1=0; //禁止定时器1中断
TR1=1; //启动定时器1
EA=1;
ES=1;
}
void UART_SendByte(unsigned char Byte)
{
SBUF=Byte;//SBUF----寄存器中储存的空间
while(TI==0);//TI----发送控制器
TI=0;
}
UART.H
#ifndef __UART_H__
#define __UART_H__
void UART_Init();
void UART_SendByte(unsigned char Byte);
#endif
4975

被折叠的 条评论
为什么被折叠?



