www.pudn.com > study_CIP51.rar > serial.c


#include 
#include 
 
#include"tdp.h" 
 
#define TBUF_SIZE   256		/* don't update these 2 lines */ 
#define RBUF_SIZE   256 
 
static xdata unsigned char tbuf [TBUF_SIZE]; 
static xdata unsigned char rbuf [TBUF_SIZE]; 
static xdata unsigned char t_in = 0; 
static xdata unsigned char t_out = 0; 
static xdata unsigned char t_disabled = 0; 
static xdata unsigned char r_in = 0; 
static xdata unsigned char r_out = 0; 
 
/* Com spot Int Service func.*/ 
static void com_isr(void) interrupt 4 using 2 { 
	if(RI != 0 ) {		/*Receiv processing */ 
		RI = 0; 
		if ((r_in + 1 ) != r_out) 
			rbuf[r_in++] =SBUF; 
	} 
 
	if(TI != 0) {		/* transm. processing */ 
		TI = 0; 
		if(t_in != t_out) 
			SBUF = tbuf[t_out++]; 
		else 
			t_disabled = 1; 
	} 
} 
 
/* com init.*/ 
void com_initialize(void) { 
	com_baudrate(67500);	 
	INT_DISABLE; 
	t_in = 0;		/* clr com's buff */ 
	t_out = 0; 
	t_disabled = 1; 
	r_in = 0; 
	r_out = 0; 
	SM0 = 0; SM1 = 1;	/* set com type -- type 1 */ 
	SM2 = 0; 
	REN = 1;			/*rev allowed */ 
	TI = 0;				/*clr com int flag */ 
	RI = 0; 
	ES = 1;				/* com int allowed */ 
	PS = 0;				/*set com int level */ 
	INT_ENABLE; 
} 
 
/* set buadrate */ 
void com_baudrate(unsigned baudrate) { 
	INT_DISABLE; 
	TI = 0; 
	t_in = 0; 
	t_out =0; 
	t_disabled = 1; 
	TR1 = 0; 
	ET1 = 0; 
	PCON |= 0x80; 
	TMOD &= ~0xF0; 
	TMOD |= 0x20; 
	TH1 = (unsigned char)(256 - (TCLK / (16L * 12L * baudrate))); 
	TR1 = 1; 
	INT_ENABLE; 
} 
 
/* Send char */ 
char com_putchar(unsigned char c) { 
	if((TBUF_SIZE -com_tbuflen()) <= 2) 
		return (-1); 
	INT_DISABLE; 
	tbuf[t_in++] = c; 
	if(t_disabled) { 
		t_disabled = 0; 
		TI = 1; 
	} 
	INT_ENABLE; 
	return(0); 
} 
 
char com_puts(char *s) { 
	if((TBUF_SIZE - com_tbuflen()) <= strlen(s)) 
		return(-1); 
	INT_DISABLE; 
	for (;*s != '\0'; s++) 
		tbuf[t_in++] = *s; 
	if(t_disabled) { 
		t_disabled = 0; 
		TI = 1; 
	} 
	INT_ENABLE; 
	return(0); 
} 
 
/*rev char*/ 
int com_getchar(void) { 
	xdata int c; 
	if(com_rbuflen() == 0) 
		return(-1); 
		INT_DISABLE; 
		c = rbuf[r_out++]; 
		INT_ENABLE; 
		return(0); 
} 
 
unsigned char com_rbuflen(void) {		/* calculate in buf len */ 
	return(r_in -r_out); 
} 
 
unsigned char com_tbuflen(void) {		/* calculate out buf len */ 
	return(t_in - t_out); 
}