#include <REG51KJ.h> #include <stdlib.h> void serial_init() { TMOD = 0x20; //set timer 1 mode to 8-bit-auto-reload SCON = 0x50; //enable reception , det serial port mode to 8-bit UART REN ENABLE PCON |= 0x80; //set mode 2 by seting SMOD TH1 = 0xF3; //set baudrate to 9600 at 24 MHZ crystal TL1 = 0xF3; TR1 = 1; //start Timer } void delay(unsigned int msec)//delay { int i,j; for(i=0;i<msec;i++); for(j=0;j<1275;j++); } void serial_send(unsigned char dat) { while(!TI); //wait for data to be send completely TI = 0; //clr Transmit interrupt flag SBUF = dat; //move data to send in SBUF } /********************************************/ void main(void) { serial_init() ; for(;;) { delay(10); serial_send('A'); //send char 'A' through rs232 across } }
You may get away with it in this case, as it's not used as a critical timing function, but you should really not mislead novices into repeating this all-too-common-mistake.
www.8052.com/.../162556
See also: www.8052.com/.../182535
Even if you had written it in assembler, where the delay could be known, it would depend on the chip used (12-clocker, 6-clocker, etc) and clock frequency - so thry must be clearly documented.
The delay is probably not delaying as much as you'd expect anyway.
void delay(unsigned int msec)//delay { int i,j; for(i=0;i<msec;i++); <<< !!! for(j=0;j<1275;j++); }
I would imagine you intended it to be a nested loop.
There is a reason why all delays (and baudrates etc) should always (!) be verified with an oscilloscope. Both when originally implemented, and regularly during the normal release testing.
It's always so sad to _believe_ that a delay does what the name claims, when it really doesn't.
Software loops are known to result in the wrong delay times because of the generated code. But even if assembler instructions are used, the code will break if crystal, PLL or similar are changed. And same thing affects timer-based timing.
In the end, a test plan is always required. And just about everything in the software should relate to that test plan, to make sure that assumptions really are fulfilled and the shipped product does what it claims to do.
This code has nothing specifically to do with Hyperterminal; so be sure to make it clear that Hyperterminal is just an example - not a particular requirement.
serial_send('A'); //send char 'A' through rs232 across
Similarly, this has nothing specifically to do with RS232 - that depends on external hardware, and has nothing to do with the code.
it will get to a point and loop forever
Erik
Yes, the original description is a bit misleading: it doesn't just send the letter 'A' once; it sends it continuously - for ever!
TI not set at first entry here
while(!TI); //wait for data to be send completely
by the way would looping forever doing nothing be fornever?
Oh yes - I missed that!