关于pic单片机串口初始化,有一段代码,求大神解释啊
时间:10-02
整理:3721RD
点击:
- void serial_setup(void)
- {
- /* relates crystal freq to baud rate - see above and PIC16F87x data sheet under 'USART async. modes'
- BRGH=1, Fosc=3.6864MHz BRGH=1, Fosc=4MHz BRGH=1, Fosc=8MHz BRGH=1, Fosc=16MHz
- ---------------------- ----------------- ----------------- ------------------
- Baud SPBRG Baud SPBRG Baud SPBRG Baud SPBRG
- 1200 191 1200 207.3 1200 415.7 9600 103
- 2400 95 2400 103.2 2400 207.3 19200 51
- 4800 47 4800 51.1 4800 103.2 38400 25
- 9600 23 9600 25.0 9600 51.1 57600 16
- 19200 11 19200 12.0 19200 25.0 115200 8
- 38400 5 38400 5.5 38400 12.0
- 57600 3 57600 3.3 57600 7.7
- 115200 1 115200 1.2 115200 3.3
- */
- /*
- * Comms setup:
- */
- #define BAUD 19200
- #define divIDER ((PIC_CLK/(16UL * BAUD) -1))
- #define HIGH_SPEED 1
- //you can comment these #assert statements out if you dont want error checking
- #if PIC_CLK==3686400 && BAUD==19200
- #assert divIDER==11
- #elif PIC_CLK==4000000 && BAUD==19200
- #assert divIDER==12
- #elif PIC_CLK==16000000 && BAUD==19200
- #assert divIDER==51
- #elif PIC_CLK==20000000 && BAUD==19200
- #assert divIDER==64
- #endif
- SPBRG=divIDER;
- BRGH=HIGH_SPEED; //data rate for sending
- SYNC=0; //asynchronous
- SPEN=1; //enable serial port pins
- CREN=1; //enable reception
- SREN=0; //no effect
- TXIE=0; //disable tx interrupts
- RCIE=0; //disable rx interrupts
- TX9=0; //8-bit transmission
- RX9=0; //8-bit reception
- TXEN=0; //reset transmitter
- TXEN=1; //enable the transmitter
- }
还有那个 divIDER 宏定义
大概是如果条件成立则编译时打印出相应信息
#define divIDER ((PIC_CLK/(16UL * BAUD) -1))
这里16UL是长整形数16,BAUD 是波特率,计算分频数据的,应该跟数据手册上公式对应,时钟频率除以16倍波特率再减一