|
本帖最后由 liweiyuangangan 于 2013-1-11 14:17 编辑
#include <iom8v.h>
#include <macros.h>
void port_init(void)
{
PORTB = 0x00;
DDRB = 0x00;
PORTC = 0x00; //m103 output only
DDRC = 0x00;
PORTD = 0x00;
DDRD = 0x00;
}
//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
CLI(); //disable all interrupts
port_init();
MCUCR = 0x00;
GICR = 0x00;
TIMSK = 0x00; //timer interrupt sources
SEI(); //re-enable interrupts
//all peripherals are now initialized
}
/************************************
Name :小延时程序
Target :atmega8
Crystal(晶振):8M
************************************/
void delay()
{
unsigned int i;//最大值65536
for (i=0;i<40000;i++)
{;}
}
/***********************************************************
用 途:串口发送接收程序
Taget :mega8
crystal :8M
介 绍:
**********************************************************/
//晶振和波特率
#define fosc 8000000
#define baud 9600
//UART初始化函数
void init_uart()
{
UCSRB=(1<<RXEN)|(1<<TXEN)|(1<<RXCIE);//允许收发,打开接收中断
UBRRL=(fosc/16/(baud+1))%256;//设置波特率寄存器
UBRRH=(fosc/16/(baud+1))/256;
UCSRC=(1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);//8位数据+1位STOP
}
//字符输出
void uart_putchar(unsigned char c)
{
while(!(UCSRA&(1<<UDRE)));//上次发送有没有完成
UDR=c;
}
//字符输入
unsigned char uart_getchar()
{
while(!(UCSRA&(1<<RXC))){;}//有没有接收到数据
return UDR;
}
//带回车的字符串输出
int uart_print(char *s)
{
while(*s)
{
uart_putchar(*s);
s++;
}
uart_putchar(0x0a);//回车换行
uart_putchar(0x0d);
return 1;
}
//不带回车换行的字符串输出
void uart_prints(char *s)
{
while(*s)
{
uart_putchar(*s);
s++;
}
}
//接收中断
#pragma interrupt_handler uart_rec_int:iv_USART_RX
void uart_rec_int()
{
uart_putchar(UDR);
uart_putchar(0x0a);//回车换行
uart_putchar(0x0d);
}
//**************************************************************************
void main()
{
port_init();
init_devices();
init_uart();
uart_print("xiaozhiyong");
while(1)
{
uart_print("aaa");
//delay();
}
}
上面的程序,但是设置的是9600波特率,连电脑后,看以9600波特率看数据不行,都是一个乱码,换成1200就可以看出数据而且正确,好奇怪,是不是程序有问题,求教育,忘说了,用的是8m外部晶振
UBRRL=(fosc/16/(baud+1))%256;//设置波特率寄存器
UBRRH=(fosc/16/(baud+1))/256;
改为
UBRRH=0;
UBRRL=51; //9600
也是不行,参考帖子http://www.amobbs.com/forum.php? ... light=mega8%2BUSART
|
阿莫论坛20周年了!感谢大家的支持与爱护!!
知道什么是神吗?其实神本来也是人,只不过神做了人做不到的事情 所以才成了神。 (头文字D, 杜汶泽)
|