This little module allows shows how directives can be used to guide the compilation process. At the moment, it only supports setting the USARTs baudrate at compile time. Normally, you make a call to SetBaudrate() to configure the USART. However, this is a runtime call - the USART_BAUDRATE option has the advantage in that it can determine the correct BRGH value for a given baudrate at compile time. For example,

device = 18F452
Clock = 20

#option USART_BAUDRATE = 2400
Include "options.bas"
Include "usart.bas"

Write("Hello World",13,10)

If you specify an invalid USART_BAUDRATE value, and error is reported. If the module cannot calculate a valid SPBRG value, a warning is generated. It probably would be better as an error, but I just thought I would use a warning to show you how it can be done! The Swordfish preprocessor can be really useful.

I should point out that the directive code shown below could be made much shorter. However, I thought it a good idea to show a collection of techniques so the reader can get a better understanding of what can be done...

Options Module

Module Options
   The following directive block looks to see if a user has specified a
   USART_BAUDRATE #option. If they have, it first checks to see if a valid value
   has been given. If not, an error is reported. If the #option is valid, the
   SPBRG value is computed with BRGH as high. If the SPBRG value is greater
   than 255, then the SPBRG value is re-calculated with BRGH as low.
Include "usart.bas"
#option USART_BAUDRATE = 19200 // default is 19200
   #if Not (USART_BAUDRATE in (300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200))
      #error USART_BAUDRATE, "Invalid baudrate!"
      #define _FOSC = _clock * 1000000
      #define _FMULT = 16 
      #define _BRGH = $24
      #define _SPBRG = _FOSC / (_FMULT * (USART_BAUDRATE + 1)) - 1 + 0.5

      // high speed option generates a SPBRG value that is too big, try
      // a low speed option instead...
      #if _SPBRG > 255
         #undefine _FMULT
         #undefine _SPBRG
         #undefine _BRGH 
         #define _FMULT = 64
         #define _BRGH = $20
         #define _SPBRG = _FOSC / (_FMULT * (USART_BAUDRATE + 1)) - 1 + 0.5

      // cannot calculate from given clock and baudrate...
      #if _SPBRG > 255
         #warning USART_BAUDRATE, "Unable to calculate valid SPBRG value from given clock and baudrate"

      // bring defines into module code...
      Const SPBRGConst As Byte = _SPBRG          
      Const BRGHConst As Byte = _BRGH

// if a user has give a valid USART_BAUDRATE option, generate
// configuration code...
#ifdef _SPBRG
SPBRGRegister = SPBRGConst // Baudrate
TXStatus = BRGHConst       // high or low speed
RCStatus = $90             // serial port enable, continuous receive
RCInput = true             // receive pin is input
TXInput = false            // transmit pin is output