Support » Tic Stepper Motor Controller User’s Guide » 12. Writing PC software to control the Tic »
12.12. Example code using the C++ API
The code below uses the C++ API provided by the Tic software to send and receive data from a Tic over USB. This code is written in C++ and works on Windows, Linux, and macOS. The code here is simpler than the equivalent C example in Section 12.11 because the Tic’s C++ API automatically frees allocated resources and converts errors into exceptions.
If you have compiled the Tic software from source and installed it on a Unix-like system (including MSYS2 on Windows), and copied the code below to a file named code.cpp, you should be able to compile the code below by running this command in a shell:
g++ code.cpp $(pkg-config libpololu-tic-1 --cflags --libs)
You might notice that the Tic only performs the desired movement for about a second before it stops moving and the red LED turns on, indicating an error. This is because of the Tic’s command timeout feature: by default, the Tic’s “Command timeout” error will happen if it does not receive certain commands periodically (see Section 5.4 for details), causing the motor to stop. You can send a “Reset command timeout” command every second to get around this, or you can disable the command timeout feature using the Tic Control Center: uncheck the “Enable command timeout” checkbox in the “Serial” box.
// Uses the Tic's C++ API to send and receive data from a Tic.
// NOTE: The Tic's control mode must be "Serial / I2C / USB".
#include <iostream>
#include <tic.hpp>
// Opens a handle to a Tic that can be used for communication.
//
// To open a handle to any Tic:
// tic_handle * handle = open_handle();
// To open a handle to the Tic with serial number 01234567:
// tic_handle * handle = open_handle("01234567");
tic::handle open_handle(const char * desired_serial_number = nullptr)
{
// Get a list of Tic devices connected via USB.
std::vector<tic::device> list = tic::list_connected_devices();
// Iterate through the list and select one device.
for (const tic::device & device : list)
{
if (desired_serial_number &&
device.get_serial_number() != desired_serial_number)
{
// Found a device with the wrong serial number, so continue on to
// the next device in the list.
continue;
}
// Open a handle to this device and return it.
return tic::handle(device);
}
throw std::runtime_error("No device found.");
}
int main()
{
try
{
tic::handle handle = open_handle();
tic::variables vars = handle.get_variables();
int32_t position = vars.get_current_position();
std::cout << "Current position is " << position << ".\n";
int32_t new_target = position > 0 ? -200 : 200;
std::cout << "Setting target position to " << new_target << ".\n";
handle.exit_safe_start();
handle.set_target_position(new_target);
}
catch (const std::exception & error)
{
std::cerr << "Error: " << error.what() << std::endl;
return 1;
}
return 0;
}












