打印

请教多机通信

[复制链接]
1508|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
ayb_ice|  楼主 | 2008-11-8 10:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

/* 肯请高手帮忙
--------------------------------------------
    这是从机的中断接收程序,不知为什么,主机在
发送地址后,要延时一段时间,再发数据,而数据之间

不用延时,如果地址后不延时则从机接收不可靠,

有时不正常,BPS2400也不高,AT89C2051@11.0592MHZ.

主机C8051F020@24MHZ BPS2400有点误差但是很小,

好象是2403.


基本通信格式 : 从机地址+0x0d+命令+帧长(仅数据长度)+数据0+数据1...
--------------------------------------------
*/

uchar rxf;          // 接收状态
uchar rxn;          // 接收数量
uchar address;      // 从机地址
bit isr_receive_ok; // 1=中断接收一帧完整数据

sbit TX_EN = P1^1;  // 1=发送, 0=接收

void isr_uart(void) interrupt 4
{
    uchar x;
    bit b;

//---------------------------------
// 发送应答命令数据
    if(TI){
        TI = 0;
        if(txx != txy){
            SBUF = ack_buffer[txx];
            txx++;
        }else{
            TX_EN = 0;
            receive_error = 0;
        }
    }

//---------------------------------
// 接收
    if(RI){
        x = SBUF;
        b = RB8;
        RI = 0;
        if(rxf && RB8){
            isr_receive_ok = 0;
            SM2 = 1;
            rxf = 0;
            return;
        }

        switch(rxf){
        case 0:
//          LED = 0;
            if(x == address){
                SM2 = 0;
                rxf++;
            }
            break;
        case 1:
            if(x == 0x0d){
                rxf++;
            }else{
                SM2 = 1;
                rxf--;
            }
            break;
        case 2:
            if(isr_receive_ok){
                SM2 = 1;
                rxf = 0;
            }else{
                Rxdata2[2] = x;
                rxf++;
            }
            break;
        case 3:
            if(!x){
                isr_receive_ok = 1;
            }else{
                Rxdata2[3] = x;
                rxn = 0;
                rxf++;
            }
            break;
        case 4:
            Rxdata2[4+rxn] = x;
            if(++rxn >= Rxdata2[3]){
                SM2 = 1;
                rxf = 0;
                isr_receive_ok = 1;
            }
            break;

        default:
        case 5:
            TX_EN = 0;
            SM2 = 1;
            rxf = 0;
            break;
        }
    }

//---------------------------------------
// 应答当前正在执行的命令
    if(isr_receive_ok){
        SM2 = 1;
        rxf = 0;

        if(Rxdata2[2] == ACK_CMD){
            ack_buffer[0] = 0x11;
            ack_buffer[1] = 0x0d;
            ack_buffer[2] = Rxdata[2];
            ack_buffer[3] = 2;
            ack_buffer[4] = receive_ok;
            ack_buffer[5] = address;
//          ack_buffer[6] = receive_error;
            TX_EN = 1;
            txx = 0; txy = 6;
            TI = 1;
            isr_receive_ok = 0;
        }else if(receive_ok){
            isr_receive_ok = 0;
            receive_error = 1;
        }
    }
}

相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

222

主题

15446

帖子

34

粉丝