Link here

Your First Program

How to compile, download and run a multitasking C program

This Chapter will get you started using the Control-C language to program your QCard Controller, a compact and capable Single Board Computer (SBC) that is ideal for instrument control applications. It will guide you through the installation of the Mosaic IDE, an integrated editor, compiler, and terminal, and you’ll start up and talk with your controller. You’ll also:

  • Compile and download your first C application program using an example multitasking program that performs calculations using floating point math, stores data in arrays in the QCard Controller's extended memory space, and prints the results to the terminal;
  • Selectively execute any program function using the QCard Controller’s on-board debugging environment (called QED-Forth);
  • Use the QCard Controller’s built-in operating system to access extended memory;
  • Use the terminal to interact with a running multitasking application; and,
  • See how easy it is to set up a multitasking application.
 

Installing the Mosaic IDE and Control-C compiler

The Mosaic IDE, which includes the Control-C Compiler, a full-featured editor and communications terminal, is provided on an installation CD-ROM. To install it onto your PC, first insert the Installation CD-ROM into your CD Drive. If the installer does not launch automatically, browse to your computer’s CD drive using the ‘My Computer’ icon and double click on ‘Setup.exe’ to manually launch the installer.

We recommend that you use the default installation directory ("C:\Mosaic\") and choose ‘Typical Setup’ when asked. If you wish to install into a different directory, you may type in any pathname provided that it does not contain any spaces. The ‘Custom’ setup option can be used if another version of either TextPad (the editor used within the Mosaic IDE), the Mosaic Terminal (previously called QED-Term), or an earlier version of the Mosaic IDE has already been installed. However, the Mosaic IDE requires all of its components to work properly. Please Contact Us if you have any questions.

When the installation is complete, you will need to restart your computer. Be sure to choose ‘Yes’ when asked to restart – if you don’t, the installation may not complete properly. If you choose ‘No’ and restart later we recommend that to assure a full restart you fully shutdown your computer and then turn it back on; lesser restarts don’t always restart fully.

You are now ready to talk with your QCard Controller!

 

Turning on your QCard Controller

Familiarize yourself with the locations of the power and serial connectors as shown in Chapters 1 and 2. After finding them follow these steps to turn on your system and establish communications with the 68HC11 processor on your QCard:

  1. Connect the female end of the 9-Pin serial communications cable to your computer terminal’s RS-232 serial communications port and the male end to the primary serial port on the PowerDock. If you are not using a PowerDock, but instead are directly connecting to the QCard Controller, you’ll need a 10-pin to dual DB-9F cable (Mosaic Part No. QED-COM-CABLE-9). You can use any of your PC’s COM ports. COM2 is usually available, but some PCs only have COM1 available. If your computer does not have an RS-232 serial port, low cost USB-to-RS-232 serial cables are available; contact Mosaic Industries for details.
  2. Power up your PC computer or terminal.
  3. You should check the configuration of your Windows communications drivers:
    1. On your PC go to the device manager dialog box by double clicking "System" in the "Control Panel", clicking the "Hardware" tab, and clicking the "Device Manager" button.
    2. In the list of devices open up the list of "Ports" and double click on "Communications Port (COM2)". (If COM2 is tied up with another service, such as a fax/modem, you may want to use COM1 instead.)
    3. You’ll now have a dialog box called "Communications Port (COM2) Properties". Click the general tab and make sure you have these settings:
      • Baud Rate = 19200
      • Data Bits = 8
      • Parity = None
      • Stop Bits = 1
      • Flow Control = Xon/Xoff
  4. We recommend that you use Mosaic Terminal, the terminal program that comes with the Mosaic IDE. You can start the terminal by double clicking the Mosaic IDE executable (the primary application of the Mosaic IDE) and choosing the terminal toolbar button which looks like this:

    Terminal Icon

    (The appearance of this and other toolbar icons may change in subsequent versions of the Mosaic IDE.) You can also start the terminal by double clicking the application "MosaicTerminal.exe".

    The terminal starts using COM2 by default at a speed of 19200 baud, no parity, and 1 stop bit. Xon/Xoff flow control is enabled, and the file transfer options are set so that the terminal waits for a linefeed (^J) character before sending each line (this is very important). You can use any other terminal program, but it must be configured with these same settings. If you use another terminal program, you must specify that it use the linefeed character as its prompt character. It might be denoted as LF, ^J, ascii decimal 10, or ascii hex A.

    If your PC is set up to use a COM port other than COM2 Mosaic Terminal will respond with a warning box saying "Invalid port number". If so, just go to the Mosaic Terminal menu item "Settings→Comm→Port" and choose the COM port you chose when configuring Windows in step 3. above.

  5. Verify the baud rate of the Mosaic Terminal by going to "Settings→Comm→Baud Rate" and making sure that 19200 is selected. This is the baud rate used to communicate with the QCard Controller. If the baud rate is incorrect, garbled characters may appear in the terminal when you try to communicate with the controller.
  6. Plug the QCard Controller’s power supply into a 110 VAC outlet. European users will need a power transformer for changing European 220 VAC to 110 VAC. Insert the power supply output plug into the power jack on the PowerDock and turn the power switch ON by moving the power switch towards the power jack.
    1. You should now see the following response:

      Coldstart QED-Forth V4.4x
    2. If you hit the enter key while the cursor is in your terminal window you should see the QCard Controller respond with,

      ok

The serial communications responses indicate that your QCard Controller is now working!

 

If something doesn’t work

If no message appears on your terminal there’s something wrong, so:
  1. Verify that power is being properly applied to the controller.
  2. Verify that the serial cable is properly connected.
  3. Check the terminal configurations of the Mosaic Terminal (using the menu item "Settings → Comm"), and recheck the communications properties of the Windows communications port.
  4. Perform a "special cleanup".
Doing a "Special Cleanup"

If you ever need to return your QCard Controller to its factory-new condition, just do a Special Cleanup:

  1. With the power on, install jumper J1,
  2. press the reset button,
  3. then remove the jumper.

This procedure will remove any application programs and reinitialize all operating system parameters to their factory-new condition.

If you still are having trouble, email or give us a call.

 

Using the Mosaic IDE

Using the editor and compiler

The Mosaic IDE has two main components, the TextPad editor, which includes the Control-C compiler, and the Mosaic Terminal serial terminal program, both of which you’ll find in the default directory "C:\Mosaic\":

TextPad is a fully featured and highly configurable text and program editor. You’ll use it to write and compile your code. All of the functions of the C compiler tools are available through the controls in TextPad. You can launch TextPad from the ‘Mosaic IDE’ group in the ‘Programs’ section of your Windows ‘Start’ menu. For convenience, you may want to place a shortcut to it on your desktop or on your Windows Taskbar.

Mosaic Terminal is a serial communications terminal that allows you to interactively control your controller over its RS-232 interface. You’ll also use it to download your compiled C programs or Forth source code for compilation into the memory of the QCard Controller. Mosaic Terminal may be launched from the ‘Mosaic IDE’ group within ‘Start→Programs’, but it is also available from within TextPad, either from the ‘Tools’ dropdown menu or by clicking the terminal icon on TextPad’s toolbar.

You can type characters directly into the terminal window, and they will be accepted by the QCard Controller’s line editor and interpreter. This mode of interaction is convenient when debugging or typing short code fragments. If you are sending source code to the QCard Controller, it is best to create a file first. The file can be saved to disk to provide a record of your work, and the terminal program can be used to download the file to the QCard Controller. You can also use the terminal to record your debugging sessions and save them as a file on disk.

 

The TextPad tool bar

IDE Toolbar

Along with the standard tools you expect in a text editor you’ll find some custom tools available in the toolbar that you’ll use to compile and download your programs. Each of these tools is also accessible in the ‘Tools’ dropdown menu of TextPad. For C programmers the Debug icon calls the C compiler and assembler only, the Single-Page Compile icon performs a standard build of your program, and the Multi-Page Compile icon performs a multi-page memory model build of your program. Forth programmers won’t need to use these tools. Both C and Forth programmers will find the Terminal icon useful; it launches the Mosaic Terminal program. Each of these tools is described in more detail below.

Embedded Debugging The ‘Debug Tool’ Finds Syntax Errors in C Programs

The Debug Tool, designated by the "Magnifying Glass" icon, invokes the Control-C compiler. The Debug Tool, designated by the "Magnifying Glass" icon, invokes the compiler and assembler only – it does not produce downloadable code. Use it to quickly check the syntax of a program and find compilation errors without performing the full build which would be needed to download the program into the microcontroller.

microcontroller c compiler The ‘Single-Page Compile Tool’ Compiles and Makes a Downloadable Single-Page C Program

The Single-Page Compile Tool, designated by the "Single-Page" icon is also for C programmers. It controls how C programs are linked and stored in memory. Forth programmers do not need to use it. The Single-Page Compile Tool, designated by the "Single-Page" icon, performs a standard, single-page memory model build of your program. If you are compiling a program whose compiled size does not exceed 32 Kbytes of memory you should use this mode for fastest execution. Although this program size is sufficient for many applications, you may need to use the multi-page build if your application grows beyond 32 K. If you see the following warning printed in the compiler output, then you must switch to the multi-page memory model build (using the Multi-Page Make icon):

WARNING: Input section ".doubleword" from ‘progname.o11’ is not used !

paged memory microcontroller c compiler The ‘Multi-Page Compile Tool’ Compiles and Makes a Downloadable Long C Program

The Multi-Page Compile Tool, designated by the "Multi-Page" icon, invokes the C compiler’s multi-page build mode. Programs compiled in this mode may be many pages in length limited only by the amount of FLASH installed in the QCard Controller. It is always a good programming practice to break large projects into multiple smaller source code files for organization, and the multi-page build also uses this organization for distributing the compiled program across multiple 32 Kbyte pages. Thus, no source code file may contain more than 32 Kbytes worth of compiled source code or the above warning will be issued and the program will not run. A more detailed description of this behavior is available in Chapter 4.

You may wonder why there are both "Single-Page" and "Multi-Page" compile modes. The reason is that C function calls between pages take just a little longer to execute (calls to functions on a different page take 49 microseconds while those on the same page or to common memory take only 11.5 or 13.75 microseconds, respectively). Because most function calls are to functions on the same page or to common memory, page changes are rare; the average execution speed of multi-page C applications is still quite fast.

Serial Terminal ‘Mosaic Terminal’ Communicates with Your Product

The Terminal icon launches the communications program, Mosaic Terminal. When you launch Mosaic Terminal for the first time, check the communications settings (Settings→Comm) to verify that the serial port is set correctly for your computer.

 

Your first C program

Now that we’ve learned about the QCard Controller's hardware, established serial communications, and installed the Mosaic IDE on the PC, it’s time to compile, download and execute a C program. We’ll also explore the QCard Controller’s on-board operating system and use it to interactively debug a program.

 

Compiling a program

In this section we'll be running a simple program that does some computation and communicates its results on the serial port. The program is one of several examples for use with the Control-C IDE in the "\Mosaic\Demos_and_Drivers\Misc\C Examples" directory. Let’s compile, download, and run it.

Start TextPad, and open the source-code file "getstart.c" from the C_Examples directory. You should see the source code in an open window – browse through it to get a feel for it. You’ll see that the final routine in the file is called main(); it’s the top-level executable program. The first routine within main() that is called when the program starts is InitVars(). Note that in the run-from-place applications of embedded systems it’s important to initialize all variables with a run-time procedure when the program starts. Variables that are initialized when the program is compiled are not automatically initialized when the program runs; you should have a runtime routine in your code that does that.

Clicking on the Single-Page Compile icon will compile and produce a downloadable form of the program, named "getstart.dlf". A new window named ‘Command Results’ will appear so that you can watch the compilation process. When compilation has finished, you can scroll the Command Results window up and look for warnings, which don’t prevent creating a valid download file, and errors, which do. You should see two warnings near the beginning:

GETSTART.C(126): Warning: Expression is always TRUE !
GETSTART.C(197): Warning: Symbol 'unused_variable' is never used in function 'main' !

We deliberately inserted into ‘main’ a variable named unused_variable that is never used in the function. If you double click on an error or warning line in the command results, TextPad will jump to the corresponding line in the affected source file. Despite the warnings, the program should have compiled successfully; the command results will end with:

Qcc-> Creating QED Download File: getstart.dlf''
Tool Completed Successfully

You can quickly switch between the Command Results window and your source code file either by hitting Ctrl-Tab, or by clicking on the file tabs at the bottom of the TextPad window.

The file named "getstart.dlf" is ready to be downloaded to the microcontroller using the Mosaic Terminal program.

 

Downloading and running the program

If it is not already open, launch Mosaic Terminal either from the ‘Start’ menu or using the TextPad toolbar or dropdown menu. It’s most convenient to use the Terminal icon on the TextPad toolbar. You should be able to hit enter at the Mosaic Terminal prompt and see the ‘ok’ response with the microcontroller plugged in and turned on. If this is not the case, check your communications settings and cabling.

Now, select ‘File → Send File’ from the Mosaic Terminal menu and enter the "\Mosaic\Demos_and_Drivers\Misc\C Examples" directory, or wherever you compiled the program. Set the file type to "Download Files (*.dlf)" and select "getstart.dlf". You will see various commands and hex data scrolling on the screen as the file is downloaded to the microcontroller. When the download is complete, the text will turn from gray to green to indicate that it is finished. Now, it’s time to run your program.

To execute the top level function of your code, simply type ‘main’ and press enter,

main↓

The ‘Enter’ key is represented by the ↓ symbol in the line above.

The getstart program will respond with:

Starting condition:
The radius is 0; the circular area is 0.
ok

While on its face that doesn’t seem a very impressive response, you’re running your first program! This particular example program uses multitasking. The program runs a background task called CalculationTask continuously, incrementing a radius variable and using it to compute a new area. The program is running in its own task, leaving the communications task free so you can continue to interact with the controller.

You will notice that you can hit enter, and use the interactive debugging capabilities even though the program is still running. For example, try executing the following function interactively from the terminal:

Announce( )↓

Note that you must type the space after the ( character. Each time you execute this function you’ll notice that the output is different, as the radius is being continuously incremented by the background task. Now try executing,

Nap( )↓

which puts the background CalculationTask ASLEEP. If you again execute

Announce( )↓

several times, you will notice that the radius and area are no longer being updated by the CalculationTask. To wake up the CalculationTask again, type

Wakeup( )↓

and notice that the calculation is again being performed by the task.

You may want to stop the program; in particular you’ll need to stop it before attempting any new downloads. This can be done most easily by simply entering ‘warm’ at the microcontroller’s prompt. The warm restart causes a soft reset to occur, terminating any background tasks that may be running.

After having run this program, you may want to play with the other example programs in the "\Mosaic\Demos_and_Drivers\Misc\C Examples" directory. We strongly recommend that you compile these programs and work through the examples as suggested in the text of this manual. This will provide you with a thorough "hands-on" introduction to the Control-C programming environment.

 

Interactively debugging your program

We have seen how to interactively call the main() function from the terminal to execute our entire program; most C development environments let you do this. But the QCard Controller’s operating system makes it easy to interactively execute any designated function in your program. By simply preceding a function definition or prototype with the _Q keyword (we chose "_Q" as a unique keyword that suggests QED), you can ensure that the function will be interactively callable from your terminal.

 

An example: Announce( ) displays an area and radius

For example, to display a summary of the current values of the radius and calculated circular area variables, we would like to call the function Announce( ).

Using the editor, look near the top of the GETSTART.C file and you’ll see that its definition is:

_Q void Announce(void)
{
    printf( "\nThe radius is %6u; the circular area is %5.4g.\n", radius, area );
}

The void keywords indicate that the Announce( ) function does not return a value, and does not expect any input parameters to be passed to it.

The _Q declarator instructs the compiler that we want to be able to interactively call this function using the on-board QED-Forth interpreter. The names and execution addresses of all functions defined with the _Q designator are placed in the .DLF download file so that QED-Forth will recognize them and will be able to interactively execute them.

The printf() function invoked in Announce( ) prints the specified string to the serial1 port. The parameters of the printf() function are well defined by the ANSI standard, and are described in many excellent texts. Briefly, the \n is an escape sequence that instructs printf to insert a newline at the designated places in the string. The % characters are formatting symbols that tell the compiler to substitute the listed arguments (in this case, the radius and area) for the % sequences at runtime. The %6u sequence tells the compiler to display the radius as an unsigned decimal number with a minimum field width of 6. The %5.4g sequence tells the compiler to display the area using either decimal or exponential notation with a precision of 4 decimal places to the right of the decimal point, and a minimum field width of 5.

The printf() function in Control-C differs from the ANSI standard in one respect: the maximum length of a printed string is limited to 80 characters instead of the standard 255 characters. This limitation also applies to the related functions named sprintf() (which writes a string to a buffer) and scanf() (which inputs a string). Of course, you can handle strings longer than 80 characters by using multiple calls to these functions.

 

Interactively calling Announce( )

To interactively call this function, simply type at your terminal

Announce( )↓

followed by a carriage return (indicated by the arrow above). Spaces are important to the QED-Forth interpreter which processes this command; make sure that there is no space between the function name Announce and the opening parenthesis (, and there must be at least one space after the opening parenthesis. If QED-Forth does not recognize your command, it will repeat what you typed followed by a "?" character and wait for another command, so you can try again. The case of the letters does not matter: you can use all uppercase, all lowercase, or any combination when typing commands for the QED-Forth interpreter.

After calling Announce( ), you should now see the message

The radius is 0; the circular area is 0.

on your screen, except that the printed values of the radius and area will correspond to the values they had when you executed the "WARM" command to stop the calculations. Then you will see an additional line of text starting with "Rtn:" that summarizes the return value of the function in several formats, followed by the "ok" prompt. Because the Announce() function has no return value, the return value summary is not relevant. The "ok" prompt indicates that QED-Forth has successfully called the function and is now ready to execute another command.

If you make a mistake while typing a command, just type "backspace" or "delete" to erase as many characters as necessary on the current line. Once you’ve typed a carriage return, though, QED-Forth executes your command. You can’t edit a command that was entered on a previous line. If you type an incorrect command and then type a carriage return, you may receive the "?" error message which means that QED-Forth does not understand the command you typed. If this happens, you can usually just re-type the command line and continue.

 

Area calculation

The next function defined in GETSTART.C is called IncrementRadius(). This simple function increments the radius variable, and resets it to 0 when it exceeds the MAX_RADIUS constant. As described below, IncrementRadius() is called from the infinite loop in CalcForever(); this results in the radius taking on all integer values between 0 and 1000.

The next function defined in the GETSTART.C file calculates the area of a circle; its definition is:

_Q float CalcArea( uint radius )
{
    return PI * radius * radius;
}

As described above, the _Q designator flags this function as one that can be called interactively. The "float" keyword declares that the function returns a floating point value, and the parameter list tells us that the function expects a single unsigned integer (uint) as its input. (Note: uint and other useful type abbreviations and declarations are defined in the TYPES.H header file in the \MOSAIC\FABIUS\INCLUDE\MOSAIC directory.)

To interactively test this function with an input radius of 5, type at your terminal

CalcArea( int 5)↓

followed by a carriage return. QED-Forth uses spaces as delimiters; consequently, you must type at least one space after the ( character and after the "int" keyword. You should see something like the following response at your terminal:

Rtn: 17053 5242 =0x429D147A=fp: 78.54

This line summarizes the returned value in several formats, including decimal or hexadecimal 16-bit values, 32-bit hexadecimal, and floating point. Because the CalcArea() function returns a floating point (fp) value, the final number on the line, labeled

=fp: 78.54

is the relevant return value. Indeed, 78.54 is the area of a circle that has the specified radius of 5. You can execute the function with any integer input as the radius, and verify that it returns the correct circular area. This capability enables interactive testing of the function over its allowed range of input values. Such thorough function-by-function testing of a program facilitates rapid development of reliable programs.

In the next chapter the interactive debugging process will be explored in more detail. You will learn how to examine the values of static variables and Forth arrays, pass parameters by value or by reference, generate hexadecimal and ascii dumps of memory contents, and modify the contents stored in variables and Forth arrays.

 

Restrictions on the use of _Q

Nearly every function in the many sample programs in the \MOSAIC\DEMOS_AND_DRIVERS\MISC\C EXAMPLES directory is declared with the _Q keyword to facilitate easy debugging.

There are, however, two restrictions associated with the use of the _Q declarator.

  1. A function defined using the _Q keyword cannot use (ellipsis) in its parameter list; rather, the number of input parameters must be specified when the function is defined. If you try to define the _Q function with an ellipsis as an input parameter, the compiler will issue a warning and remove the _Q specifier, so you will not be able to interactively call the function during debugging.)
  2. The _Q function cannot be called via a function pointer if the function accepts input parameters. In other words, do not use the _Q declarator if:
    1. You need to call the function using a function pointer; and,
    2. The function accepts input parameters.


This restriction does not affect many functions. Any function declared using _Q can always be called in the standard way (that is, by invoking the function name followed by parentheses that contain any input parameters). Moreover, any _Q function can be called indirectly via a function pointer (by passing its name without any parentheses) if the function’s input parameter list is "void".

 
This page is about: Edit, Compile, Download, Test, and Run C-language Program, Using RAM and Flash Memory, Using Interactive Debugger, Using Paged Memory and Arrays, Multitasking, Write Protecting, Autostart on Powerup – How to compile, download, interactively debug, run, write protect and autostart a multitasking C program on the QCard Controller. write protection, autostarting, task, Forth
 
 
Navigation