Options

SwordfishUser.Options History

Show minor edits - Show changes to output

Added lines 1-68:
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,

=code [=
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...
!!!Options Module
=code [=
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
#if IsOption(USART_BAUDRATE)
  #if Not (USART_BAUDRATE in (300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200))
      #error USART_BAUDRATE, "Invalid baudrate!"
  #else
      #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
      #endif 
     
      // cannot calculate from given clock and baudrate...
      #if _SPBRG > 255
        #warning USART_BAUDRATE, "Unable to calculate valid SPBRG value from given clock and baudrate"
      #endif 
     
      // bring defines into module code...
      Const SPBRGConst As Byte = _SPBRG         
      Const BRGHConst As Byte = _BRGH
  #endif 
#endif

// 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
#endif
=]