comsend.c

来自「嵌入式开发 嵌入式开发 嵌入式开发」· C语言 代码 · 共 126 行

C
126
字号
#include <stdio.h>
#include <dos.h> 
#include <process.h> 
#include <bios.h> 
#include <ctype.h> 
#include <stdlib.h> 
#include <string.h> 
#include <alloc.h> 
#include <conio.h>
#include <mem.h>
#define UC unsigned char
#define UI unsigned int
#define ID 4
static unsigned long arUL[10]={
    1800,
    2400,
    4800,
    7200,
    9600,
    14400,
    19200,
    38400,
    57600,
    115200
};//波特率可选值大小
#define PORTBASE 0x03f8       //COM1口
#define   RXD   0            //接收缓冲器
#define   TXD   0            //发送缓冲器
#define   LSB   0            //除法因子寄存器(低位)(DLAB=0)
#define   MSB   1            //除法因子寄存器(高位)(DLAB=0)
#define   IER   1            //中断寄存器(设置中断)
#define   IIR   2            //中断状态寄存器(查询中断状态)
#define   LCR   3            //控制解调寄存器(设置DLAB)
#define   MCR   4            //
#define   LSR   5            //线控制寄存器(线状态查询)
#define   MSR   6            //

typedef struct {
    unsigned id;
    unsigned char rtr; //remote transmition request (RTR)
    unsigned char dlen;
    unsigned char data[8];
} MSG_STRUCT;
void Open_COM1(void)
{
    UC data,rd1,rd2;
    UI Record;
 
    Record=(UI)(115200/arUL[ID]);
    rd1=(UC)((Record>>8)&0xff);
    rd2=(UC)(Record&0xff);

    outportb(PORTBASE+LCR,0x80);//Dlab为1
    outportb(PORTBASE+1,rd1);//rd1除法因子寄存器最低有效数据
    outportb(PORTBASE,rd2);//rd2最高有效数据
    outportb(PORTBASE+IER,0x00);//不产生中断,采用查询方式
    outportb(PORTBASE+LCR,0x03);
    outportb(PORTBASE+4, 0x0B);
    outportb(PORTBASE+1, 0x01);
}

void Close_COM1(void)//关闭COM1端口
{
    UC B;
    disable();
    outportb(PORTBASE+IER, 0x00);
    outportb(PORTBASE+MCR, 0x00);
    B=inportb(0x21)|0x10;
    outportb(0x21, B);
    enable();
}
 
//unsigned char Buffer[8]={0};
void ComSend(MSG_STRUCT *msg,unsigned char length)
{
    unsigned char jcount,iVAL;
  
    while(  inportb(PORTBASE+LSR)&0x20  )
    {
         outportb(PORTBASE,(msg->id>>6)&0x1f ); 
    }
         
    delay(2);
    while(  inportb(PORTBASE+LSR)&0x20  )
    {
         outportb(PORTBASE,length );
    }
    delay(2); 
    for( jcount=0; jcount<length; )
    {
        while( inportb(PORTBASE+LSR)&0x20 )
        {
            outportb(PORTBASE,msg->data[jcount++] );  
        }
        delay(2);
    }
    while(  inportb(PORTBASE+LSR)&0x20  )
    {
         outportb(PORTBASE,0xff ); 
    }
    delay(2);
}

/*void main(void)
{
    unsigned char jcount=0,iVAL;
    unsigned char Buffer[3];
    Open_COM1();
    while( !kbhit() )
    {
        Buffer[0]=0xff;
        Buffer[1]=++jcount;
        Buffer[2]=0xee;
        for( iVAL=0; iVAL<3; )
        {
             if( inportb(PORTBASE+LSR)&0x20 )
             {
                outportb(PORTBASE,Buffer[iVAL++] );
             }
        }
        if( jcount==0xff) 
        jcount=0;
    }
    Close_COM1();
} */
    

⌨️ 快捷键说明

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