STC89C52RC MCU realizes serial port printing function
[Copy link]
This post was last edited by nettui on 2019-4-17 21:24 The 89c52rc model development board of stc has a crystal oscillator of 12m. This is because the minimum system I bought has this frequency. Using the baud rate of 9600, setting TL and TH to 0xfd will result in garbled characters in both English and Chinese. The baud rate of the 12M crystal oscillator can only be 2400. In the case of 9600, there will be a 7.8% error, so garbled characters will be generated, while in the case of 2400 baud rate, the error is 0.16%, so no garbled characters will be generated. Why are TH1 and TL1 both set to F3? 51 The crystal oscillator of the microcontroller generally uses 11.0592? The reason for using the 11.0592 crystal oscillator is due to the timer of the 51 microcontroller. When using the timer of the 51 microcontroller as a baud rate generator, if a 11.0592Mhz crystal oscillator is used, the value that needs to be set by the timer according to the formula is an integer; if a 12Mhz crystal oscillator is used, the baud rate will be biased, for example, 9600, the timer takes 0XFD, the actual baud rate is 10000, and the general baud rate deviation is about 4%, so STC90C516 can also be used. The crystal oscillator is 12M and the baud rate is 9600. The error rate is 6.99% when it is a multiple, and 8.51% when it is not a multiple. The data will definitely be wrong. This is why everyone likes to use 11.0592MHz crystal oscillator for serial communication. When the baud rate is doubled, the maximum can reach 57600, and the error rate is 0.00%. 小平头技术问答 Using 12MHz, the maximum is only 4800, and there is a 0.16% error rate, but it is within the allowable range, so it doesn't have much impact. - #include<reg51.h> //stdio.h, string.h are used for printf function prototype #include<stdio.h>
- void delay(unsigned int z); void uart_init(void);//Serial port initialization int main(void) { int a=99; char *string="abde"; uart_init(); while(1) { puts("abcd"); printf("%d %x %c %s %p ",a,a,(char)a,string,string); delay(1000); } return 0; } void uart_init(void) { TMOD=0x20;//That is 0010 0000, timer/counter 1, working mode 2 TH1=0xf3;//Set the baud rate to 9600 TL1=0xf3; TR1=1;//Start timer/counter 1 SCON=0x50; //0101 0000. Serial port working mode 1, serial control allowed PCON=0x00;//Set SMOD=0 IE=0x90; //CPU allows interrupts, serial allows interrupts TI=1; //This sentence must be added to send when using printf directly} void delay(unsigned int z) { unsigned int x,y; for(x=z;x>0;x--) for(y=110;y>0;y--); }
复制代码
|