ask question about motor controllers

Introduction

The Roboteq Micro Basic is high level language that is used to generate programs that runs on Roboteq motor controllers. It uses syntax nearly like Basic syntax with some adjustments to speed program execution in the controller and make it easier to use.

Comments

A comment is a piece of code that is excluded from the compilation process. A comment begins with a single-quote character. Comments can begin anywhere on a source line, and the end of the physical line ends the comment. The compiler ignores the characters between the beginning of the comment and the line terminator. Consequently, comments cannot extend across multiple lines.

'Comment goes here till the end of the line.

Boolean

True and False are literals of the Boolean type that map to the true and false state, respectively.

Numbers

Micro Basic supports only integer values ranged from -2,147,483,648 (0x80000000) to 2,147,483,647 (0x7FFFFFFF).

Numbers can be preceded with a sign (+ or -), and can be written in one of the following formats:

  • Decimal Representation
    Number is represented in a set of decimal digits (0-9).
    120                5622                504635
    Are all valid decimal numbers.

     

  • Hexadecimal Representation
    Number is represented in a set of hexadecimal digits (0-9, A-F) preceded by 0x.
    0xA1               0x4C2               0xFFFF
    Are all valid hexadecimal numbers representing decimal values 161, 1218 and 65535 respectively.

     

  • Binary Representation
    Number is represented in a set of binary digits (0-1) preceded by 0b.
    0b101              0b1110011           0b111001010
    Are all valid binary numbers representing decimal values 5, 115 and 458 respectively.

     

Strings

Strings are any string of printable characters enclosed in a pair of quotation marks. Non printing characters may be represented by simple or hexadecimal escape sequence. Micro Basic only handles strings using the Print command. Strings cannot be stored in variable and no string handling instructions exist.

  • Simple Escape Sequence
    The following escape sequences can be used to print non-visible or characters:
    SequenceDescription
    \' Single quote
    \" Double quote
    \\ Backslash
    \0 Null
    \a Alert
    \b Backspace
    \f Form feed
    \n New line
    \r Carriage return
    \t Horizontal tab
    \v Vertical tab
  • Hexadecimal Escape Sequence

    Hexadecimal escape sequence is represented in a set of hexadecimal digits (0-9, A-F) preceded by \x in the string (such as \x10 for character with ASCII 16).

    Since a hexadecimal escape sequence can have a variable number of hex digits, the string literal "\x123" contains a single character with hex value 123. To create a string containing the character with hex value 12 followed by the character 3, one could write "\x00123".

So, to represent a string with the statement "Hello World!" followed by a new line, you may use the following syntax:

"Hello World!\n"

Blocks and Labels

A group of executable statements is called a statement block. Execution of a statement block begins with the first statement in the block. Once a statement has been executed, the next statement in lexical order is executed, unless a statement transfers execution elsewhere.

A label is an identifier that identifies a particular position within the statement block that can be used as the target of a branch statement such as GoTo, GoSub or Return.

Label declaration statements must appear at the beginning of a line. Label declaration statements must always be followed by a colon (:) as the following:

Print_Label:
                        Print("Hello World!")

Label name should start with alphabetical character and followed by zero or more alphanumeric characters or underscore. Label names cannot start with underscore. Labels names cannot match any of Micro Basic reserved words.

Label names are case insensitive that is PrintLabel is identical to printlabel.

The scope of a label extends whole the program. Labels cannot be declared more than once in the program.

Variables

Micro Basic contains only two types of variable (Integer and Boolean) in addition to arrays of these types. Boolean and arrays must be declared before use, but Integer variables may not be declared unless you use the Option Explicit compiler directive.

Option Explicit

Variables can be declared using DIM keyword.

Variable name should start with alphabetical character and followed by zero or more alphanumeric characters or underscore. Variable names cannot start with underscore. Variable names cannot match any of Micro Basic reserved words.

Variable names are case insensitive, that is VAR is identical to var.

The scope of a variable extends whole the program. Variables cannot be declared more than once in the program.

Arrays

Arrays is special variables that holds a set of values of the variable type. Arrays are declared using DIM command.

To access specific element in the array you can use the indexer [] (square brackets). Arrays indices are zero based, so index of 5 refer to the 6th element of the array.

arr[0] = 10     'Set the value of the first element in the array to 10.
a = arr[5]      'Store the 6th element of the array into variable a.

Terminology

In the following sections we will introduce Micro Basic commands and how it is used, and here is the list of terminology used in the following sections:

  • Micro Basic commands and functions will be marked in blue and cyan respectively.
  • Anything enclosed in < > is mandatory and must be supplied.
  • Anything enclosed in [ ] is optional, except for arrays where the square brackets is used as indexers.
  • Anything enclosed in { } and separated by | characters are multi choice options.
  • Any items followed by an ellipsis, ... , may be repeated any number of times.
  • Any punctuation and symbols, except those above, are part of the structure and must be included.
var is any valid variable name including arrays.
arr is any valid array name.
expression is any expression returning a result.
condition is any expression returning a boolean result.
stmt is single Micro Basic statement.
block is zero or more Micro Basic statements.
label is any valid label name.
n is a positive integer value.
str is a valid string literal.

Keywords

A keyword is a word that has special meaning in a language construct. All keywords are reserved by the language and may not be used as variables or label names. Below is a list of all Micro Basic keywords:

#define And AndWhile As Boolean
Continue Dim Do Else ElseIf
End Evaluate Exit Explicit False
For GoSub GoTo If Integer
Loop Mod Next Not Option
Or Print Return Step Terminate
Then To ToBool True Until
While XOr      

Operators

Micro Basic provides a large set of operators, which are symbols or keywords that specify which operations to perform in an expression. Micro Basic predefines the usual arithmetic and logical operators, as well as a variety of others as shown in the following table.

CategoryOperators
Arithmetic +   -   *   /   Mod  
Logical (boolean and bitwise) And   Or   XOr   Not   True   False  
Increment, decrement ++   --  
Shift <<   >>  
Relational =   <>   <   >   <=   >=  
Assignment =   +=   -=   *=   /=   <<=   >>=  
Indexing []  

Micro Basic Functions

The following is a set of Micro Basic functions

Abs Returns the absolute value of a given number.
Atan Returns the angle whose arc tangent is the specified number.
Cos Returns the cosine of the specified angle.
Sin Returns the sine of the specified angle.
Sqrt Returns the square root of a specified number.

Controller Configuration and Commands

The following is a set of device functions for interacting with the Controller

SetConfig Set a configuration parameter
SetCommand Send a Real Time command
GetConfig Read a configuration parameter
GetValue Read an operating value

Timers Commands

The following is a set of functions for interacting with the timers:

SetTimerCount Set number of milliseconds for timer to count.
SetTimerState Set state of a specific timer.
GetTimerCount Read timer count.
GetTimerState Read state of a specific timer.

Option (Compilation Options)

Micro Basic by default treats undeclared identifiers as integer variables. If you want the compilers checks that every variable used in the program is declared and generate compilation error if a variable is not previously declared, you may use Option explicit compiler option by pacing the following at the beginning of the program:

Option Explicit

Pre-Processor Directives (#define)

The #define creates a macro, which is the association of an identifier with a token expression. After the macro is defined, the compiler can substitute the token expression for each occurrence of the identifier in the source file.

#define <var> <expression>

The following example illustrates how use pre-processor directive:

#define CommandID _GO + 5
Print(CommandID)

Dim (Variable Declaration)

Micro Basic contains only two types of variable (Integer and Boolean) in addition to arrays of these types. Boolean and arrays must be declared before use, but Integer variables may not be declared unless you use the Option Explicit compiler directive.

Dim var As { Integer | Boolean }

The following example illustrates how to declare Integer variable:

Dim intVar As Integer

Arrays declaration uses a different syntax, where you should specify the array length between square brackets []. Array length should be integer value greater than 1.

Dim arr[n] As { Integer | Boolean }

The following example illustrates how to declare array of 10 integers:

Dim arr[10] As Integer

To access array elements (get/set), you may need to take a look to Arrays section.

Variable and arrays names should follow specification stated in the Variables section.

If...Then Statement

  • Line If
    If <condition> Then <stmt> [Else <stmt>]
  • Block If
    If <condition> [Then]
        <block>
    [ElseIf <condition> [Then]
        <block>]
    [ElseIf <condition> [Then]
        <block>]
    ...
    [Else
        <block>]
    End If

An If...Then statement is the basic conditional statement. If the expression in the If statement is true, the statements enclosed by the If block are executed. If the expression is false, each of the ElseIf expressions is evaluated. If one of the ElseIf expressions evaluates to true, the corresponding block is executed. If no expression evaluates to true and there is an Else block, the Else block is executed. Once a block finishes executing, execution passes to the end of the If...Then statement.

The line version of the If statement has a single statement to be executed if the If expression is true and an optional statement to be executed if the expression is false. For example:

Dim a As Integer
Dim b As Integer
a = 10
b = 20
' Block If statement.
If a < b Then
    a = b
Else
    b = a
End If
' Line If statement
If a < b Then a = b Else b = a

Below is an example where ElseIf takes place:

If score >= 90 Then
    grade = 1
ElseIf score >= 80 Then
    grade = 2
ElseIf score >= 70 Then
    grade = 3
Else
    grade = 4
End If

For...Next Statement

Micro Basic contains two types of For...Next loops:

  • Traditional For...Next:
    Traditional For...Next exists for backward compatibility with Basic, but it is not recommended due to its inefficient execution.

    Traditional For...Next is the same syntax as Basic For...Next statement.

  • C-Style For...Next:

    This is a new style of For...Next statement optimized to work with Roboteq controllers and it is recommended to be used. It is the same semantics as C++ for loop, but with a different syntax.

    For <var> = <expression> AndWhile <condition> [Evaluate <stmt>]
        <block>
    Next

    The c-style for loop is executed by initialize the loop variable, then the loop continues while the condition is true and after execution of single loop the evaluate statement is executed then continues to next loop.

    Dim arr[10] As Integer
    For i = 0 AndWhile i < 10
        arr[i] = -1
    Next

    The previous example illustrates how to initialize array elements to -1.

    The following example illustrates how to use Evaluate to print even values from 0-10 inclusive:

    For i = 0 AndWhile i <= 10 Evaluate i += 2
                                    Print(i, "\n")
    Next

While/Do Statements

  • While ... End While Statement
    While <condition>
        <block>
    End While

    Example:

    a = 10
    While a > 0
                                    Print("a = ", a, "\n")
        a--
    End While
    Print("Loop ended with a = ", a, "\n")
    
  • Do While ... Loop Statement
    Do While <condition>
        <block>
    Loop

    The Do While ... Loop statement is the same as functionality of the While ... End While statement but uses a different syntax.

    a = 10
    Do While a > 0
                                    Print("a = ", a, "\n")
        a--
    Loop
    Print("Loop ended with a = ", a, "\n")
                            
  • Do Until ... Loop Statement
    Do Until <condition>
        <block>
    Loop

    Unlike Do While ... Loop statement, Do Until ... Loop statement exist the loop when the expression evaluates to true..

    a = 10
    Do Until a = 0
                                    Print("a = ", a, "\n")
        a--
    Loop
    Print("Loop ended with a = ", a, "\n")
                            
  • Do ... Loop While Statement
    Do
        <block>
    Loop While <condition>

    Do ... Loop While statement grantees that the loop block will be executed at least once as the condition is evaluated and checked after executing the block.

    a = 10
    Do
                                    Print("a = ", a, "\n")
        a--
    Loop While a > 0
    Print("Loop ended with a = ", a, "\n")
                        
  • Do ... Loop Until Statement
    Do
        <block>
    Loop Until <condition>

    Unlike Do ... Loop While statement, Do ... Loop Until statement exist the loop when the expression evaluates to true..

    a = 10
    Do
                                    Print("a = ", a, "\n")
        a--
    Loop Until a = 0
    Print("Loop ended with a = ", a, "\n")
                        

Terminate Statement

The Terminate statement ends the execution of the program.

Terminate

Exit Statement

The following is the syntax of Exit statement:

Exit { For | While | Do }

An Exit statement transfers execution to the next statement to immediately containing block statement of the specified kind. If the Exit statement is not contained within the kind of block specified in the statement, a compile-time error occurs.

The following is an example of how to use Exit statement in While loop:

While a > 0
                        If b = 0 Then Exit While
End While

Continue Statement

The following is the syntax of Continue statement:

Continue { For | While | Do }

A Continue statement transfers execution to the beginning of immediately containing block statement of the specified kind. If the Continue statement is not contained within the kind of block specified in the statement, a compile-time error occurs.

The following is an example of how to use Continue statement in While loop:

While a > 0
                        If b = 0 Then Continue While
End While

GoTo Statement

A GoTo statement causes execution to transfer to the specified label. GoTo keyword should be followed by the label name.

GoTo <label>

The following example illustrates how to use GoTo statement:

GoTo Target_Label
Print("This will not be printed.\n")
Target_Label:
                        Print("This will be printed.\n")

GoSub/Return Statements

GoSub used to call a subroutine at specific label. Program execution is transferred to the specified label. Unlike the GoTo statement, GoSub remembers the calling point. Upon encountering a Return statement the execution will continue the next statement after the GoSub statement.

GoSub <label>

Return

Consider the following example:

Print("The first line.")
GoSub PrintLine
Print("The second line.")
GoSub PrintLine
Terminate
PrintLine:
                        Print("\n")
                        Return

The program will begin with executing the first print statement. Upon encountering the GoSub statement, the execution will be transferred to the given PrintLine label. The program prints the new line and upon encountering the Return statement the execution will be returning back to the second print statement and so on.

ToBool Statement

Converts the given expression into boolean value. It will be return False if expression evaluates to zero, True otherwise.

ToBool(<expression>)

Consider the following example:

Print(ToBool(a), "\n")

The previous example will output False if value of a equals to zero, True otherwise.

Print Statement

Output the list of expression passed.

Print({str | expression | ToBool(<expression>)}[,{str | expression | ToBool(<expression>)}]...)

The print statement consists of the Print keyword followed by a list of expressions separated by comma. You can use ToBool keyword to force print of expressions as Boolean. Strings are C++ style strings with escape characters as described in the Strings section.

a = 3
b = 5
Print("a = ", a, ", b = ", b, "\n")
Print("Is a less than b = ", ToBool(a < b), "\n")

+ Operator

The + operator can function as either a unary or a binary operator.

+ expression
expression + expression

- Operator

The - operator can function as either a unary or a binary operator.

- expression
expression - expression

* Operator

The multiplication operator (*) computes the product of its operands.

expression * expression

/ Operator

The division operator (/) divides its first operand by its second.

expression * expression

Mod Operator

The modulus operator (Mod) computes the remainder after dividing its first operand by its second.

expression Mod expression

And Operator

The (And) operator functions only as a binary operator. For numbers, it computes the bitwise AND of its operands. For boolean operands, it computes the logical AND for its operands; that is the result is true if and only if both operands are true.

expression And expression

Or Operator

The (Or) operator functions only as a binary operator. For numbers, it computes the bitwise OR of its operands. For boolean operands, it computes the logical OR for its operands; that is, the result is false if and only if both its operands are false.

expression Or expression

XOr Operator

The (XOr) operator functions only as a binary operator. For numbers, it computes the bitwise exclusive-OR of its operands. For boolean operands, it computes the logical exclusive-OR for its operands; that is, the result is true if and only if exactly one of its operands is true.

expression XOr expression

Not Operator

The (Not) operator functions only as a unary operator. For numbers, it performs a bitwise complement operation on its operand. For boolean operands, it negates its operand; that is, the result is true if and only if its operand is false.

Not expression

True Literal

The True keyword is a literal of type Boolean representing the boolean value true.

False Literal

The False keyword is a literal of type Boolean representing the boolean value false.

++ Operator

The increment operator (++) increments its operand by 1. The increment operator can appear before or after its operand:

++ var
var ++

The first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.

The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.

a = 10
Print(a++, "\n")
Print(a, "\n")
Print(++a, "\n")
Print(a, "\n")

The output of previous program will be the following:

10
11
12
12

-- Operator

The decrement operator (--) decrements its operand by 1. The decrement operator can appear before or after its operand:

-- var
var --

The first form is a prefix decrement operation. The result of the operation is the value of the operand after it has been decremented.

The second form is a postfix decrement operation. The result of the operation is the value of the operand before it has been decremented.

a = 10
Print(a--, "\n")
Print(a, "\n")
Print(--a, "\n")
Print(a, "\n")

The output of previous program will be the following:

10
9
8
8

<< Operator

The left-shift operator (<<) shifts its first operand left by the number of bits specified by its second operand.

expression << expression

The high-order bits of left operand are discarded and the low-order empty bits are zero-filled. Shift operations never cause overflows.

>> Operator

The right-shift operator (>>) shifts its first operand right by the number of bits specified by its second operand.

expression >> expression

<> Operator

The inequality operator (<>) returns false if its operands are equal, true otherwise.

expression <> expression

< Operator

Less than relational operator (<) returns true if the first operand is less than the second, false otherwise.

expression < expression

> Operator

Greater than relational operator (>) returns true if the first operand is greater than the second, false otherwise.

expression > expression

<= Operator

Less than or equal relational operator (<=) returns true if the first operand is less than or equal to the second, false otherwise.

expression <= expression

> Operator

Greater than relational operator (>) returns true if the first operand is greater than the second, false otherwise.

expression > expression

>= Operator

Greater than or equal relational operator (>=) returns true if the first operand is greater than or equal to the second, false otherwise.

expression >= expression

+= Operator

The addition assignment operator.

var += expression

An expression using the += assignment operator, such as

x += y

is equivalent to

x = x + y

-= Operator

The subtraction assignment operator.

var -= expression

An expression using the -= assignment operator, such as

x -= y

is equivalent to

x = x - y

*= Operator

The multiplication assignment operator.

var *= expression

An expression using the *= assignment operator, such as

x *= y

is equivalent to

x = x * y

/= Operator

The division assignment operator.

var /= expression

An expression using the /= assignment operator, such as

x /= y

is equivalent to

x = x / y

<<= Operator

The left-shift assignment operator.

var <<= expression

An expression using the <<= assignment operator, such as

x <<= y

is equivalent to

x = x << y

>>= Operator

The right-shift assignment operator.

var >>= expression

An expression using the >>= assignment operator, such as

x >>= y

is equivalent to

x = x >> y

[] Operator

Square brackets ([]) are used for arrays, see Arrays section.

Abs Function

Returns the absolute value of an expression.

Abs(<expression>)

Example:

b = Abs(-200) '200

Atan Function

Returns the angle whose arc tangent is the specified number.

Number is devided by 1000 before applying atan.

The return value is multiplied by 10.

Atan(<expression>)

Example:

angle = Atan(1000) '450 = 45.0 degrees

Cos Function

Returns the cosine of the specified angle.

The return value is multiplied by 1000.

Abs(<expression>)

Example:

value = Cos(0) '1000

Sin Function

Returns the sine of the specified angle.

The return value is multiplied by 1000.

Sin(<expression>)

Example:

value = Sin(90) '1000

Sqrt Function

Returns the square root of a specified number.

The return value is multiplied by 1000.

Sqrt(<expression>)

Example:

value = Sqrt(2) '1414

GetValue

This function is read operating parameters from the controller at runtime. The function requires a Operating Item, and an Index as parameters. The Operating Item can be any one from the table below. The Index is used to select one of the Value Items in multi channel configurations. When accessing a Operating Item that is not part of an array, the index value 1 must be used.

Details on the various operating parameters that can be read can be found in the Controller's User Manual

GetValue(OperatingItem, Index)
Current2 = GetValue(_BAMPS, 2) ' Read Battery Amps for Motor 2
Sensor = GetValue(_ANAIN, 6) ' Read voltage present at Analog Input 1

SetCommand

This function is used to send operating commands to the controller at runtime. The function requires a Command Item, and a Value as parameters. The Command Item can be any one from the table below. Details on the various commands, their effects and acceptable ranges can be found in the Controller's User Manual

SetCommand(CommandItem, [Channel], Value)
SetCommand(_GO, 1, 500) ' Set Motor 1 command level at 500
SetCommand(_DSET, 2) ' Activate Digital Output 2

SetConfig / GetConfig

These two functions are used to read or/and change one of the controller's configuration parameters at runtime. The changes are made in the controller's RAM and take effect immediately. Configuration changes are not stored in EEPROM.

SetConfig Set a configuration parameter
GetConfig Read a configuration parameter

Both commands require a Configuration Item, and an Index as parameters. The Configuration Item can be any one from the table below. The Index is used to select one of the Configuration Item in multi channel configurations. When accessing a configuration parameter that is not part of an array, the index value 1 must be used. Details on the various configurations items, their effects and acceptable values can be found in the Controller's User Manual.

Note that most but not all configuration parameters are accessible via the SetConfig or GetConfig function. No check is performed that the value you store is valid so this function must be handled with care.

When setting a configuration parameter, the new value of the parameter must be given in addition to the Configuration Item and Index.

SetConfig(ConfigurationItem, [Index], value)
GetConfig(ConfigurationItem, [Index])
Accel2 = GetConfig(_MAC, 2) ' Read Acceleration parameter for Motor 2
PWMFreq = GetConfig(_PWMF) ' Read Controller's PWM frequency
SetConfig(_MAC, 2, Accel2 * 2) ' Make Motor2 acceleration twice as slow

SetTimerCount/GetTimerCount

These two functions used to set/get timer count.

SetTimerCount(<index>, <milliseconds>)
GetTimerCount(<index>)

Where, index is the timer index (1-4) and milliseconds is the number of milliseconds to count.

SetTimerState/GetTimerState

These two functions used to set/get timer state (started or stopped).

SetTimerState(<index>, <state>)
GetTimerState(<index>)

Where, index is the timer index (1-4) and state is the timer state (1 means timer reached 0 and/or stopped, 0 means timer is running).

Sending RoboCAN Commands and Configuration

Sending commands or configuration values to remote nodes on RoboCAN is done using the functions.

SetCANCommand(<id>, <cc>, <ch>, <vv>)
SetCANConfig(<id>, <cc>, <ch>, <vv>)

Where:
    id is the remote Node Id in decimal.
    cc is the Command code, eg. _G.
    cc is the channel number. Put 1 for commands that do not normally require a channel number.
    vv is the value.

Reading RoboCAN Operating Values Configurations

The following functions are available in Micro Basic for requesting operating values and configurations from a remote node on RoboCAN.

FetchCANValue(<id>, <cc>, <ch>)
FetchCANConfig(<id>, <cc>, <ch>)

Where:
    id is the remote Node Id in decimal
    cc is the Command code, eg. _G
    cc is the channel number. Put 1 for commands that do not normally require a channel number.

The following functions can be used to wait for the data to be ready for reading.

IsCANValueReady()
IsCANConfigReady()

These functions return a Boolean true/false value. They take no argument and apply to the last issued FetchCANValue or FetchCANConfig function.

The retrieved value can then be read using the following functions.

ReadCANValue()
ReadCANConfig()

These functions return an integer value. They take no argument and apply to the last issued FetchCANValue or FetchCANConfig function.

RoboCAN Continuous Scan

A scan of a remote RoboCAN node is initiated with the function.

ScanCANValue(<id>, <cc>, <ch>, <tt>, <bb>)

Where:
    id is the remote Node Id in decimal.
    cc is the Query code, eg. _V.
    cc is the channel number. Put 1 for commands that do not normally require a channel number.
    tt is the scan rate in ms.
    bb is the buffer location.

The scan rate can be up to 255ms. Setting a scan rate of 0 stops the automatic sending from this node.

Unless otherwise specified, the buffer can store up to 32 values.

The arrival of a new value is checked with the function.

IsScannedCANReady(<aa>)

Where:
    aa is the location in the scan buffer.

The function returns a Boolean true/false value.

The new value is then read with the function.

ReadScannedCANValue(<aa>)

Where:
    aa is the location in the scan buffer.

The function returns an integer value. If no new value was received since the previous read, the old value will be read.

Checking the Presence of a RoboCAN Node

No error is reported in MicroBasic if an exchange is initiated with a node that does not exist. A command or configuration sent to a non-existent node will simply not be executed. A query sent to a non existing or dead node will return the value 0. A function is therefore provided for verifying the presence of a live node. A live node is one that sends the distinct RoboCAN heartbeat frame every 128ms. The function syntax is:

IsCANNodeAlive(<id>)

Where:
    id is the remote Node Id in decimal

The function returns a Boolean true/false value.

Go to top