Shared Variables
Shared variables are standard Global variables that can share their name and type, so they occupy the same RAM positions as other Shared variables with the same name and same type. This allows Global variables to be created within multiple procedures that may use them, but the Global variables will not be created unless the procedure is called from within a program, and they will not give an error message about 'duplicate variables created'.
Shared variables are also created using the Dim directive, but the text ‘Shared’ must follow it.
The format for creating a Global Shared variable within a procedure is as follows: -
Global Dim Name as Type Shared
If a Shared variable is created outside of a procedure, the syntax is:
Dim Name as Type Shared
Where, Name is any valid identifier, (excluding keywords). Type is Bit, Pin, Byte, Word, Dword, SByte, SWord, SDword, Float, String or Arrays . Some examples of creating Shared variables are: -
Dim tCat as Bit Shared ' Create a single bit shared variable
Dim bDog as Byte Shared ' Create an 8-bit unsigned shared variable
Dim MyPin as Pin Shared ' Create a shared Port.Pin mask variable
Dim wRat as Word Shared ' Create a 16-bit unsigned shared variable
Dim dRat as Dword Shared ' Create a 32-bit unsigned shared variable
Dim fBoat as Float Shared ' Create a Floating Point shared variable
Dim sbDog as SByte Shared ' Create an 8-bit signed shared variable
Dim swRat as SWord Shared ' Create a 16-bit signed shared variable
Dim sdLrg_Rat as SDword Shared ' Create a 32-bit signed shared variable
Dim bDog[10] as Byte Shared ' Create an 8-bit unsigned shared array
Dim wRatAr[10] as Word Shared ' Create a 16-bit unsigned shared array
Dim dRatAr[10] as Dword Shared ' Create a 32-bit unsigned shared array
Dim fBoatAr[10] as Float Shared ' Create a 32-bit Floating Point shared array
Dim MyString as String * 10 Shared ' Create a shared String variable
For example:
Device = 24FJ64GA002 ' Select the device to compile for
Declare Xtal = 16 ' Tell the compiler the device will be operating at 16MHz
Declare Hserial_Baud = 9600 ' Set the Baud rate for HRsout
Declare Hrsout1_Pin = PORTB.14 ' Select the pin for TX with USART1
RPOR7 = 3 ' Make PPS Pin RP14 U1TX
Dim MyDword as Word Shared = 10 ' Create another Shared Dword variable
Do ' Create a loop
MyDword = TestProc() ' Call the procedure and load its result into MyDword
HRsoutLn Dec MyDword ' Transmit the result to a serial terminal
DelayMs 512 ' A delay so the terminal is not flooded with values
Loop ' Do it forever
Proc TestProc()
Global Dim MyDword as Dword Shared ' Create a Global Shared variable
MyDword = MyDword + 1 ' Increment the variable MyDword
EndProc
A Shared variable must be the same type as the other Shared variables using the same name. String variables and arrays must be the same type and also contain the same amount of elements.
