C51跟atmega64的串行通信。相關(guān)理論知識(shí)這里就不多說(shuō),只提幾個(gè):
51的UART所用的幾個(gè)寄存器
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的兩個(gè)
所用到的寄存器
這里用的是uart0,所以初始化時(shí)應(yīng)該設(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
別問(wèn)我這些都是代表什么含義,不懂自己翻書(shū)去。。
PROTEUS仿真如下圖:
仿真結(jié)果如下圖所示:
其中要注意的是:
因?yàn)槲以诜抡嬷兄荒苓x擇atmega64的CKSEL Fuse中的8MHz,所以在AVR的程序中初始化波特率是按8MHz來(lái)計(jì)算的。所以仿真歸仿真,注意實(shí)際中應(yīng)用。
51單片機(jī)用定時(shí)器1來(lái)產(chǎn)生波特率時(shí),看書(shū)據(jù)說(shuō)模式2下,12MHz時(shí)最高只能到達(dá)4800bps。這里就只好用定時(shí)器2來(lái)。不過(guò)也挺好用的。。仿真時(shí)用的是8052核。。否則沒(méi)反應(yīng)不要怪我哦。。
最后把程序附上,里面有些變量聲明了沒(méi)有用到,當(dāng)初只是實(shí)驗(yàn)。。
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的程序:
兩個(gè)文件,一個(gè)是將函數(shù)模塊化,別一個(gè)是主函數(shù),調(diào)用(- -!最近習(xí)慣將程序模塊化。。。)
//------------------uart.c---------------------
//----這里將通信函數(shù)模塊化------------
#include
void UART0_init(void)
baud rate
unsigned char uart0_Receive( void )
//--------------main.c-----------
//--------------------------------
#include
//-----------send a commun_symbol-----
ok,任務(wù)完成了,改天實(shí)驗(yàn)一下!
{
UCSR0B = 0x00; //disable while setting
UCSR0A = 0x00;
UCSR0C = 0x06;
UBRR0L = 0x33; //set baud rate lo
UBRR0H = 0x00; //set baud rate hi
UCSR0B = 0x18;
}
void uart0_Transmit( unsigned char data )
{
/* Wait for empty transmit buffer */
while ( !( UCSR0A & (1<
/* Copy ninth bit to TXB8 */
UCSR0B &= ~(1<
//UCSR0B |= (1<
UDR0 = data;
}
{
/* 等待接收數(shù)據(jù)*/
while ( !(UCSR0A & (1<
/* 從緩沖器中獲取并返回?cái)?shù)據(jù)*/
return UDR0;
}
#include "spi.h"
#define commun_symbol 0x31
//-----------receive a commun_symbol--
// <--no,continue receive||||||yes-->receive the data and send
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);
}
}
}