单片机教程网

电脑版
提示:原网页已由神马搜索转码, 内容由www.51hei.com提供.
查看:471|回复:1
打印上一主题下一主题

m8单片机串口通讯程序

[复制链接]
跳转到指定楼层
楼主
ID:1104531发表于 2024-1-11 21:08|只看该作者回帖奖励
个人认为,AVR系列的串口使用还是比较容易出错,如果采用传统的查询方式太耗系统时间,而且现在关于AVR的教材大多给你的是查询发送方式,中断接收方式。
本例子是采用中断接收,中断发送方式。希望对大家有所帮助。

//ICC-AVR
// Target : M8
// Crystal: 4.0000Mhz

#include< iom8v.h>
#include< macros.h>

#define DISABLE_UARTTX()       UCSRB&=~BIT(TXCIE)
#define ABLE_UARTTX()           UCSRA|=BIT(TXC);UCSRB|=BIT(TXCIE)

unsigned char ucRecv;
unsigned char ucRecvOk;

unsigned char ucSendData[8]="Recv OK!";
unsigned char ucComSendCnt,ucComSendPtr;


void InitPort(void)
{
       PORTB = 0xFF;
       DDRB  = 0x00;
       PORTC = 0x7F; //m103 output only
       DDRC  = 0x00;
       PORTD = 0xFE;
       DDRD  = 0x02;
}

//UART0 initialize
// desired baud rate: 2400
// actual: baud rate:2404 (0.2%)
void InitUart0(void)
{
       UCSRB = 0x00; //disable while setting baud rate
       UCSRA = 0x00;
       UCSRC = BIT(URSEL) | 0x06;
       UBRRL = 0x67; //set baud rate lo
       UBRRH = 0x00; //set baud rate hi
       UCSRB = 0x98;
}

#pragma interrupt_handler uart0_rx_isr:iv_USART0_RXC
void uart0_rx_isr(void)
{
       unsigned char ucTmp;
//uart has received a character in UDR
       ucTmp=UDR;
       if (ucTmp=='A')
       {
           ucRecv=ucTmp;
           ucRecvOk=0x01;      
       }
}


#pragma interrupt_handler uart0_tx_isr:iv_USART0_TXC
void uart0_tx_isr(void)
{
//character has been transmitted
       if (ucComSendCnt!=0)
       {
             ucComSendPtr+=1;
             UDR=ucSendData[ucComSendPtr];
           ucComSendCnt-=1;
       }else
       {      
           //PORTB&=~BIT(PB_COM_LED);                           //串口指示灯灭
           DISABLE_UARTTX();
           //PORTB^=BIT(PB_COM_LED);                           //串口指示灯灭
       }
}



//call this routine to initialize all peripherals
void InitMcu(void)
{
//stop errant interrupts until set up
       CLI();                 //disable all interrupts
       InitPort();
       InitUart0();

       MCUCR = 0x00;
       GICR  = 0x00;
       TIMSK = 0x00;       //timer interrupt sources
       SEI();                 //re-enable interrupts
                             //all peripherals are now initialized
}



void main(void)
{
       unsigned char i;
       InitMcu();
       while(1)
       {
           if (ucRecvOk==0x01)
           {
                 CLI();
                 ucRecvOk=0;
                 SEI();
                
                 ucComSendCnt=7;
                 ucComSendPtr=0;
                 ABLE_UARTTX();
                 UDR=ucSendData[0];
           }      
       }
}

m8 串口通讯.zip

44.24 KB, 下载次数: 4, 下载积分: 黑币 -5

评分

黑币 +50
收起理由
+ 50
共享资料的黑币奖励!

查看全部评分

沙发
ID:229502发表于 2024-2-11 21:18|只看该作者
楼主能否有个注解,对初学者更友好

手机版|小黑屋|51黑电子论坛|51黑电子论坛6群QQ管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网