APIs, concepts, guides, and more
rttaskfunctions.cpp
1
10#include "rttaskglobals.h"
11
12#include <cstdlib>
13#include <ctime>
14
15#include <iostream>
16
17using namespace RSI::RapidCode;
18using namespace RSI::RapidCode::RealTimeTasks;
19
21// This task initializes the global data and the random number generator
22RSI_TASK(Initialize)
23{
24 data->counter = 0;
25 data->average = 0;
26
27 std::srand(std::time(nullptr));
28}
30
32// This task increments the counter in the global data
33RSI_TASK(Increment)
34{
35 data->counter += 1;
36}
38
40// This task randomly moves the axis back and forth
41RSI_TASK(RandomWalk)
42{
43 int random = std::rand() % 2;
44 double step = random ? 0.05 : -0.025; // Randomly increment or decrement the average
45 data->average += step;
46 data->counter += 1;
47
48 RTAxisGet(0)->MoveSCurve(data->average);
49}
51
53// This task reads the analog input value from the network node, scales it to
54// a value between 0 and 1, and stores it in the targetPosition variable
55RSI_TASK(CalculateTarget)
56{
57 constexpr int NODE_INDEX = 0; // The network node with the analog input
58 constexpr int ANALOG_INDEX = 0; // The index of the analog input to use
59 constexpr int ANALOG_MAX = 65536; // Max value of the analog input
60 constexpr int ANALOG_ORIGIN = 42800; // The value to treat as the "origin" of the analog input
61
62 auto networkNode = RTNetworkNodeGet(NODE_INDEX);
63
64 // Read the raw analog input value
65 int32_t analogInVal = networkNode->AnalogInGet(ANALOG_INDEX);
66
67 // Shift the value by the origin
68 int32_t shiftedVal = analogInVal - ANALOG_ORIGIN;
69
70 // Make sure the value is between 0 and ANALOG_MAX using modulo
71 int32_t modVal = (shiftedVal + ANALOG_MAX) % ANALOG_MAX;
72
73 // Scale the value to be between 0 and 1 and store it in targetPosition
74 data->targetPosition = double(modVal) / ANALOG_MAX;
75}
77
79// This task moves the axis to the target position if it is not within the tolerance
80// of the target position already.
81RSI_TASK(FollowTarget)
82{
83 constexpr int AXIS_INDEX = 1; // The index of the axis to move
84 constexpr double TOLERANCE = 0.02; // The tolerance for the position difference
85
86 auto axis = RTAxisGet(AXIS_INDEX);
87 // Check if the axis is within the tolerance of the target position
88 if (abs(axis->ActualPositionGet() - data->targetPosition) > TOLERANCE)
89 {
90 // Move the axis to the target position
91 axis->MoveSCurve(data->targetPosition);
92 }
93}