hi, all. I am a new comer to 8051. It seems that I have problem in generating the baud rate of 19200 for serial port using timer 2. The uC is AT89C52. here is my code:
#include <at89x52.h> #include <stdio.h> void SPortISR (void) interrupt 4 { unsigned char i = 0; putchar (i); /* output character i*/ TI = 0; /* clear flag */ } void main (void){ T2CON = 0x34; /* Set T2 Mode 1 */ RCAP2H = 0xFF; RCAP2L = 0xEC; /* RCAP2 = 65516 */ TH2 = RCAP2H; TL2 = RCAP2L; SCON = 0x50; /*set serial port mode 1 */ ES = 1; /*Enable Serial Port interrupt*/ EA = 1; /*Enable Global Interrupt */ }
Hi, Stefan. Thanks for your answer. In 2, my words was misleading. I want to know whether i can use SBUF=i in C code. It is supposed to be working, but I observe nothing from the Serial Window #1 when I use it. In 3, the function should be putchar(i), sorry about the typing mistake. I think I find out the problem. The printed character in serial port is ASCII character set. Below is my code, but it doesnt work.
#include <at89x52.h> #include <stdio.h> static signed char i = 0; void SPISR (void) interrupt 4 /* serial port ISR */ { TI = 0; /* clear flag */ } void main (void) { RCAP2H = 0xFF; RCAP2L = 0xEC; /* set 18500 baud rate */ T2CON = 0x34; /* Set T2 Mode 1. SCON = 0x50; /* set serial port mode 1. */ IE = 0x90; /* Enable global & serial port interrupt */ while (1) { if(i==20) putchar(i); /* output character i, */ i++; if(i==126) i=0; } }
The default implementation of putchar() isn't intended to be used with interrupt driven serial comms. It waits for TI to be set before transmitting a character, but your ISR clears TI, so putchar() hangs. If you want to use interrupt driven serial comms with the standard library I/O functions you need to write your own versions of _getkey() and putchar(). The source for Keil's implementations is in the C51\LIB directory. By the way, putchar() translates linefeed characters (0x0a) into CRLF sequences (0x0d, 0x0a). Yes, you can use SBUF=i in C code, this is exactly what putchar() does. There is an 'interrupt driven serial comms' example somewhere on this site, I suggest you track it down and have a look. The basic difference between interrupt driven and non-interrupt driven comms is that with interrupt driven comms the RI and TI flags cause the serial ISR to be called, this will 'preempt' any code outwith the ISR that is looking at these flags. In either case you must reset the flags in software. Stefan
Hi, Stefan. Thanks for your clear and detail explanation. I am clear on transmit from Serial port, and my program is working now. I've learnt a lot from you and Kaushik B. Thanks again. ^_^
My pleasure. Stefan