该"测试程序"系列的编写是为了检测学校实验室板子上的各个部分是否正常工作 同时复习之前实验的知识要点 由于代码上附带多数注释 故此文只放代码 不再多做注解
/*
作者:Murrey_Xiao
编写时间:2017.6.5
功能介绍:
该程序为MEGA16上UART的测试代码。
UART通讯主要控制通讯双方的波特率和帧格式,与时钟频率无关。
USART_sendData8()实现数据的发送
USART_getData8()或uart0_rx_isr()中断实现数据的接收
使用中断实现数据接收时,
需要初始化寄存器B:UCSRB |= (1<<RXCIE);并编写中断服务程序。
注意:设置帧格式时:UCSRC |= (1<<URSEL)|(1<<USBS)|(3<<UCSZ0);
即必须在使能URSEL的同时,对其他项同时进行设置,否则设置无效。
*/
#include <iom16v.h>
#include <macros.h>
#define MCLK 7.3728
void port_init(void)
{
PORTA = 0x00;
DDRA = 0xff;
}
unsigned char USART_getData8(void)
{
// wait for receiving the data completed
while (!(UCSRA & (1<<RXC))) ;
// return the data
return UDR;
}
void USART_sendData8(unsigned char data)
{
// wait for UDR empty
while (!(UCSRA & (1<<UDRE))) ;
// assign the data to UDR, ready to send
UDR = data;
}
/*
#pragma interrupt_handler uart0_rx_isr:iv_USART0_RXC
void uart0_rx_isr(void)
{
//uart has received a character in UDR
dataGet=UDR;
}
*/
void USART_init(unsigned int baud)
{
unsigned int ubrr_calc;
//UCSR Init
UCSRA = 0x00;
UCSRB = 0x00;
UCSRC = 0x00;
// set baud rate
UCSRC &=~(1<<URSEL); //EN UBRRH
ubrr_calc=MCLK*1000000/16/baud-1;
UBRRL = (unsigned char)ubrr_calc;
UBRRH = (unsigned char)(ubrr_calc >> 8);
// enable TX and RX
UCSRB |= (1<<RXEN) | (1<<TXEN);
// enable complete action to interrupt
//UCSRB |= (1<<RXCIE);
// set frame format
// EN UCSRC / 2 bit for stop / 8 bit for data / no check
UCSRC |= (1<<URSEL)|(1<<USBS)|(3<<UCSZ0);
}
//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
CLI(); //disable all interrupts
port_init();
//uart0_init();
USART_init(9600);
MCUCR = 0x00;
GICR = 0x00;
TIMSK = 0x00; //timer interrupt sources
SEI(); //re-enable interrupts
//all peripherals are now initialized
}
int main(void)
{
unsigned char i;
init_devices();
while(1)
{
PORTA = USART_getData8();
}
return 0;
}