Tutorial: Building a HelloWorld Application (Step 4)

Implementing Application Functionality

For the application functionality we define a class Application in a file with the name Application.h. The file is placed in directory src, as it can be used without modifications in the simulation environment as well as on a real target. It may look like this:

#ifndef APPLICATION_H_
#define APPLICATION_H_
#include "Platform.h"
#include <Core/Base/TGlobalPtrBase.h>

class Application: public redBlocks::Core::TGlobalPtrBase<Application>  // (1)
{
  public:
    Application() : mLedState( false )          // (2)
    {
      Platform::DiPushButton::enableCallback(); // (3)
    }

    void run()                                  // (4)
    {
      while ( true )
      {
      }
    }

    void switchLed()                            // (5)
    {
      mLedState = !mLedState;
      Platform::DoLed::setOutput ( mLedState ); // (6)
    }

    private:
    /**
     * the current Led state
     */
    bool mLedState;                             // (7)
};

#endif // APPLICATION_H_

The current state of the Led is maintained in a boolean member variable mLedState (7). This member variable is initialized with false (2).

In the constructor we enable callbacks for the PushButton input (3). Thus, the method switchLed() (5) will be called, when a falling edge is detected on the PushButton signal (we will see in a moment how this is achieved). This method toggles the current Led state and sets a new value for the Led output (6).

In order to easily access the single instance of class Application that is built during construction, the class is derived from redBlocks::Core::TGlobalPtrBase (1). By deriving from this class template, Application inherits the method getInstanceRef(), via which the single instance of class Application can be conveniently accessed (which is handy, in order to call methods of this instance from interrupt context as we will see later).

In our simple example, the method Application::run() will just loop forever without doing any other actions (4). Please note, that this is very inefficient, as the processor should better enter sleep mode instead, but we want to keep our example very simple for now. However, when running this HelloWorld application on a single core host machine, this approach might slow down your computer considerably.

Application initialization

The class Application needs to be constructed during system startup. So we need to add the following code to the main() routine in project/sim/host/Workbench/main.cpp.

// @todo: application specific startup code goes here
Application app;
app.run();

We also need to include the file Application.h in main.cpp, so add the following line to the include list of main.cpp:

#include <Application.h>

The rest of the code in the file is responsible to set up the simulation environment and does not need to be changed as long as the simulation is running on a Windows computer.