📄 串口发送接收._c
字号:
//ICC-AVR application builder : 2009-3-11 14:28:07
// Target : M8
// Crystal: 8.0000Mhz
#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()
{
unsigned char i;
i=UDR;
uart_putchar(i);
uart_putchar(0x0a);//回车换行
uart_putchar(0x0d);
}
//**************************************************************************
void main()
{
port_init();
init_devices();
init_uart();
uart_print("xiaozhiyong");
while(1)
{
;
//delay();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -