/**********************************************
工程名称:485通讯接口测试程序
控 制 器: ATmega16
说 明:CPU通过串口接RS485发送数据,终端PC机通过
RS485转RS232转换器接入PC机,使用串口调试
助手发送数据并接收数据。
端口配置:
CPU RS485
RXD RO
TXD DI
PD2 DE,/RE
**********************************************/
#include <avr/io.h rel='nofollow' onclick='return false;'>
#include <util/delay.h>
#include <avr/interrupt.h rel='nofollow' onclick='return false;'>
#define uchar unsigned char
#define uint unsigned int
//常量声明
#define BAUD 9600
volatile uchar rdata;
volatile uint8_t flag=0;
volatile uint8_t n=0;
/*******************************************
函数名称: port_init
功 能: 端口初始化
参 数:
返回值 : 无
********************************************/
void port_init(void)
{
//USART的接收端口为PD0,发送端口为PD1,
//PD2=0 485芯片的/RE端口使能,PD2=1 485芯片的DE端口输出驱动使能
PORTD = 0x00;
DDRD |= (1 << PD1); //PD1为发送端口,置为输出
DDRD |= (1 << PD2); //PD2为485接收发送使能,置1为可输出
}
/*******************************************
函数名称: uart_init
功 能: 计算波特率,可任意设置
参 数:
返回值 : 无
********************************************/
void uart_init(void)
{
UCSRB=0x00;
UCSRA=0x00; //控制寄存器清零
UCSRC = (1<<URSEL)|(0<<USBS)|(0<<UPM0)|(3<<UCSZ0);//设置帧格式: 8 个数据位, 1 个停止位,异步模式,禁止校验
UBRRL = (F_CPU / BAUD / 16 - 1) % 256; //波特率设置
UBRRH = (F_CPU / BAUD / 16 - 1) / 256;
UCSRB=(1<<TXEN)|(1<<RXEN)|(1<<RXCIE); //接收、发送使能,接收中断使能
SREG=_BV(7); //全局中断开放
}
/*******************************************
函数名称: uart_sendB
功 能: 发送数据
参 数:
返回值 : 无
********************************************/
void uart_sendB(uchar data)
{
while(!(UCSRA&(_BV(UDRE))));
UDR=data;
while(!(UCSRA&(_BV(TXC))));
UCSRA|=_BV(TXC);
}
ISR(USART_RXC_vect)
{
UCSRB &= ~_BV(RXCIE);
rdata=UDR;
flag=1;
UCSRB|=_BV(RXCIE);
}
/*****************************************************************************************************
;* 函数名称 : UART0_Puts
;* 描 述 : 串口发送字符串
;* 输 入 : *Str: 字符串
;*
;* 输 出 : 无
****************************************************************************************************/
void UART_Puts(uchar *Str)
{
while (*Str) //字符串未结束则继续发送
{
uart_sendB(*Str++);
}
}
/*******************************************
函数名称: main
功 能: 完成异步串口接收数据,并返回给PC机(用串口调试助手)
参 数:
返回值 : 无
********************************************/
int main(void)
{
port_init();
uart_init(); //初始化串口,设置波特率
PORTD |= _BV(PD2);
// _delay_ms(2);
UART_Puts("\r\n你发送的字符串是:");//发送字符串
_delay_ms(2);
PORTD &= ~_BV(PD2);
while(1)
{
if(flag)
{
PORTD |= _BV(PD2);
// _delay_ms(2);
uart_sendB(rdata);
_delay_ms(2);
PORTD &= ~_BV(PD2);
flag=0; //清收到新数据标志位
}
}
}