51的UART所用的幾個寄存器
SCON:SM0 SM1 SM2 REN RB8 TX8 RI TI
PCON: SMOD -- -- -- --- --- PD IDLE
T2CON: TF2 EXF2 RCLK TCLK EXEN2 TR2 C/_T CP/_RL2
TH2,TL2
波特率為9600bps
avr:atmega64的USART的兩個
所用到的寄存器
這里用的是uart0,所以初始化時應該設(shè)置相關(guān)的寄存器有:
UCSR0A : RXC TXC UDRE FE DOR UPE U2X MPCM
UCSR0C :-- UMSEL UPM1 UPM0 USBS UCSZ1 UCSZ0 UCPOL
UBRR0H 、 UBRR0L、
UCSR0B :RXCIE TXCIE UDRIE RXEN TXEN UCSZ2 RXB8 TXB8
別問我這些都是代表什么含義,,不懂自己翻書去,。,。
proteus仿真如下圖:
仿真結(jié)果如下圖所示:
其中要注意的是:
因為我在仿真中只能選擇atmega64的CKSEL Fuse中的8MHz,,所以在AVR的程序中初始化波特率是按8MHz來計算的。所以仿真歸仿真,,注意實際中應用,。
51單片機用定時器1來產(chǎn)生波特率時,看書據(jù)說模式2下,,12MHz時最高只能到達4800bps,。這里就只好用定時器2來。不過也挺好用的,。。仿真時用的是8052核,。,。否則沒反應不要怪我哦,。。
最后把程序附上,,里面有些變量聲明了沒有用到,,當初只是實驗。,。
51的:
#include "reg52.h"
#define AA 0x61
#define commun_symbol 0x31
sbit LED=P2^0;
unsigned char Tx[]={"my name is seven!"};
void uart_init(void)
{
SCON = 0x50;
RCAP2H = 0xFF;
RCAP2L = 0xD9;
TH2 = 0xFF;
TL2 = 0xD9;
T2CON = 0x34;
}
void uart_send(unsigned char byData)
{
TI=0;
SBUF=byData;
while(TI==0);
TI=1;
}
unsigned char uart_receive(void)
{
RI=0;
while(RI==0);
RI=1;
return(SBUF);
}
void main()
{
unsigned char byBuff,i;
uart_init();
uart_send(commun_symbol);
while(1)
{
byBuff=uart_receive();
LED=1;
if(byBuff==0x31)
{
for(i=0;i<20;i++)
{
P1=byBuff;
uart_send(Tx[i]);
}
}
}
}
atmega64的程序:
兩個文件,,一個是將函數(shù)模塊化,別一個是主函數(shù),,調(diào)用(- -,!最近習慣將程序模塊化。,。,。)
//------------------uart.c---------------------
//----這里將通信函數(shù)模塊化------------
#include
void uart0_init(void)
{
UCSR0B = 0x00; //disable while setting baud rate
UCSR0A = 0x00;
UCSR0C = 0x06;
UBRR0L = 0x33; //set baud rate lo
UBRR0H = 0x00; //set baud rate hi
UCSR0B = 0x18;
}
void uart0_Transmit( unsigned char da
{
/* Wait for empty transmit buffer */
while ( !( UCSR0A & (1<
/* Copy ninth bit to TXB8 */
UCSR0B &= ~(1<
//UCSR0B |= (1<
UDR0 = da
}
unsigned char uart0_Receive( void )
{
/* 等待接收數(shù)據(jù)*/
while ( !(UCSR0A & (1<
/* 從緩沖器中獲取并返回數(shù)據(jù)*/
return UDR0;
}
//--------------main.c-----------
//--------------------------------
#include
#include "spi.h"
#define commun_symbol 0x31
//-----------send a commun_symbol-----
//-----------receive a commun_symbol--
// <--no,continue receive||||||yes-->receive the da
void main()
{
unsigned char bybuff;
DDRB=0xff;
PORTB=0xff;
uart0_init();
{
do
{
bybuff=uart0_Receive();
}
while (bybuff!=commun_symbol);//commun_symbol);
while(1)
{
uart0_Transmit(bybuff);
bybuff=uart0_Receive();
PORTB=(0xff|bybuff);
}
}
}