The MICROPROCESSOR PRINCIPLES AND APPLICATIONS Lab 7 Timer, USART Cheng-Chien Su 蘇正建 Home Automation, Networking, and Entertainment Lab Dept. of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
Outline Timer0 Introduction & Operation Timer1 Introduction & Operation C18 C Libraries of Timer USART Introduction & Operation C18 C Libraries of USART Lab Reference National Cheng Kung University, TAIWAN 2
Timer0 Introduction The Timer0 module incorporates the following features: Software selectable operation as a timer or counter in both 8-bit or 16-bit modes Readable and writable registers Dedicated 8-bit, software programmable prescaler Selectable clock source (internal or external) Edge select for external clock Interrupt-on-overflow National Cheng Kung University, TAIWAN 3
Timer0 Introduction Block Diagram The T0CON register controls all aspects of the module s operation, including the prescale selection. It is both readable and writable. A simplified block diagram of the Timer0 module in 8-bit mode is shown in figure. National Cheng Kung University, TAIWAN 4
Timer0 Introduction T0CON Register National Cheng Kung University, TAIWAN 5
Timer0 Introduction Prescaler An 8-bit counter is available as a prescaler for the Timer0 module. Its value is set by the PSA and T0PS2:T0PS0 bits (T0CON<3:0>) which determine the prescaler assignment and prescale ratio. Clearing the PSA bit assigns the prescaler to the Timer0 module. When it is assigned, prescale values from 1:2 through 1:256 in power-of-2 increments are selectable. National Cheng Kung University, TAIWAN 6
Timer0 Operation Timer0 can operate as either a timer or a counter; the mode is selected with the T0CS bit (T0CON<5>). In Timer mode (T0CS = 0), the module increments on every clock by default unless a different prescaler value is selected. The user can work around this by writing an adjusted value to the TMR0 register. The Counter mode is selected by setting the T0CS bit (= 1). In this mode, Timer0 increments either on every rising or falling edge of pin RA4/T0CKI. The incrementing edge is determined by the Timer0 Source Edge Select bit, T0SE (T0CON<4>); clearing this bit selects the rising edge. National Cheng Kung University, TAIWAN 7
Timer0 Operation Interrupt The TMR0 interrupt is generated when the TMR0 register overflows from FFh to 00h in 8-bit mode, or from FFFFh to 0000h in 16-bit mode. This overflow sets the TMR0IF flag bit. The interrupt can be masked by clearing the TMR0IE bit (INTCON<5>). Before re-enabling the interrupt, the TMR0IF bit must be cleared in software by the Interrupt Service Routine. Since Timer0 is shut down in Sleep mode, the TMR0 interrupt cannot awaken the processor from Sleep. National Cheng Kung University, TAIWAN 8
Timer1 Introduction The Timer1 timer/counter module incorporates these features: Software selectable operation as a 16-bit timer or counter Readable and writable 8-bit registers (TMR1H and TMR1L) selectable clock source (internal or external) with device clock or Timer1 oscillator internal options Interrupt-on-overflow Reset on CCP Special Event Trigger Device clock status flag (T1RUN) National Cheng Kung University, TAIWAN 9
Timer1 Introduction Block Diagram National Cheng Kung University, TAIWAN 10
Timer1 Introduction T1CON Register National Cheng Kung University, TAIWAN 11
C18 C Libraries of Timerx Overall Timer Functions: the timer peripherals are supported with the following functions: CloseTimerx OpenTimerx ReadTimerx WriteTimerx National Cheng Kung University, TAIWAN 12
C18 C Libraries of Timer OpenTimer0 OpenTimer0: Configure and enable timer0. Include: timers.h Prototype: void OpenTimer0( unsigned char config ); Arguments: config Enable Timer0 Interrupt: TIMER_INT_ON Interrupt enabled TIMER_INT_OFF Interrupt disabled Timer Width: T0_8BIT 8-bit mode T0_16BIT 16-bit mode Clock Source: T0_SOURCE_EXT External clock source (I/O pin) T0_SOURCE_INT Internal clock source (TOSC) External Clock Trigger (for T0_SOURCE_EXT): T0_EDGE_FALL External clock on falling edge T0_EDGE_RISE External clock on rising edge Prescale Value: T0_PS_1_1 1:1 prescale T0_PS_1_2 1:2 prescale T0_PS_1_256 1:256 prescale Remarks: This function configures timer0 according to the options specified and then enables it. Code Example: OpenTimer0( TIMER_INT_OFF & T0_8BIT & T0_SOURCE_INT & T0_PS_1_32 ); National Cheng Kung University, TAIWAN 13
C18 C Libraries of Timer OpenTimer1 OpenTimer1: Configure and enable timer1. Include: timers.h Prototype: void OpenTimer1( unsigned char config ); Arguments: config Enable Timer1 Interrupt: TIMER_INT_ON Interrupt enabled TIMER_INT_OFF Interrupt disabled Timer Width: T1_8BIT_RW 8-bit mode T1_16BIT_RW 16-bit mode Clock Source: T1_SOURCE_EXT External clock source (I/O pin) T1_SOURCE_INT Internal clock source (TOSC) Prescaler: T1_PS_1_1 1:1 prescale T1_PS_1_2 1:2 prescale T1_PS_1_4 1:4 prescale T1_PS_1_8 1:8 prescale Oscillator Use: T1_OSC1EN_ON Enable Timer1 oscillator T1_OSC1EN_OFF Disable Timer1 oscillator Synchronize Clock Input: T1_SYNC_EXT_ON Sync external clock input T1_SYNC_EXT_OFF Don t sync external clock input Remarks: This function configures timer1 according to the options specified and then enables it. Code Example: OpenTimer1( TIMER_INT_ON & T1_8BIT_RW & T1_SOURCE_EXT & T1_PS_1_1 & T1_OSC1EN_OFF & T1_SYNC_EXT_OFF ); National Cheng Kung University, TAIWAN 14
C18 C Libraries of Timer WriteTimer0 WriteTimer0: Write a value into the specified timer. Include: timers.h Prototype: void WriteTimer0( unsigned int timer ); Arguments: timer The value that will be loaded into the specified timer. Remarks: These functions write a value to the respective timer register(s):tmr0l,tmr0h Code Example: WriteTimer0( 10000 ); National Cheng Kung University, TAIWAN 15
C18 C Libraries of Timer ReadTimer0 ReadTimer0: Read the value of the specified timer. Include: timers.h Prototype: unsigned int ReadTimer0( void ); Remarks: These functions read the value of the respective timer register(s): TMR0L,TMR0H Return Value: The current value of the timer. Note: When using a timer in 8-bit mode that may be configured in 16-bit mode (e.g., timer0), the upper byte is not ensured to be zero. The user may wish to cast the result to a char for correct results. Code Example: unsigned int result; result = (unsigned char) ReadTimer0(); National Cheng Kung University, TAIWAN 16
C18 C Libraries of Timer CloseTimer0 CloseTimer0: Disable the specified timer. Include: timers.h Prototype: void CloseTimer0( void ); Remarks: This function disables the interrupt and the specified timer. National Cheng Kung University, TAIWAN 17
C18 C Libraries of Timer Example #include <p18c4520.h> #include <timers.h> #include <stdlib.h> void main( void ){ int result; char str[7]; // configure timer0 OpenTimer0( TIMER_INT_OFF & T0_SOURCE_INT & T0_PS_1_32 ); TRISD = 0; while( 1 ) { while(! PORTBbits.RB3 ); result = ReadTimer0(); if( result > 0xc000 ) break; WriteTimer0( 0 ); // wait for RB3 high // read timer // exit loop if value // is out of range // restart timer } PORTD = (unsinged char) result; } CloseTimer0(); // close modules National Cheng Kung University, TAIWAN 18
USART Introduction The Enhanced Universal Synchronous Asynchronous Receiver Transmitter (USART) module is one of the two serial I/O modules. The USART can be configured A full-duplex asynchronous system, such as personal computers, etc. A half-duplex, synchronous system, such as serial EEPROMs, etc. The Enhanced USART module implements additional features: automatic baud rate detection and calibration automatic wake-up on Sync Break reception 12-bit Break character transmit. National Cheng Kung University, TAIWAN 19
USART Introduction (cont ) The USART can be configured in the following modes: Asynchronous (full duplex) with: Auto-wake-up on character reception Auto-baud calibration 12-bit Break character transmission Synchronous Master (half duplex) with selectable clock polarity Synchronous Slave (half duplex) with selectable clock polarity National Cheng Kung University, TAIWAN 20
USART Introduction (cont ) The pins of the Enhanced USART are multiplexed with PORTC. In order to configure RC6/TX/CK and RC7/RX/DT as an USART: bit SPEN (RCSTA<7>) must be set (= 1) bit TRISC<7> must be set (= 1) bit TRISC<6> must be set (= 1) The operation of the Enhanced USART module is controlled through three registers: Transmit Status and Control (TXSTA) Receive Status and Control (RCSTA) Baud Rate Control (BAUDCON) National Cheng Kung University, TAIWAN 21
Registers of USART TXSTA Register National Cheng Kung University, TAIWAN 22
Registers of USART RCSTA Register National Cheng Kung University, TAIWAN 23
Registers of USART BAUDCON Register National Cheng Kung University, TAIWAN 24
USART Operation Baud Rate Generator (BRG) The BRG is a dedicated, 8-bit or 16-bit generator that supports both the Asynchronous and Synchronous modes of the USART. By default, the BRG operates in 8-bit mode; setting the BRG16 bit (BAUDCON<3>) selects 16-bit mode. The SPBRGH:SPBRG register pair controls the period of a free-running timer. In Asynchronous mode, bits, BRGH (TXSTA<2>) and BRG16 (BAUDCON<3>), also control the baud rate. In Synchronous mode, BRGH is ignored. National Cheng Kung University, TAIWAN 25
USART Operation Baud Rate Generator (BRG) Example Lookup table Baud Rate Formula National Cheng Kung University, TAIWAN 26
USART Operation Asynchronous Mode The Asynchronous mode of operation is selected by clearing the SYNC bit (TXSTA<4>). In this mode, the USART uses standard Non- Return-to-Zero (NRZ) format (one Start bit, eight or nine data bits and one Stop bit). The USART transmits and receives the LSB first. The USART s transmitter and receiver are functionally independent but use the same data format and baud rate. Parity is not supported by the hardware but can be implemented in software and stored as the 9th data bit. National Cheng Kung University, TAIWAN 27
USART Operation Asynchronous Transmitter USART Asynchronous Transmitter The heart of the transmitter is the Transmit (Serial) Shift Register (TSR). The Shift register obtains its data from the Read/Write Transmit Buffer register, TXREG. The TXREG register is loaded with data in software. The TSR register is not loaded until the Stop bit has been transmitted from the previous load. As soon as the Stop bit is transmitted, the TSR is loaded with new data from the TXREG register (if available). National Cheng Kung University, TAIWAN 28
USART Operation Asynchronous Transmitter This interrupt can be enabled or disabled by setting or clearing the interrupt enable bit, TXIE (PIE1<4>). TRMT is a read-only bit which is set when the TSR register is empty. National Cheng Kung University, TAIWAN 29
USART Operation Asynchronous Transmitter To set up an Asynchronous Transmission: 1. Initialize the SPBRGH:SPBRG registers for the appropriate baud rate. Set or clear the BRGH and BRG16 bits, as required, to achieve the desired baud rate. 2. Enable the asynchronous serial port, SYNC=0 and SPEN=1. 3. If interrupts are desired, TXIE=1. 4. If 9-bit transmission is desired, TX9=1. 5. Enable the transmission by setting bit, TXEN, which will also set bit, TXIF. 6. If 9-bit transmission is selected, the ninth bit should be loaded in bit, TX9D. 7. Load data to the TXREG register (starts transmission). 8. If using interrupts, ensure that the GIE and PEIE bits in the INTCON register (INTCON<7:6>) are set. National Cheng Kung University, TAIWAN 30
USART Operation Asynchronous Receiver USART Asynchronous Receiver The data is received on the RX pin and drives the data recovery block. The data recovery block is actually a high-speed shifter operating at x16 times the baud rate, whereas the main receive serial shifter operates at the bit rate or at FOSC. This mode would typically be used in RS-232 systems. National Cheng Kung University, TAIWAN 31
USART Operation Asynchronous Receiver To set up an Asynchronous Reception: 1. Initialize the SPBRGH:SPBRG registers for the appropriate baud rate. Set or clear the BRGH and BRG16 bits, as required, to achieve the desired baud rate. 2. Enable the asynchronous serial port, SYNC=0 and SPEN=1. 3. If interrupts are desired, RCIE=1. 4. If 9-bit reception is desired, RX9=1. 5. Enable the reception by CREN=1. 6. Flag bit, RCIF, will be set when reception is complete and an interrupt will be generated if enable bit, RCIE, was set. 7. Read the RCSTA register to get the 9th bit (if enabled) and determine if any error occurred during reception. 8. Read the 8-bit received data by reading the RCREG register. 9. If any error occurred, clear the error by clearing enable bit, CREN. 10.If using interrupts, ensure that the GIE and PEIE bits in the INTCON register (INTCON<7:6>) are set. National Cheng Kung University, TAIWAN 32
C18 Libraries of USART Overall USART Functions: The following routines are provided for devices with a single USART peripheral: National Cheng Kung University, TAIWAN 33
C18 Libraries of USART OpenUSART OpenUSART: Configure the specified USART module. Include: usart.h Prototype: void OpenUSART( unsigned char config, unsigned int spbrg); Arguments: config Interrupt on Transmission: USART_TX_INT_ON Transmit interrupt ON USART_TX_INT_OFF Transmit interrupt OFF Interrupt on Receipt: USART_RX_INT_ON Receive interrupt ON USART_RX_INT_OFF Receive interrupt OFF USART Mode: USART_ASYNCH_MODE Asynchronous Mode USART_SYNCH_MODE Synchronous Mode Transmission Width: USART_EIGHT_BIT 8-bit transmit/receive USART_NINE_BIT 9-bit transmit/receive Slave/Master Select*: USART_SYNC_SLAVE Synchronous Slave mode USART_SYNC_MASTER Synchronous Master mode Reception mode: USART_SINGLE_RX Single reception USART_CONT_RX Continuous reception Baud rate: USART_BRGH_HIGH High baud rate USART_BRGH_LOW Low baud rate National Cheng Kung University, TAIWAN 34
C18 Libraries of USART OpenUSART (cont ) Arguments: spbrg This is the value that is written to the baud rate generator register which determines the baud rate at which the USART operates. The formulas for baud rate are: Asynchronous mode, high speed: FOSC / (16 * (spbrg + 1)) Asynchronous mode, low speed: FOSC / (64 * (spbrg + 1)) Synchronous mode: FOSC / (4 * (spbrg + 1)) Where FOSC is the oscillator frequency. Remarks: This function configures the USART module according to the specified configuration options. Code Example: OpenUSART1( USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_HIGH, 25); National Cheng Kung University, TAIWAN 35
C18 Libraries of USART baudusart baudusart: Set the baud rate configuration bits for enhanced USART operation. Include: usart.h Prototype: void baudusart( unsigned char baudconfig ); Arguments: baudconfig Clock Idle State: BAUD_IDLE_CLK_HIGH Clock idle state is a high level BAUD_IDLE_CLK_LOW Clock idle state is a low level Baud Rate Generation: BAUD_16_BIT_RATE 16-bit baud generation rate BAUD_8_BIT_RATE 8-bit baud generation rate RX Pin Monitoring: BAUD_WAKEUP_ON RX pin monitored BAUD_WAKEUP_OFF RX pin not monitored Baud Rate Measurement: BAUD_AUTO_ON Auto baud rate measurement enabled BAUD_AUTO_OFF Auto baud rate measurement disabled Remarks: These functions are only available for processors with enhanced USART capability. Code Example: baudusart (BAUD_IDLE_CLK_HIGH & BAUD_16_BIT_RATE & BAUD_WAKEUP_ON & BAUD_AUTO_ON); National Cheng Kung University, TAIWAN 36
C18 Libraries of USART BusyUSART BusyUSART: Is the USART transmitting? Include: usart.h Prototype: char BusyUSART( void ); Remarks: Returns a value indicating if the USART transmitter is currently busy. This function should be used prior to commencing a new transmission. BusyUSART should be used on parts with a single USART peripheral. Return Value: 0 if the USART transmitter is idle 1 if the USART transmitter is in use Code Example: while (BusyUSART()); National Cheng Kung University, TAIWAN 37
C18 Libraries of USART WritUSART putcusart WritUSART / putcusart: Write a byte (one character) to the USART transmit buffer, including the 9th bit if enabled. Include: usart.h Prototype: void WritUSART( char data ); void putcusart( char data ); Arguments: data The value to be written to the USART. Remarks: This function writes a byte to the USART transmit buffer. If 9-bit mode is enabled, the 9th bit is written from the field TX_NINE, found in a variable of type USART. Code Example: unsigned int outval; USART_Status.TX_NINE = (outval & 0x0100) >> 8; Write1USART( (char) outval ); National Cheng Kung University, TAIWAN 38
C18 Libraries of USART putsusart putrsusart putsusart and putrsusart: Writes a string of characters to the USART including the null character. Include: usart.h Prototype: void putsusart( char *data ); void putrsusart( const rom char *data ); Arguments: data Pointer to a null-terminated string of data. Remarks: This function only works in 8-bit transmit/receive mode. This function writes a string of data to the USART including the null character. Strings located in data memory should be used with the puts versions of these functions. Strings located in program memory, including string literals, should be used with the putrs versions of these functions. Code Example: putrsusart( Hello World! ); National Cheng Kung University, TAIWAN 39
C18 Libraries of USART DataRdyUSART DataRdyUSART: Is data available in the read buffer? Include: usart.h Prototype: char DataRdyUSART( void ); Remarks: This function returns the status of the RCIF flag bit in the PIR register. Return Value: 1 if data is available 0 if data is not available Code Example: while (!DataRdyUSART()); National Cheng Kung University, TAIWAN 40
C18 Libraries of USART ReadUSART getcusart ReadUSART / getcusart : Read a byte (one character) out of the USART receive buffer, including the 9th bit if enabled. Include: usart.h Prototype: char ReadUSART( void ); char getcusart(void ); Remarks: This function reads a byte out of the USART receive buffer. The Status bits and the 9th data bits are saved in a union with the following declaration: union USART { unsigned char val; struct { unsigned RX_NINE:1; unsigned TX_NINE:1; unsigned FRAME_ERROR:1; unsigned OVERRUN_ERROR:1; unsigned fill:4; }; }; The 9th bit is read-only if 9-bit mode is enabled. The Status bits are always read. Return Value: This function returns the next character in the USART receive buffer. Code Example: int result; result = ReadUSART(); result = (unsigned int) USART_Status.RX_NINE << 8; National Cheng Kung University, TAIWAN 41
C18 Libraries of USART getsusart getsusart: Read a fixed-length string of characters from the specified USART. Include: usart.h Prototype: void getsusart ( char * buffer, unsigned char len ); Arguments: buffer A pointer to the location where incoming characters are to be stored. Arguments: len The number of characters to read from the USART. Remarks: This function only works in 8-bit transmit/receive mode. This function waits for and reads len number of characters out of the specified USART. There is no time out when waiting for characters to arrive. Code Example: char inputstr[10]; getsusart( inputstr, 5 ); National Cheng Kung University, TAIWAN 42
C18 Libraries of USART ClosUSART ClosUSART: Disable the specified USART. Include: usart.h Prototype: void ClosUSART( void ); Remarks: This function disables the interrupts, transmitter and receiver for the specified USART. National Cheng Kung University, TAIWAN 43
C18 Libraries of USART Example #include <p18c4520.h> #include <usart.h> void main(void){ // configure USART OpenUSART( USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_HIGH, 25 ); while(1) { while(! PORTAbits.RA0 ); //wait for RA0 high WritUSART( PORTD ); //write value of PORTD if(portd == 0x80) //check for termination break; //value } ClosUSART(); } National Cheng Kung University, TAIWAN 44
Reference 1) PIC18F4520 Data Sheet 2) MPLAB C18 (v3.00) C Compiler Getting Started 3) MPLAB C18 (v3.00) C Compiler User's Guide 4) MPLAB C18 C Compiler Libraries 5) Applying PIC18 Microcontrollers: Architecture, Programming, and Interfacing using C and Assembly (Hardcover) by Barry B. Brey (Author) 6) PIC Microcontroller: An Introduction to Software & Hardware Interfacing (Hardcover) by Han-Way Huang (Author) 7) http://www.microchip.com/ National Cheng Kung University, TAIWAN 45
Ex Ex 7-1 設計一個 0.5 秒讓 PORTD 的 LED 所顯示的二進位數字自動加一的程式 National Cheng Kung University, TAIWAN 46
Ex Ex 7-2 設計一個 0.5 秒讓 PORTD 的 LED 所顯示的二進位數字自動加一的程式並使微處理器進入睡眠模式以節省電能 National Cheng Kung University, TAIWAN 47
Ex 7-3 Ex 設計一個程式, 回傳你在鍵盤打的字元 RATE : 38400 Baud Rate Asynchronous mode, high speed: FOSC / (16 * (spbrg + 1)) 16M/16*(25+1) 38400 National Cheng Kung University, TAIWAN 48
National Cheng Kung University, TAIWAN 49
National Cheng Kung University, TAIWAN 50
National Cheng Kung University, TAIWAN 51
National Cheng Kung University, TAIWAN 52