uart.c

来自「avr单片机mega128 的串口通讯的完整程序」· C语言 代码 · 共 110 行

C
110
字号
//-----------------------------------------------------------
//程序由AVR辅助开发工具V2.1.1自动生成     
//MCU系统的处理器为:    ATMega128
//MCU系统的晶振频率:    8.0000 Mhz
//-----------------------------------------------------------

#include <iom128v.h>
#include "uart.h"
#include "delay.h"


//-----------------------------------------------------------
//串口0初始化子程序
//字符长度:8位
//奇偶校验:禁止
//通讯模式:异步
//-----------------------------------------------------------
void Uart0_Init(void)
{
    UCSR0B  =  0x00;     //disable while setting baud rate
    UCSR0A  =  0x00;     //Bit1为1则倍速发送
    UCSR0C  =  0x06;  
    UBRR0L  =  0x22;     //波特率:14400 Bps
    UBRR0H  =  0x00;     //误差率:-0.799%
    UCSR0B  =  0x18;  
//初始化RS485通讯的流控制引脚
    RS485_RD0_PORT|= RS485_RD0_BIT;
    RS485_RD0_DDR|= RS485_RD0_BIT;
    RS485_RD0_L;
}

//-----------------------------------------------------------
//串口0接收字节子程序
//-----------------------------------------------------------
unsigned char Getchar0(void)
{
 while(!(UCSR0A& (1<<RXC0)));
   return UDR0;
}

//-----------------------------------------------------------
//串口0发送字节子程序
//-----------------------------------------------------------
void Putchar0(unsigned char c)
{
   RS485_RD0_H;
   while (!(UCSR0A&(1<<UDRE0)));
   UDR0=c;
   while (!(UCSR0A&(1<<UDRE0)));
   delay_nus(500);
   RS485_RD0_L;
}

//-----------------------------------------------------------
//串口0发送字符串子程序
//-----------------------------------------------------------
void Putstr0(char *s)
{
   while (*s)
   {
      Putchar0(*s);
      s++;
   }
}

//-----------------------------------------------------------
//串口0发送字符串子程序(带有换行符)
//-----------------------------------------------------------
void Puts0(char *s)
{
   while (*s)
   {
      Putchar0(*s);
      s++;
   }
   Putchar0(0x0d);   //回车换行
   Putchar0(0x0a);
}

//-----------------------------------------------------------
//数组转换成可发送的字符串
//-----------------------------------------------------------
char *buffer2str(char *hhh)
{
   unsigned char i=0;

   while (i<40)
   {
      hhh[i]=hhh[i]+48;
      i++;
   }	
   return hhh;
}

//-----------------------------------------------------------
//数字转换成可发送的字符串
//-----------------------------------------------------------
char *long2str(unsigned long hh)
{
   char *ss="    ";

   ss[0]=48+hh/1000;
   ss[1]=48+(hh%1000)/100;
   ss[2]=48+(hh%100)/10;
   ss[3]=48+(hh%10);

   return ss;	
}

⌨️ 快捷键说明

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