串口通信._c

来自「AVR之ATMega16」· _C 代码 · 共 77 行

_C
77
字号
//外部晶振 8M
#include <ioM16v.h>
#include <macros.h>
#include"delay.h"



/*------宏定义------*/
#define uchar	unsigned char
#define uint	unsigned int



//端口初始化
void port_init(void)
{
 PORTA = 0x00;//设置端口方向、数据
 DDRA  = 0x00;
 PORTB = 0x00;
 DDRB  = 0x00;
 PORTC = 0x00;
 DDRC  = 0x00;
 PORTD = 0x00;
 DDRD  = 0x03;
}


//串口通信初始化
void usart_init(void)
{
 UCSRB = 0x00;//禁止中断
 UCSRA = 0x00;//数据发送、接受位、数据帧错误、奇偶校验、溢出、多机模式
 UCSRC = BIT(URSEL) | 0x06;//使用UBRRH寄存器、数据位数8位
 UBRRL = 0x19;//设置波特率
 UBRRH = 0x00;
 UCSRB = 0x98;//接受中断使能、接受、发送使能、不使用第9数据位
}
void uart_putchar(char x)
{
 	 while (!(UCSRA&0x20))//查询发送区是否为空
	 ;
	 UDR=x; //发送数据 
}

//串行接收结束中断服务程序
#pragma interrupt_handler usart_rx_isr:12
void usart_rx_isr(void)
{
 	 char y;
	 y=UDR;
	 uart_putchar(y);//把接收到的数据返回给上位机
}


void init_devices(void)
{
 CLI(); //禁止所有中断
 MCUCR  = 0x00;//INT0、INT1中断触发方式
 MCUCSR = 0x80;//禁止JTAG
 GICR   = 0x00;//外部中断使能
 port_init();
 usart_init();
 SEI();//开全局中断
}
//主函数
void main(void)
{
 init_devices();
 //在这继续添加你的代码
 while(1)
 {
  NOP();
 }
}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?