ask question about motor controllers

Introduction

Roboteq's MicroBasic 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.

For an overview and video demonstration go to the MicroBasic Overview page.

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:

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

Micro Basic currently support only one function called Abs.

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

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  Then  [Else ]
  • Block If
    If  [Then]

    [ElseIf [Then]
    ]
    [ElseIf [Then]
    ]
    ...
    [Else
    ]
    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  =  AndWhile  [Evaluate ]

    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 

    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 

    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 

    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

    Loop While

    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

    Loop Until

    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 

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 

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()

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()}[,{str | expression | ToBool()}]...)

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")

Abs Function

Returns the absolute value of an expression.

Abs()

Example:

a = 5
b = Abs(a – 2 * 10)

+ 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.

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

 

Operating ItemDescription
_ABCNTR Absolute Encoder Count
_ABSPEED Encoder Motor Speed in RPM
_ANAIN Analog Inputs
_BATAMPS Battery Amps
_BLCNTR Absolute Brushless Counter
_BLRCNTR Brushless Count Relative
_BLRSPEED BL Motor Speed as 1/1000 of Max
_BLSPEED BL Motor Speed in RPM
_CMDANA Internal Analog Command
_CMDPLS Internal Pulse Command
_CMDSER Internal Serial Command
_DIGIN All Digital Inputs
_DIGOUT Current Digital Outputs
_DIN Individual Digital Inputs
_FEEDBK Feedback
Operating ItemDescription
_FLTFLAG Fault Flags
_LOCKED Lock status
_LPERR Closed Loop Error
_MOTAMPS Motor Amps
_MOTCMD Actual Motor Command
_MOTPWR Applied Power Level
_PLSIN Pulse Inputs
_RELCNTR Encoder Count Relative
_RELSPEED Encoder Motor Speed as 1/1000 of Max
_STFLAG Status Flags
_TEMP Case & Internal Temperatures
_TIME Time
_VAR User Variable
_VOLTS Internal Voltages

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
Command ItemDescription
_ACCEL Set Acceleration
_DECEL Set Deceleration
_DOUT Set all Digital Out bits
_DRES Reset Individual Digital Out bits
_DSET Set Individual Digital Out bits
_ESTOP Emergency Shutdown
_GO Set Motor1 Command
_HOME Load Home counter
Command ItemDescription
_ACCEL Set Acceleration
_DECEL Set Deceleration
_DOUT Set all Digital Out bits
_DRES Reset Individual Digital Out bits
_DSET Set Individual Digital Out bits
_ESTOP Emergency Shutdown
_GO Set Motor1 Command

 

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

 

Config ItemDescription
_ACS Enable Ana Center Safety
_ACTR Analog Center
_ADB Analog Deadband
_AINA Analog Input Actions
_ALIM Motor Amps Limit
_ALIN Analog Linearity
_AMAX Analog Max
_AMAXA Action on Analog Input Max
_AMIN Analog Min
_AMINA Action on Analog Input Min
_AMOD Analog Input Mode
_AMS Enable Ana Min/Max Safety
_APOL Analog Input Polarity
_ATGA Amps Trigger Action
_ATGD Amps Trigger Delay
_ATRIG Amps Trigger Value
_BHL Encoder High Limit
_BHLA Encoder High Limit Action
_BHOME Brushless Counter Load at Home Position
_BLFB Speed and Position sensor feedback
_BLL Encoder Low Limit
_BLLA Encoder Low Limit Action
_BLSTD BL Stall Detection
_BPOL Number of Poles of BL Motor
_CLERD Close Loop Error Detection
_CLIN Command Linearity
_DFC Default Command value
_DINA Digital Input Action
_DINL Read Digital Inputs
_DOA Digital Output Action
_DOL Digital Output Action
_ECHOF Disable/Enabe RS232 & USB Echo
_EHL Encoder High Limit
_EHLA Encoder High Limit Action
_EHOME Encoder Counter Load at Home Position
_ELL Encoder Low Limit
_ELLA Encoder Low Limit Action
Config ItemDescription
_EMOD Encoder Operating Mode
_EPPR Encoder PPR
_ICAP Motor(s) Int Cap
_KD Set PID Differential Gain
_KDC1 KD Curve Points for Motor1
_KDC2 KD Curve Points for Motor2
_KI Set PID Integral Gain
_KIC1 KI Curve Points for Motor1
_KIC2 KI Curve Points for Motor2
_KP Set PID Proportional Gain
_KPC1 KP Curve Points for Motor1
_KPC2 KP Curve Points for Motor2
_MAC Motor(s) Desired Acceleration
_MDEC Motor(s) Desired Deceleration
_MMOD Motor Operating Mode
_MVEL Motor(s) Default Position Velocity
_MXPF Motor Max Power
_MXPR Motor Max Power
_MXRPM Motor RPM at 100%
_MXTRN Number of Motor Turns between Limits
_PCTR Pulse Center
_PDB Pulse Deadband
_PIDM Set PID Options
_PINA Pulse Input Actions
_PLIN Pulse Linearity
_PMAX Pulse Max
_PMAXA Action on Pulse Input Max
_PMIN Pulse Min
_PMINA Action on Pulse Input Min
_PMOD Pulse Input Mode
_PMS Enable Pulse Min/Max safety
_PPOL Pulse Input Polarity
_RWD RS232 Watchdog (0 to disable)
_SXC Sepex Curve Points
_SXM Minimum Field Current

 

SetTimerCount/GetTimerCount

These two functions used to set/get timer count.

SetTimerCount(, )
GetTimerCount()

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(, )
GetTimerState()

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).

Go to top