Firewing Language Reference

Similar documents
Firewing Language Reference.

Swordfish Compiler Structured BASIC for PIC microcontrollers

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types

A Fast Review of C Essentials Part I

UNIT- 3 Introduction to C++

Quick Reference Guide

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Visual C# Instructor s Manual Table of Contents

Chapter 3: Operators, Expressions and Type Conversion

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Outline. Data and Operations. Data Types. Integral Types

.Net Technologies. Components of.net Framework

Review of the C Programming Language for Principles of Operating Systems

Chapter 12 Variables and Operators

Lexical Considerations

Variables and literals

Language Reference Manual simplicity

C++ Programming: From Problem Analysis to Program Design, Third Edition

Quick Reference Guide

Work relative to other classes

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

XC Specification. 1 Lexical Conventions. 1.1 Tokens. The specification given in this document describes version 1.0 of XC.

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Data Types Literals, Variables & Constants

Chapter 2: Basic Elements of C++

Tokens, Expressions and Control Structures

Fundamental of Programming (C)

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

The C++ Language. Arizona State University 1

Full file at

Maciej Sobieraj. Lecture 1

Reserved Words and Identifiers

Review of the C Programming Language

Chapter 12 Variables and Operators

reply db y prompt db Enter your favourite colour:, 0 colour db 80 dup(?) i db 20 k db? num dw 4000 large dd 50000

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Basic Types, Variables, Literals, Constants

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Objectives. In this chapter, you will:

1 Lexical Considerations

Introduce C# as Object Oriented programming language. Explain, tokens,

BLM2031 Structured Programming. Zeyneb KURT

>B<82. 2Soft ware. C Language manual. Copyright COSMIC Software 1999, 2001 All rights reserved.

VLC : Language Reference Manual

Zheng-Liang Lu Java Programming 45 / 79

Darshan Institute of Engineering & Technology for Diploma Studies

ME 461 C review Session Fall 2009 S. Keres

String Computation Program

Chapter 12 Variables and Operators

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Lexical Considerations

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

C Language Programming

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

DEPARTMENT OF MATHS, MJ COLLEGE

Variables. Data Types.

Decaf Language Reference Manual

BASIC ELEMENTS OF A COMPUTER PROGRAM

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Introduction to C# Applications

by NetMedia, Inc. All rights reserved. Basic Express, BasicX, BX-01, BX-24 and BX-35 are trademarks of NetMedia, Inc.

Introduction to Programming Using Java (98-388)

Fundamentals of Programming

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2: Using Data

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

Sprite an animation manipulation language Language Reference Manual

Fundamental of C programming. - Ompal Singh

Model Viva Questions for Programming in C lab

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

CS401 - Computer Architecture and Assembly Language Programming Glossary By

CSCI 171 Chapter Outlines

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Chapter 2 Basic Elements of C++

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

6.096 Introduction to C++ January (IAP) 2009

Introduction to AEL. Introduction to AEL. General AEL Structure. Language Specifics

CSC 1214: Object-Oriented Programming

Full file at

Structure of this course. C and C++ Past Exam Questions. Text books

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Types and Expressions. Chapter 3

ISA 563 : Fundamentals of Systems Programming

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Types, Operators and Expressions

Introduction to C Language

Object Oriented Software Design

DigiPen Institute of Technology

Programming. Elementary Concepts

Transcription:

Firewing Language Reference www.firewing.info February 12, 2013

Contents 1 Basic Concepts 1 Identifiers and Reserved Words.............................. 1 Comments.......................................... 1 Line Continuation Character............................... 1 Constants.......................................... 2 Array Constants...................................... 3 Enumerated Types..................................... 4 2 Variables 7 Variable Initialiser..................................... 8 Boolean Types....................................... 8 String and Char Types................................... 9 Arrays............................................ 11 Alias and Modifiers..................................... 13 3 Structures, Unions and User Types 17 Unions............................................ 19 User Types......................................... 20 4 Declaration Scope 23 Block Scope......................................... 23 Subroutine and Function Scope.............................. 24 Module Scope........................................ 24 5 Conditional Statements 27 The If Then Statement.................................. 27 The Select Case Statement................................ 28 Conditional Jump..................................... 29 6 Repetitive and Block Statements 31 The While End While Loop................................ 31 The Do Loop Until Loop................................. 31 The For Next Loop.................................... 32 Short Circuit Boolean Expressions............................ 33 Exit Statement....................................... 33 Continue Statement.................................... 34 With Statement....................................... 35 i

ii CONTENTS 7 Subroutines and Functions 37 Subroutine Declarations.................................. 37 Function Declarations................................... 38 Parameters......................................... 39 ByVal, ByRef and ByRefConst.............................. 40 Optional Parameters.................................... 42 Static Variables....................................... 42 Frame Recycling...................................... 43 Inline............................................ 44 Function Return Types.................................. 44 Subroutine and Function Aliasing............................. 46 Overloading......................................... 46 Compound Subroutines.................................. 48 8 Events 51 Declaring An Event.................................... 51 Raising and Event..................................... 52 Events and Interrupts................................... 52 9 Interrupts 53 Enabling and Disabling Interrupts............................ 53 Context Saving....................................... 54 10 Inbuilt Subroutines and Functions 57 AddressOf.......................................... 57 BitOf............................................ 57 UBound........................................... 58 Erase............................................ 58 DelayMS.......................................... 59 DelayUS........................................... 59 High............................................. 59 Input............................................ 60 Low............................................. 60 Output........................................... 60 Toggle............................................ 60 SizeOf............................................ 61 11 Compiler Directives 63 #constant......................................... 63 #variable.......................................... 63 #define........................................... 64 #undefine.......................................... 64 #ifdef #else #endif.................................... 64 #ifndef #else #endif................................... 64 #if #elseif #else #endif................................. 65 #error............................................ 65 #warning.......................................... 65 #option........................................... 65 Appendix H Examples SD Card Reader Want to test your SD Card? This simple program shows how to read a *.hex file from the SD card and dump to the screen using the Firewing built in 232 to USB interface. You can view the data by pressing "F4" in the Firewing IDE to open the Serial Communicator Window. Imports SD program entry point... sub Main() filename and data byte... dim filename as string = "data.hex" dim databyte as byte initialise the SD card... If SD.Init <> errok Then Console.Write("Failed to initialise",13,10) now open the file - can be on FAT16 or FAT32... elseif SD.Open(Filename) <> errok then Console.Write("Failed to open ", Filename, 13,10) now read the data... else do databyte = SD.ReadByte Console.Write(dataByte) loop Until SD.EOF SD.Close Console.Write("Finished", 13, 10) end if end sub 87

APPENDIX G. INTERRUPT HANDLER NAMES CONTENTS iii public const SPI2Interrupt as string = "SPI2Interrupt, IEC2.1" public const C1RxRdyInterrupt as string = "C1RxRdyInterrupt, IEC2.2" public const C1Interrupt as string = "C1Interrupt, IEC2.3" public const DMA3Interrupt as string = "DMA3Interrupt, IEC2.4" public const PMPInterrupt as string = "PMPInterrupt, IEC2.13" public const DMA4Interrupt as string = "DMA4Interrupt, IEC2.14" public const DMA5Interrupt as string = "DMA5Interrupt, IEC3.13" public const RTCCInterrupt as string = "RTCCInterrupt, IEC3.14" public const U1ErrInterrupt as string = "U1ErrInterrupt, IEC4.1" public const U2ErrInterrupt as string = "U2ErrInterrupt, IEC4.2" public const CRCInterrupt as string = "CRCInterrupt, IEC4.3" public const DMA6Interrupt as string = "DMA6Interrupt, IEC4.4" public const DMA7Interrupt as string = "DMA7Interrupt, IEC4.5" public const C1TxReqInterrupt as string = "C1TxReqInterrupt, IEC4.6" IsOption........................................... 66 Preprocessor Expressions................................. 66 A Operators 69 B Reserved Words 71 C Types, Modifiers and Constants 75 D Conversion Functions 77 E Type Conversions 79 F Using Embedded Assembler 83 G Interrupt Handler Names 85 H Examples 87 SD Card Reader...................................... 87 86

iv CONTENTS Appendix G Interrupt Handler Names public const OscillatorFail as string = "OscillatorFail" public const AddressError as string = "AddressError" public const StackError as string = "StackError" public const MathError as string = "MathError" public const DMACError as string = "DMACError" public const INT0Interrupt as string = "INT0Interrupt, IEC0.0" public const IC1Interrupt as string = "IC1Interrupt, IEC0.1" public const OC1Interrupt as string = "OC1Interrupt, IEC0.2" public const T1Interrupt as string = "T1Interrupt, IEC0.3" public const DMA0Interrupt as string = "DMA0Interrupt, IEC0.4" public const IC2Interrupt as string = "IC2Interrupt, IEC0.5" public const OC2Interrupt as string = "OC2Interrupt, IEC0.6" public const T2Interrupt as string = "T2Interrupt, IEC0.7" public const T3Interrupt as string = "T3Interrupt, IEC0.8" public const SPI1ErrInterrupt as string = "SPI1ErrInterrupt, IEC0.9" public const SPI1Interrupt as string = "SPI1Interrupt, IEC0.10" public const U1RXInterrupt as string = "U1RXInterrupt, IEC0.11" public const U1TXInterrupt as string = "U1TXInterrupt, IEC0.12" public const ADC1Interrupt as string = "ADC1Interrupt, IEC0.13" public const DMA1Interrupt as string = "DMA1Interrupt, IEC0.14" public const SI2C1Interrupt as string = "SI2C1Interrupt, IEC1.0" public const MI2C1Interrupt as string = "MI2C1Interrupt, IEC1.1" public const CMPInterrupt as string = "CMPInterrupt, IEC1.2" public const CNInterrupt as string = "CNInterrupt, IEC1.3" public const INT1Interrupt as string = "INT1Interrupt, IEC1.4" public const IC7Interrupt as string = "IC7Interrupt, IEC1.6" public const IC8Interrupt as string = "IC8Interrupt, IEC1.7" public const DMA2Interrupt as string = "DMA2Interrupt, IEC1.8" public const OC3Interrupt as string = "OC3Interrupt, IEC1.9" public const OC4Interrupt as string = "OC4Interrupt, IEC1.10" public const T4Interrupt as string = "T4Interrupt, IEC1.11" public const T5Interrupt as string = "T5Interrupt, IEC1.12" public const INT2Interrupt as string = "INT2Interrupt, IEC1.13" public const U2RXInterrupt as string = "U2RXInterrupt, IEC1.14" public const U2TXInterrupt as string = "U2TXInterrupt, IEC1.15" public const SPI2ErrInterrupt as string = "SPI2ErrInterrupt, IEC2.0" 85

APPENDIX F. USING EMBEDDED ASSEMBLER Chapter 1 Basic Concepts Identifiers and Reserved Words The most common use for an identifier is to name constants, variables, aliases, structures, subroutines and functions. You should try and use descriptive names for identifiers, as this will make your program easier to follow and debug. A valid identifier is composed of the following elements: [underscore] letter letter digit underscore In other words: an optional underscore character followed by a single letter of the alphabet, followed by one or more letters, digits or underscores. A reserved word has a special meaning for the compiler and cannot be used as an identifier. A list of reserved words can be found in Appendix B. Comments Comments are not compiled and are used to document your program. To add a single line comment, use a quote character. For example, this is a comment... Value = 10 this is also a comment Firewing also supports block comments. For example, /* this is a block comment */ Line Continuation Character Individual declarations or statements must be contained on a single line. For example, Dim Value As Byte 84 1

CHAPTER 1. BASIC CONCEPTS is allowed but Dim Value As Byte is not allowed. If you want to continue a declaration or statement on another line, you must use the line continuation underscore character. For example, Dim Value _ continue to next line As Byte Constants [private public] const identifier as type = expression Private An optional keyword which ensures that a constant is only available from within the module it is declared. Constant declarations are private by default. Public An optional keyword which ensures that a constant is available to other programs or modules. Appendix F Using Embedded Assembler You can embed PIC assembler code in subroutines and functions, as well as your main program code, by using an asm end asm block. You can also declare local variables inside your subroutine or function and use them in you assembler code. For example, Function AddTen(value As uinteger) As Byte Dim localvar As uinteger = 10 Asm mov localvar, WREG ; local variable into WREG add value ; add param variable mov WREG, AddTen End Asm End Function ; move WREG result into function result Identifier A mandatory constant name, which follows the standard identifier naming conventions Type A mandatory data type. Supported types include boolean, bit, byte, sbyte, short, ushort, integer, uinteger, single, string and char. Expression A mandatory literal, constant declaration or a mixture of both. A constant declaration can be used in a program or module in place of a literal value. Constant data cannot be changed at runtime (that is, you cannot assign a new value to a constant when your program is executing). However, constants have the advantage of making your code much more readable and manageable. You can declare constants one at a time, like this Const maxsamples As Byte= 20 Const sizeofarray As Byte = 20 You can also use an expression on the right hand side of a constant declaration. For example, Const hello As String = "Hello" Const helloworld As String = Hello + " World" Const valuea As Single = 12 * 0.4 Const valueb = valuea + 10 2 83

APPENDIX E. TYPE CONVERSIONS CHAPTER 1. BASIC CONCEPTS Constants, unlike program variables, do not use RAM to store their values. If a constant is used in a program expression, code memory is used instead. When declaring numeric constants, or when using numeric literals in your program, you can use different number representations. Representation Prefix Example Value Decimal none 100 100 decimal Binary &B &B100 4 decimal Octal &O &O12 10 decimal Hexadecimal &H &H100 256 decimal Array Constants [private public] const identifier([size]) as type = ""value, value"" Private An optional keyword which ensures that a constant array is only available from within the module it is declared. Constant arrays are private by default. Public An optional keyword which ensures that a constant array is available to other programs or modules. Identifier A mandatory constant name, which follows the standard identifier naming conventions Size An optional constant expression which defines the number of elements in the constant array. If size is omitted, the compiler will automatically compute the size based on the number of elements in the list. Type A mandatory data type. Supported types include boolean, bit, byte, sbyte, short, ushort, integer, uinteger, single, string and char. Value One or more data values. Array constants are extremely useful for accessing sets of data from within your program at runtime. Like single constant declarations, array data values cannot be changed at runtime. For example, Const arraysize As Byte = 5 Const constarray(arraysize) As Byte = 1, 2, 10, 20, 100 Constant arrays can be accessed in the same way as you would any other variable array. For example, display value to terminal program, include CR and LF 82 3

CHAPTER 1. BASIC CONCEPTS APPENDIX E. TYPE CONVERSIONS Const constarray(2) As Byte = 100, 200 Dim index As Byte For index = 0 To UBound(constArray) Console.Write(CStr(constArray(index)), 13, 10) Next result may be intermittent, which makes very difficult debugging sessions. Typecasting is very useful, but it must be used with extreme care. A table of possible conversion functions can be found in Appendix D. You can also directly assign a constant array to a variable array, if the number of array elements are the same. For example, Const constarray(2) As Byte = 100, 200 two elements Dim vararray(2) As Byte two elements vararray = constarray assign values to variable array You can assign constant string arrays to variable string arrays. The only caveat is that the size of each string size, as well as the number of array elements, must be the same. This is easy to do by packing out the constant array strings with spaces. For example, largest string (Au revoir) is 9 characters, so pack each string to match- Const menuenglish(2) As String = "Hello ", "Goodbye " Const menufrench(2) As String = "Bonjour ", "Au revoir" Dim menu(2) As String(10) 9 + null terminator menu = menuenglish menu is now set for english menu = menufrench menu is now set for french You only need to pack constant strings when performing direct assignment, like in the example above. If you just wish to access each array element individually, then no packing is required. Constant arrays can only have a single dimension. Firewing does not support multidimensional constant arrays. Constant arrays use program memory and not data RAM to store their values. This is unlikely to cause problems under normal circumstances, given the amount of code space available with current PIC microcontrollers. However, code space is not unlimited and care should be exercised if using exceptionally large constant array declarations. Enumerated Types [private public] enum identifer [as type] enumvalue [ = expression] end enum 4 81

APPENDIX E. TYPE CONVERSIONS CHAPTER 1. BASIC CONCEPTS Notice that the temporary variable is a word size, because adding two bytes may result in a number larger than 8 bits. To override this behavior, you can use a typecast, result = CByte(a + b) + c The intermediate storage allocation for (a + b) will now only be a byte. Typecasting can also be used to reduce the size of a declared variable, for example result = CByte(WordVar) + b + c This will generate a temporary storage value of 16 bits (rather than 32), because byte + byte will require a 16 bit result. Note the subtle difference between MyWord made a byte, added to b, tmp storage = 16 bits result = CByte(WordVar) + b + c result of (MyWord + b) is byte, tmp storage is 8 bits result = CByte(WordVar + b) + c You do not normally have to worry about mixing types within Firewing expressions, as the compiler will generally promote variables automatically to ensure the correct result is obtained. However, typecasting can be extremely useful for expressions that contain mixed types. For example, Dim SValue As Integer Dim UValue As UShort Dim FValue As Single Dim Result As UShort Result = SValue + UValue + FValue In this example, the compiler needs to ensure that the signed and unsigned integer addition (SValue + UValue) is computed correctly by internally converting and promoting the subexpression before a signed addition is performed. Next, the intermediate result is converted to a floating point format, before it can be added to FValue. Finally, the floating point intermediate result is converted into an ordinal type and assigned to the variable Result. All these computations need to be done for the correct result to be calculated, given that the compiler knows nothing about the state of the mixed types used. However, if you understand what your program is doing, you can change the behavior of the compiler expression generator to produce better optimized code. For example, we could write the expression as, Result = CUShort(SValue) + UValue + CUShort(FValue) This would reduce the amount of code needed to support the computation by approximately 70 Please remember, the compiler expression generator will produce code to try and obtain the correct results, given any mix of variable types. It does not make assumptions about your code. Changing this behavior may lead to an incorrect result being obtained. Worse, the incorrect Private An optional keyword which ensures that an enumerated type is only available from within the module it is declared. Enumerated types are private by default. Public An optional keyword which ensures that an enumerated type is available to other programs or modules. Identifier A mandatory name, which follows the standard identifier naming conventions. Type - An optional type. The type value can be byte, sbyte, short, ushort, integer or uinteger. If omitted, the type defaults to byte. Firewing stores the enumerated type values as integers. EnumValue A list of unique enumerated identifiers. Expression An optional constant expression which redefines the default number assigned to each enumerated identifier. An enumerated type is a list of unique identifiers with an optional value. When you declare a variable of type enumerated, it can only take on those values. For example, enumerated type... Public Enum DeviceState Unknown Inserted Removed End Enum set state to unknown... Dim state As DeviceState = DeviceState.Unknown get the device state... Sub GetDeviceState() If PORTD.1 = 0 Then state = DeviceState.Inserted Else state = DeviceState.Removed End If main program... GetDeviceState If state = DeviceState.Inserted Then Console.Write("Device is inserted", 13, 10) Else 80 5

CHAPTER 1. BASIC CONCEPTS Console.Write("Device is NOT inserted", 13, 10) End If In this example, trying to assign a value other than Unknown, Inserted or Removed to the variable State will generate a compile error. Enumerated values that don t have an explicit value expression will start at zero, with the next item being one greater than the previous item. For example, With Console, State.Write(CStr(.Unknown), " = ", CStr(CByte(.Unknown)),13,10).Write(CStr(.Inserted), " = ", CStr(CByte(.Inserted)),13,10).Write(CStr(.Removed), " = ", CStr(CByte(.Removed)),13,10) End With Will output Unknown = 0 Inserted = 1 Removed = 2 To change this default behaviour, simply assign an expression to each enumerated item. For example, Public Enum DeviceState As Byte Unknown = 0 Inserted = 100 Removed = 200 End Enum Note that you can give enumerated values the same value either explicitly or implicitly, Public Enum DeviceState As Byte Unknown Inserted = 100 Removed = 200 Plugged = Inserted Unplugged = Removed End Enum Appendix E Type Conversions The compiler uses relatively strong type checking, which means that an error is generated if you try and assign variables of different types to each other. This is good as it helps prevents program errors through the incorrect assignment of variable types. However, you can typecast a value to override this behavior. For example, you may want to assign a char to a byte or a bit to a boolean, like this Dim mychar As Char = "A" Dim mybyte As Byte = CByte(myChar) Dim myboolean As Boolean = CBool(STATUS.2) Type assignment is a little more relaxed when assigning floating point to integer or vice versa, so typecasting is not needed. For example, Dim myfloat As Single = 10.3 Dim mybyte As Byte = 0 mybyte = myfloat myfloat = mybyte Type conversion or typecasting can be particularly useful for controlling code generation when expressions are used. If an expression has more than two operands, temporary storage is automatically allocated by the compiler to store intermediate results. For example, Dim a As Byte Dim b As Byte Dim c As Byte Dim result As UShort result = a + b + c Would translate to something like TMP_WORD = a + b result = TMP_WORD + c 6 79

APPENDIX D. CONVERSION FUNCTIONS Chapter 2 Variables [private public] dim identifier as type [ = expression] Private An optional keyword which ensures that a variable is only available from within the module it is declared. Variables are private by default. Public An optional keyword which ensures that a variable is available to other programs or modules. Identifier A mandatory variable name, which follows the standard identifier naming conventions Type A mandatory data type. Supported types include enumerated, boolean, bit, byte, sbyte, short, ushort, integer, uinteger, single, structures, string and char. Expression - An optional assignment expression. A variable holds data on which a program operates. Unlike constants, variable values can change dynamically when the program is executing. A variable is like a box, which holds values. You have to tell the compiler in advance the type of variable that will fit into the box. You declare variables one at a time, like this Dim index As Byte Dim range As Byte As mentioned previously, the type defines what values can fit into a variable. It s important to note that data RAM on a PIC microcontroller is substantially less than the code memory used to store your program. In addition, program operations on large data types (for example, unsigned integers) will generate much more underlying ASM code. Refer in Appendix C for a list of variable types supported by the compiler and their storage requirements. Unlike many other BASIC compilers, Firewing does allow variables of different types to be used in the same expression. For example, an unsigned byte can be multiplied by an integer and assigned to a variable declared as floating point. However, this practice should be avoided if possible, as the code automatically generated by 78 7

CHAPTER 2. VARIABLES the compiler needs to convert one type into another in order to compute the correct result. This will result in a larger code footprint than would otherwise be generated if all of the variables used had been declared as the same type. The types bit, byte, sbyte, short, ushort, integer, uinteger and single shown in Appendix C clearly outline the numeric ranges for any variables declared using them. Variable Initialiser A variable initialiser has the ability to combine a variable declaration with an assignment. For example, Dim value As Byte = 0 Is the same as Dim value As Byte value = 0 An initialiser does not need to be a constant, it can be any legal expression. For example, Dim mystr As String = "Hello World" a string Dim myval As Byte = Len(MyStr) length of string Boolean Types Appendix D Conversion Functions Function Converts Argument To CBit Bit CBool Boolean CByte Unsigned Byte CChar Char CDbl Floating point number CInt Integer CLng Integer CSByte Signed Byte CShort Signed Word CSng Floating point number CStr String CUInt Unsigned Integer CULng Unsigned Integer CUShort Unsigned Word The boolean data type enables you to represent something as true or false. It cannot hold a numeric value. The right hand side of an assignment expression must always evaluate to true or false, or set directly by using the compilers predefined boolean constants. For example, Dim Ok As Boolean = True Booleans are particularly useful when dealing with flow control statements, such as if then or iteration statements, such as while end while or do loop until. A boolean data type can significantly contribute to the readability of a program, making code sequences appear more logical and appropriate. For example, the following code shows how you could set a bit flag, if the value of index falls within 10 and 20, Dim index As Byte = 5 Dim datainrange As Bit If index >= 10 And index <= 20 Then datainrange = 1 Else datainrange = 0 End If 8 77

APPENDIX C. TYPES, MODIFIERS AND CONSTANTS CHAPTER 2. VARIABLES However, if we change the flag datainrange to a boolean type, we could write the code like this, Dim index As Byte = 5 Dim datainrange As Boolean datainrange = index >= 10 And index <= 20 In the first example, testing index using if then evaluates to true or false. In the second example, datainrange is a boolean type, so we can dispense with the if then statement altogether and assign the result directly to datainrange. In addition, because datainrange is a boolean type, we don t have to explicitly test it when encountering any conditional expressions. Remember, a boolean can only be true or false, so we simply write something like this, If Not datainrange Then output an error End If In this example, if datainrange is false, then the if then statement will evaluate to true (the boolean operator not inverts the false into a true) and an error is output. String and Char Types A string variable can be described as a collection of character elements. For example, the string "Hello" consists of 5 individual characters, followed by a null terminator. The Firewing compiler uses a null terminator (character 0) to denote the end of a string sequence. A string variable can be declared and initialized in the following way, Dim mystring As String mystring = "Hello World" By default, the compiler will allocate 24 bytes of RAM for each string declared. That is, you can assign a string sequence of up to 23 characters, plus one for the null terminator. In the previous example, "Hello World" was 11 characters long. Assuming mystring will never get assigned a sequence larger than this, we can save some RAM storage by explicitly specifying the size of the string after the string keyword, like this 11 characters + null terminator... Dim mystring As String(12) It is extremely important that string variables are declared with enough character elements to support the runtime operation of your program. Failure to do so will 76 9

CHAPTER 2. VARIABLES certainly result in problems when your code is executing. For example, concatenating (joining) two strings that contain 20 characters each will require a destination string that has reserved 41 elements (2 * 20, + 1 string terminator). Firewing enables you to specify string sizes of up to 256 bytes, which equates to 255 individual character elements. Unlike strings, a char type can only hold one single character. A char variable can be declared and initialized in the following way, Dim mychar As Char mychar = "A" Appendix C Types, Modifiers and Constants The compiler supports the "+" or "&" operators to concatenate (join) two strings. example, For Dim stra As String = "Hello" Dim strb As String = "World" Dim result As String = stra & " " & strb Will result in result being set to "Hello World". The two relational operators = (equal) and <> (not equal) are also supported for string comparisons. For example, If stra = strb Then Console.Write("Strings are equal!") End If If stra <> strb Then Console.Write("Strings are NOT equal!") End If You can also mix the concatenation operator with the supported relational operators, as shown in the following example, Dim stra As String = "Hello" Dim strb As String = "World" If stra & " " & strb = "Hello World" Then Console.Write("Strings are equal!", 13, 10) End If The compiler can also read or write to a single string element by indexing it in the following way, Dim strresult As String = "Hello World" strresult(5) = "_" This would result in "Hello World" being changed to "Hello_World". Note that the first character of a string variable is located at 0, the second character at 1 and so on. 10 75

APPENDIX B. RESERVED WORDS CHAPTER 2. VARIABLES An alternative way to assign a single character to a string element or char variable is by using the CChar typecast. For example, the underscore character ("_") can be represented by the ASCII number 95 decimal. We could therefore write StrResult(5) = cchar(95). This technique is particularly useful when dealing with non printable characters, such as carriage returns and line feeds. A useful compiler constant is nothing, which can be used to set, or tested for, a string null terminator. In the following example, the length of a string is computed and output via the microcontroller s hardware USART. Dim str As String = "Hello World" Dim index As Byte = 0 While str(index) <> Nothing Index = Index + 1 End While Console.Write("Length is ", CStr(Index), 13, 10) It should be noted that the compiler constant nothing is logically equivalent to "" (an empty string). Arrays [private public] dim identifier(size) as type [ = ""value, value ""] Private An optional keyword which ensures that an array is only available from within the module it is declared. Arrays are private by default. Public An optional keyword which ensures that an array is available to other programs or modules. Identifier A mandatory variable name, which follows the standard identifier naming conventions Size A mandatory size which describes the number of elements in the array. Arrays can only have a single dimension. Firewing does not currently support multi-dimensional arrays. Type A mandatory data type. Supported types include boolean, bit, byte, sbyte, short, ushort, integer, uinteger, single, structures, string and char. Value - An optional list of array values. Arrays are collections of values, with each element being of the same type. When you have many variables in your program, it is sometimes useful to use a more manageable array, rather than keep track of them manually. You can declare arrays like this: 74 11

CHAPTER 2. VARIABLES APPENDIX B. RESERVED WORDS Dim array1(5) As Byte Dim array2(10) As Byte For bit or boolean arrays, accessing a single element using a variable index is very computationally expensive. For example bitarray(index) = 1. If at all possible, use a byte array instead. You can initialize your array when declaring it. For example, Dim myarray(5) As Byte = 1,2,3,4,5 This will declare a byte array of 5 elements and initialize the array with the value 1..5. To access a single array element in your program, use the array name followed by round brackets around the index of element you want. For example, if you want to access the second element of myarray, then use myarray(1) = 10 Note that the first element of an array is located at 0, the second element at 1 and so on. Because Firewing arrays begin with zero indexes, care must be taken when iterating through an array. For example, Dim index As Byte For index = 0 To 4 myarray(index) = 200 Next is correct, and will set all 5 array elements (0 to 4) of myarray to the value 200. A very useful compiler keyword is ubound, which will automatically insert the correct upper bound for your array when the program is compiled. The ubound keyword is particularly useful when arrays are passed to functions or procedures, allowing you to write a routine that accepts arrays with different upper bounds. Using ubound, we could rewrite the previous example like this, Public RaiseEvent Return Save SByte Select Short Single SizeOf Static Step String Structure Sub System Then To Toggle True Type UBound UInteger ULong Union Until UShort While With Xor Dim index As Byte For index = 0 To UBound(myArray) myarray(index) = 200 Next Using ubound prevents your program inadvertently indexing an array beyond its highest element, which would certainly lead to problems when you program is executing. For example, Dim array(5) As Byte Dim index As Byte For index = 0 To 5 array(index) = 2 Next 12 73

APPENDIX B. RESERVED WORDS CHAPTER 2. VARIABLES Device Dim Disable Do Double EEPROM Else Else ElseIf Enable End Enum Erase Event Exit False For Function GoTo Handles High If IfSym Imports Inline Input Integer Interrupt Is IsNot LBound Long Loop Low Mod Module New Next Not Nothing NotInline Optional Or OrElse Output Overloads Port Private After compilation the variable Index would be stored in data RAM, directly after the array declaration. When index = 5, the memory location used by Index is overwritten with a 2 because we have set the incorrect upper limit in the for next loop. Instead of terminating at 5, the for next loop will never finish because the loop counter Index has been changed from 5 to a value of 2. Alias and Modifiers [private public] dim alias as identifier.modifier Private An optional keyword which ensures that an alias is only available from within the module it is declared. Variables are private by default. Public An optional keyword which ensures that an alias is available to other programs or modules. Alias A mandatory alias name, which follows the standard identifier naming conventions Identifier A mandatory and previously declared variable name, which follows the standard identifier naming conventions Modifier One or more optional modifiers which can be used to access different parts of the variable identifier Unlike a variable, an alias is declared without a type and does not allocate any data RAM. As the name suggests, it shares its data RAM with a previously declared variable. A simple alias declaration is shown below, Dim value As Byte Dim myalias As Value myalias = 100 In this example, value has been declared as a byte type. myalias has been declared as an alias to value. When 100 is assigned to myalias, the number is stored at the RAM location reserved for value. In other words, value becomes equal to 100. Whilst a simple alias like this may be useful, substantial power and flexibility can be achieved when using an alias declaration with a modifier. For example, the program Dim Led As PORTB.7 While True High(Led) DelayMS(500) 72 13

CHAPTER 2. VARIABLES Low(Led) DelayMS(500) End While will flash an Led connected to PORTB, pin 7. A list of additional modifiers is shown in Appendix C. Some modifiers use an array notation. For example, PORTB.7 can be written as PORTB.Bits(7). The Booleans() array modifier is very useful for changing a bit field into a boolean. For example, many PIC microcontrollers have hardware USARTs to support serial communication. You can test to see if data is available in the receive buffer by testing PIR1.5. Using the booleans modifier, we can create a more descriptive alias which has the virtue of being easy to test when using if then, while end while and do loop until statements, Dim dataisavailable As U1STA.Booleans(0) URXDA flag If dataisavailable Then process data here... End If Modifiers can also be used directly from within your program code. For example, Dim value As UShort value.byte1 = &HFF will set the high byte of the variable value to 255 decimal. Alias and modifiers can also be used on arrays. This is particularly useful if you want to access a single element in a complex data structure. In the following example, value is aliased to the first array elements minutes field. Structure Time Dim hours As Byte Dim minutes As Byte End Structure Dim array(10) As Time Dim value As array(0).minutes these assignments are logically identical... value = 10 array(0).minutes = 10 Aliases and modifiers can also be used on previously declared aliases. For example, Dim array(10) As UShort a word array Dim elementalias As array(3) alias to element 4 Dim bytealias As elementalias.byte1 element 4, high byte Dim bitalias As bytealias.7 element 4, high byte, bit 7 Appendix B Reserved Words Absolute AddressOf And AndAlso As Bit BitOf Boolean ByRef ByRefConst Byte ByVal Call Case CBit CBool CByte CChar CDbl Char CInt CLng Clock Compound Config Const Continue CSByte CShort CSng CStr CUInt CULng CUShort DelayMS DelayUS 14 71

APPENDIX A. OPERATORS CHAPTER 2. VARIABLES Operator Meaning * Multiply / Divide + Addition - Subtraction MOD Modulus In addition to the mathematical operators shown above, you can use the unary operator to change the sign. For example, Dim Value As SByte Value = 10 Value = 10 Value = -Value Value = -10 Logical Operators The modifiers discussed up until now have been used to access smaller parts of a larger variable. The Firewing compiler also supports modifier promotion. That is, aliasing a smaller variable to a larger whole. For example, given the declarations Dim array(8) As Byte Dim lower As array(0).asuinteger Dim upper As array(4).asuinteger we can now access the lower and upper 4 bytes of an array using single assignments, like this lower = &HF0F0F0F0 upper = &HF0F0F0F0 Each element of Array will now be set to &HF0. Please note that the Firewing compiler does not currently support modifier promotion of PIC microcontroller register names from within a code block. Operator NOT AND OR XOR Meaning Negate Logical AND Logical OR Logical XOR Logical operators can be used to build conditional expressions, for example, when using if then, while end while and do repeat until statements. Applying a boolean operator yields either true or false. Bitwise Operators The following operators perform bitwise manipulation on integer operands. Operator Meaning NOT A bitwise NOT or complement AND Bitwise AND OR Bitwise OR XOR Bitwise XOR «Shift Left» Shift Right 70 15

CHAPTER 2. VARIABLES Appendix A Operators Operator Precedence Level Operators 1 unary -, unary + 2 *, / 3 MOD 4 +, - 5 & 6 «,» 7 =, <, >, <=, >=, <> 8 NOT 9 AND, ANDALSO 10 OR, ORELSE 11 XOR Operators at level one have the highest precedence, with operators at level seven having the lowest precedence. Parentheses can be used to override the order of precedence rules, allowing parts of an expression to be evaluated before others. Relational Operators The operators used for comparison are called relational operators. Applying a relational operator will yield a result of true or false. Operator Meaning = Is equal to < Is less than > Is greater than <= Is less than or equal to >= Is greater than or equal to <> Is not equal to The only relational operators supported for string types are equal and not equal, unless the string is being compared against nothing., in which case "is" and "isnot" may be used. Because the internal binary representation of floating point numbers may not be exact, the equality operator should be avoided for floating point numbers. Mathematical Operators 16 69

CHAPTER 11. COMPILER DIRECTIVES Chapter 3 Structures, Unions and User Types [private public] structure identifier variable-declaration variable declaration end structure Private An optional keyword which ensures that a structure is only available from within the module it is declared. Structures are private by default. Public An optional keyword which ensures that a structure is available to other programs or modules. Identifier A mandatory type name, which follows the standard identifier naming conventions Variable-declaration One or more variable declarations Type A mandatory data type. Supported types include boolean, bit, byte, sbyte, short, ushort, integer, uinteger, single, structures, string and char. A structure is a collection of one or more variable declaration fields. Each field can be a different data type. A structure is an extremely useful and powerful feature of the Firewing language which enables you to assemble dissimilar elements under one single roof. To better understand structures, the following example illustrates how to create a new structure called Time, Structure Time Dim hours As Byte Dim minutes As Byte End Structure The declaration above informs the compiler that Time contains two byte fields, called hours and minutes. We can now create a variable of type Time, in exactly the same way as you would any other compiler type, such as byte or single. For example, Dim mytime As Time Access to an individual field within the variable mytime is achieved by using the dot (.) notation, 68 17

CHAPTER 3. STRUCTURES, UNIONS AND USER TYPES CHAPTER 11. COMPILER DIRECTIVES mytime.hours = 9 mytime.minutes = 59 A structure can also use another structure in one or more of its field declarations. example, time structure Structure Time Dim hours As Byte Dim minutes As Byte End Structure sample structure... Structure Sample Dim thetime As Time Dim value As Short End Structure Dim mysample As Sample For Relational <, <=, <>, >=, >, = Logical and, or, xor, not Bitwise «,», and, or, xor, not Math +, -, /, *, mod In addition to the standard operators show above, the preprocessor also allows the use of the in operator. For example, #if _clock = 3 Or _clock = 4 Or _clock = 8 Or _clock = 10 #define LowSpeed #endif can be written more simply as #if _clock in (3,4,8,10) #define LowSpeed #endif You can also use a range of values with the in operator. For example, We now have a type called Sample, who s field members include thetime (of type Time) and value (of type ushort). Again, dot (.) notation is used to access individual field elements, mysample.thetime.hours = 15 mysample.thetime.minutes = 22 mysample.value = 1024 Structures can also be used with arrays. For example, using the previously declared Sample type, we could declare and access multiple mysample variables by declaring an array, Dim mysamples(24) As Sample array of samples, one every hour To access each field for every array element, we just need to iterate through the samples array, #if Value in (1 to 10, 20, 100 to 255) #define LegalRange #else #error "Value out of range" #endif Because the in operator evaluates to true or false, you can apply other boolean operators. For example, #if Not (Value in (1 to 10)) #error "Out of range" #endif In the above example, an error is generated if value is not in the range 1 to 10. Dim index As Byte For index = 0 To UBound(mySamples) mysamples(index).thetime.hhours = 0 mysamples(index).thetime.minutes = 0 mysamples(index).value = 0 Next The above code is actually a very verbose way of initializing all fields to zero, but it does demonstrate how each field can be accessed. It should be noted that by using the inbuilt compiler command erase, the above can be achieved by using, Erase(Samples) 18 67

CHAPTER 11. COMPILER DIRECTIVES CHAPTER 3. STRUCTURES, UNIONS AND USER TYPES In the above example, the program constant MyBufferSize becomes equal to 64, as this is the value assigned to the option identifier BUFFER_SIZE. It is important to note that a user program identifier will always take precedence over an option directive. For example, #option BUFFER_SIZE = 64 Const BUFFER_SIZE = 16 Const MyBufferSize = BUFFER_SIZE In this example, MyBufferSize becomes equal to 16. The other difference between option and define directives is that re-declaring an option twice, using the same identifier will not cause an error. For example, #option BUFFER_SIZE = 64 #option BUFFER_SIZE = 16 In this example, BUFFER_SIZE will become equal to 64, which is the first option found by the preprocessor. The second declaration of BUFFER_SIZE is ignored. This capability may appear a little redundant at first, but it s an extremely useful technique to enable users to configure a module from their main program code. IsOption IsOption(Identifier) Used in conjunction with an #If #else #endif statement IsOption will return true if an #option for the referenced identifier has been defined. This is primarily of use for validating the parameters which have been defined in the #option. Typically, if the validation fails an error can be raised to the preprocessor and the error message reported. #if IsOption(USART_LS) And Not (USART_LS in (True, False)) #error USART_LS, "Invalid option. LS must be TRUE or FALSE." #endif #option USART_LS = False This will check to see if the option USART_LS has been previously defined. If it has, it will check the values that have been assigned to the option are true or false. If any another value has been assigned to USART_LS it will generate an error. The last line will then set a default value for the USART_LS option. Preprocessor Expressions The preprocessor allows you to use a rich set of operators within expressions. They include Unions In the previous structure example, the total size of the structure is the sum of all members of the structure. For example, Time has two member fields (hours and minutes) and each field is one byte in size. Therefore, the total size of the structure is two bytes. A union works differently in that member fields can share the same address space. For example, Structure Status Dim val As Byte Dim enabled As Val.0 Dim connected As Val.1 Dim overrun As Val.2 End Structure The member fields enabled, connected and overrun are aliased to the byte variable val. They don t have separate storage requirements - they are shared with val. For example, Dim mystatus As Status mystatus.val = 0 clear status mystatus.connected = 1 In the above example, we can access the structure as a byte value or access individual bits. Importantly, the total structure size is only one byte. You can apply all the standard aliasing rules to structures. For example, Structure IPAddr Dim val(4) As Byte Dim IP As val(0).asuinteger End Structure Dim myaddr As IPAddr myaddr.ip = &HFFFFFFFF myaddr.val(0) = &H00 In this example, the IP address structure only uses 4 bytes of storage. In some cases, it may not be possible to create a union through aliasing alone. For example, the member field type may be another structure. In these situations, you can use the union keyword, like this: Structure Word Dim LSB As Byte Dim MSB As Byte End Structure 66 19

CHAPTER 3. STRUCTURES, UNIONS AND USER TYPES CHAPTER 11. COMPILER DIRECTIVES Structure Value Union byteval As Byte Union wordval As Word Union floatval As Single End Structure In the above example, the size of the structure is equal to the size of the largest member field which is 4 bytes (the size of single). Another way to think of the union keyword is that it resets the internal offset address of the member field to zero. For example, Structure TValue Dim floatval As Single offset = 0 (0 + 4 byte = 4) Dim wordval As UShort offset = 4 (4 + 2 byte = 6) Dim byteval As Byte offset = 6 (6 + 1 byte = 7) End Structure total storage requirement = 7 The above structure declaration shows the starting offset address, with the total storage requirement for the structure. Now take a look at the same structure, but this time with the union keyword: Structure Value Union floatval As Single offset = 0 (0 + 4 byte = 4) Union wordval As UShort offset = 0 (0 + 2 byte = 2) Union byteval As Byte offset = 0 (0 + 1 byte = 1) End Structure total storage requirement = 4 Include source statements if a define directive has not been declared. If the expression evaluates to false (that is, the identifier has been declared), the code statements following #else are included. The #else directive is optional. #if #elseif #else #endif #if expression code [#elseif expression code] [#else code] #endif Include source statements if an expression evaluates to true. If the expression evaluates to false, each #elseif is then evaluated. If neither #if or #elseif evaluate to true, code statements following #else are included. Both #elseif and #else directives are optional. #error #error "Error string" Generate a preprocessor error and halt compilation. User Types [private public] Type identifier = Type Private An optional keyword which ensures that an alias is only available from within the module it is declared. Variables are private by default. Public An optional keyword which ensures that an alias is available to other programs or modules. Identifier A mandatory and previously declared variable name, which follows the standard identifier naming conventions Type A mandatory data type. Supported types include boolean, bit, byte, sbyte, short, ushort, integer, uinteger, single, structures, string and char. You can create your own specific user type based on an existing data type or structure. This has two main purposes: #warning #warning "Error string" Generate a preprocessor warning. Unlike #error, compilation will continue. #option #option identifier [ = expression] Creates an option identifier. An option identifier is global and identical to the #define directive in every way, except for two main differences. Firstly, an option identifier can be seen and used in the declaration block of a user program. For example, #option BUFFER_SIZE = 64 Const MyBufferSize = BUFFER_SIZE 20 65

CHAPTER 11. COMPILER DIRECTIVES CHAPTER 3. STRUCTURES, UNIONS AND USER TYPES Creates a variable identifier. A variable identifier is global, but unlike a constant directive, its value and type can be changed. For example, #variable MyValue = 10 #variable MyValue = "Hello" #define To ensure a rigorous application of type checking. See type casting later in this reference. To enable overloaded operations to identify which overloaded routine to call when the data presented is of a similar data type. See overloading later in this reference) Here is an example of a user type: Type mytype = Byte Dim myvar As mytype #define identifier [ = expression] Creates a define identifier. A define identifier is global, which can be taken out of scope using the #undefine directive. An optional expression can be assigned to a define directive. This can be used like a constant in any expression. #undefine #undefine identifier Undefines a previously declared define directive. #ifdef #else #endif #ifdef identifier code [#else code] #endif Include source statements if a define directive has been declared. If the expression evaluates to false (that is, the identifier has not been declared), the code statements following #else are included. The #else directive is optional. #ifndef #else #endif #ifndef identifier code [#else code] #endif 64 21