Veethree D7 SDK
Loading...
Searching...
No Matches
I/O library examples

Please also have a look at the details page for I/O: Analog, Digital, PWM to get a better understanding of what functionality is available on the D7.

Analog Read

CLI Analog Read

The example code in cli-analog.cpp demonstrates:

  • How to initialize the analog IO library
  • How to add a resistive sensor
  • How to read a value from it

Test harness

This example uses pin "VRSNS_0", which corresponds to pin 6 on the AMPSEAL 35-pin connector on the D7, to measure an external resistance. Refer to a. 1-wire resistance sensing (using VRSNS pins and AGND pin) for wiring details. Build and deploy this app to the target and run it.

CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(
cli-analog-read
VERSION 0.1
LANGUAGES CXX)
# Set C++ standard to C++17
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 17)
# Project name
set(APPNAME cli-analog-app)
# Find VSDK packages
find_package(vsdk REQUIRED CONFIG COMPONENTS libio utils)
# Add executable and link against VSDK libraries
add_executable(${APPNAME} cli-analog.cpp)
target_include_directories(${APPNAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(${APPNAME} PRIVATE vsdk::libio vsdk::utils)
## Deploy to target from Qt Creator
include(GNUInstallDirs)
install(TARGETS ${APPNAME}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
@ analog
Analog module.
Definition log.h:38
Any entities that belong to the utils library.
Any entities that belong to the Veethree SDK libraries.
Definition can_adapter.h:11
cli-analog.cpp
#include <cassert>
#include <iostream>
#include <libio/analog.h>
// An example of initializing the analog IO library, adding a resistive sensor
// and reading a value from it.
int main() {
using namespace vsdk::io;
// The pins available to the analog IO library can be configured to be used as
// sensors for different types of readings: resistance, voltage, temperature.
//
// A sensor can be comprised of multiple pins. For instance:
// - a four-wire RTD sensor uses 3 user-selected pins and the R_REF pin
// implicitly
// - a thermocouple sensor uses 2 user-selected pins
// - a two-wire resistive sensor uses 1 user-selected pin and the R_REF pin
// implicitily
// - a one wire resistive sensor uses 1 user selected pin and the PWR_IN- pin
// implicitly
//
// To build valid pin configurations, you will need to use a profile_builder.
profile_builder builder{};
// Add resistive sensor
// - "rsns0" -> name for the sensor (arbitrary). This is used to reference the
// sensor in the configuration.
// - analog::pin_t::vrsns0 -> physical pin vrsns0
//
// The maximum number of sensors that can be registered in a profile is
// device-specific. Please refer to the data sheet.
constexpr auto sns_name = "rsns0";
if (!builder.add_one_wire_resistive_sensor(sns_name, analog::pin_t::vrsns0)) {
// Adding an analog sensor will fail if the configuration is invalid.
// For example, if the same pin is used for 2 different sensors.
std::cerr << fmt::format("Failed to add sensor '{}'\n", sns_name);
return EXIT_FAILURE;
}
// Construct the analog profile and use it
// to initialize the analog IO interface
//
// Note: sensors remain registered until analog::instance()->init() is called
// with a new analog profile
auto analog_profile = builder.to_profile();
auto lib_analog = analog::analog::instance();
// The init method will throw in the case of an invalid profile or if the
// configuration fails to be applied.
//
// Most of the configuration issues should be caught just by checking whether
// the sensor has been registered successfully in the builder.
lib_analog->init(analog_profile);
// To be able to read from a sensor, you must get its handle using the name
// with which it was registered (line 31)
//
// Similar to open(), the handle is just a number. If the sensor name was not
// found, the handle returned will be -1.
auto rsns_handle = lib_analog->get_handle(sns_name);
assert(rsns_handle != -1);
// This call can throw a vsdk::io::libio_error only if the handle cannot be
// found in the current configuration.
//
// In any other error case, the status of the returned value will be !=
// io_status::ok.
const auto reading = lib_analog->read_from(rsns_handle);
if (reading.status != io_status::ok) {
std::cerr << fmt::format("Error while reading from {}: {}\n", sns_name,
to_string(reading.status));
return EXIT_FAILURE;
}
// Read was successful. The value can be used
fmt::println("{} (vrsns0): {:.2f} ", sns_name, reading.value,
to_string(reading.unit));
return EXIT_SUCCESS;
}
The analog interface.
static analog * instance()
Get a pointer to the singleton instance.
This is used to provide a valid profile for the analog class.
Definition profile_builder.h:41
bool add_one_wire_resistive_sensor(std::string label, analog::pin_t positive_a)
Add a one wire resistive sensor.
analog::analog_profile to_profile()
Export the profile.
std::tuple< std::vector< sensor >, std::vector< function_channel > > analog_profile
Representation of an analog profile.
Definition analog.h:32
Any entities that belong to the IO library.
constexpr const char * to_string(io_status status)
Definition io_common.h:82
@ ok
Operation successful.
Definition io_common.h:19
The profile builder interface.

GUI Analog Read

UI example project using QML and the D7 SDK

This is a minimal starter project that uses Qt with QML to create a UI application on the D7.

Scope of the example

The example demonstrates:

  • a minimal QML application that displays a graphical user interface on the D7
  • reading from multiple analog inputs on a separate thread to avoid blocking the UI main thread

It does not demonstrate:

  • installing the D7 SDK
  • adding D7 SDK as a Qt Kit in Qt Creator (or any other editor)

Dependencies

  • Qt 6.10.2 - Requires QtQuick
  • Building for the host requires the Qt version installed on the host matches the version in the D7 SDK, currently 6.10.2.

Build instructions

Please refer to the minimal CLI example. The instructions to configure and build the project are identical.

Notable remark

Reading from the sensors on a separate thread

Reading from a sensor is slower than accessing a regular file, as such it should not be done on the main UI thread to avoid blocking it and making the UI lag.

To help with that, an intermediary store is needed to hold the values such that the UI can access them without waiting to read directly from the sensors. In this example, the SensorModel::_cache mapping is used as that intermediary store.

Since the store is accessed from different threads, it is protected by a mutex. Qt classes and methods are reentrant, therefore care should be taken with the type of mutex. A regular std::mutex would throw an exception if it were locked twice recursively (due to reentrancy) on the same thread. Because of that, a std::recursive_mutex is a safer choice for the UI thread.

Test harness

This example uses all the analog sensor pins (VRSNS_0 through VRSNS_5) as resistance sensors.

To set up the test harness, you should connect 6 resistances on the target device. Please refer to a. 1-wire resistance sensing (using VRSNS pins and AGND pin) to connect a resistor to each one of pins 6 (VRSNS_0), 17 (VRSNS_1), 5 (VRSNS_2), 16 (VRSNS_3), 4 (VRSNS_4), 15 (VRSNS_5) of the AMPSEAL 35-way Connector. Please refer to I/O interfaces to locate relevant pins on the AMPSEAL 35-pin and 23-pin connectors.

CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(
qml-analog-read
VERSION 0.1
LANGUAGES CXX)
# Project name
set(APPNAME qml-analog-app)
# Set C++ standard to C++17
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 17)
# Find QT and VSDK packages
find_package(Qt6 REQUIRED COMPONENTS Quick)
find_package(vsdk REQUIRED CONFIG COMPONENTS utils libio)
qt_standard_project_setup(REQUIRES 6.8)
qt_add_executable(${APPNAME} main.cpp)
qt_add_qml_module(
${APPNAME}
URI
qml_analog_read
VERSION
1.0
QML_FILES
ui/Main.qml
ui/SensorsView.qml
SOURCES
sensor_model.cpp)
target_include_directories(${APPNAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(${APPNAME} PRIVATE Qt6::Quick vsdk::utils vsdk::libio)
## Deploy to target from Qt Creator
include(GNUInstallDirs)
install(TARGETS ${APPNAME}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
sensor_model.h
#ifndef SENSOR_MODEL_H
#define SENSOR_MODEL_H
#include <QAbstractTableModel>
#include <atomic>
#include <condition_variable>
#include <libio/analog.h>
#include <mutex>
#include <thread>
#include <unordered_map>
class SensorModel : public QAbstractTableModel {
Q_OBJECT
public:
explicit SensorModel(QObject *parent = nullptr);
~SensorModel() override;
// Implementations for QAbstractTableModel
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index,
int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const override;
private:
QString sensorName(int idx) const;
QString sensorValue(int idx) const;
QString sensorUnit(int idx) const;
void configureSensors(vsdk::io::profile_builder &builder);
void readSensors();
static const std::vector<QString> _sensors;
struct HandleAndReading {
int8_t handle = -1;
};
mutable std::recursive_mutex _mtx;
std::condition_variable _cv;
std::atomic_bool _stopReading;
std::thread _sensorReaderThread;
std::unordered_map<QString, HandleAndReading> _cache;
analog::analog *_analog;
};
#endif // SENSOR_MODEL_H
Anything related to configuring or reading analog sensors.
io_result< double > analog_result
Analog result type.
Definition io_common.h:67

Events

The example code in cli-analog-events.cpp demonstrates:

  • How to set up event handlers
  • How to configure analog notifications, using different schedules and event criteria
  • How to start and stop notifications

This example is based on analog reading, but it is also possible with PWM, 4-20 mA and digital inputs.

Test harness

This example uses pin "VRSNS_0", which corresponds to pin 6 on the AMPSEAL 35-pin connector on the D7, to measure an external resistance.

You will need to connect a resistance of known value between pin 6 and pin 14 (RREF) on the AMPSEAL 35-pin connector before running the example on the target device.

Please refer to I/O interfaces to locate relevant pins on the AMPSEAL 35-pin.

CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(
cli-analog-events
VERSION 0.1
LANGUAGES CXX)
# Set C++ standard to C++17
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 17)
# Project name
set(APPNAME cli-analog-events-app)
# Find VSDK packages
find_package(vsdk REQUIRED CONFIG COMPONENTS libio utils)
# Add executable and link against VSDK libraries
add_executable(${APPNAME} cli-analog-events.cpp)
target_link_libraries(${APPNAME} PRIVATE vsdk::libio vsdk::utils)
## Deploy to target from Qt Creator
include(GNUInstallDirs)
install(TARGETS ${APPNAME}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
cli-analog-events.cpp
#include <libio/analog.h>
#include <atomic>
#include <csignal>
#include <limits>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace vsdk::io;
using namespace std::chrono_literals;
// Global flag for program termination
std::atomic_bool should_stop = false;
std::condition_variable stop_cv;
std::mutex should_stop_mtx;
void stop(int signal) {
if (signal == SIGTERM || signal == SIGINT) {
fmt::println("Stopping analog event monitoring...");
stop_cv.notify_one();
should_stop = true;
}
}
int main(int argc, char *argv[]) {
// By default the program runs for an infinite duration or until Ctrl+C is pressed
// The program takes an optional argument: number of seconds to run before exiting
bool has_time_limit = false;
int run_duration = 1;
if (argc == 2) {
run_duration = std::atoi(argv[1]);
if (run_duration > 0) {
has_time_limit = true;
}
}
// Handle signals for clean termination
std::signal(SIGINT, stop);
std::signal(SIGTERM, stop);
fmt::println("Starting Analog Events example...");
try {
// Create a profile with a two-wire resistive sensor
profile_builder builder{};
// Configure a two-wire resistive sensor on VRSNS1 and RREF
constexpr auto two_wire_sensor = "rsns_two_wire";
if (!builder.add_two_wire_resistive_sensor(two_wire_sensor, analog::pin_t::vrsns1)) {
fmt::println("Failed to add two-wire resistive sensor");
return EXIT_FAILURE;
}
fmt::println("Configured sensor:");
fmt::println("Two-wire resistive sensor on VRSNS1 + RREF");
// Initialize the analog interface
analog->init(builder.to_profile());
// Get handles for the sensor
auto two_wire_handle = analog->get_handle(two_wire_sensor);
if (two_wire_handle < 0) {
fmt::println("Failed to get sensor handles");
return EXIT_FAILURE;
}
// Create event sources for our sensor
const auto two_wire_source = event_source{event_source::source::analog, two_wire_handle};
// Create event handlers
fmt::println("\nSetting up event handlers");
// Create an event queue
auto queue = std::make_shared<event_queue>();
// Define event handlers
auto event_handler = [](std::shared_ptr<event> evt) {
switch (evt->type()) {
evt->get_data(data);
fmt::println("in-range event triggered: value {:.2f} in range [{:.2f}, {:.2f}]",
data.value, data.criteria.start, data.criteria.end);
break;
}
evt->get_data(data);
fmt::println("out-of-range triggered: value {:.2f}, outside range [{:.2f}, {:.2f}]",
data.value, data.criteria.start, data.criteria.end);
break;
}
evt->get_data(data);
fmt::println("threshold-above triggered: value {:.2f} > threshold {:.2f}",
data.value, data.criteria);
break;
}
evt->get_data(data);
fmt::println("threshold-below triggered: value {:.2f} < threshold {:.2f}",
data.value, data.criteria);
break;
}
default:
return;
}
};
// Create a second handler for threshold_below events
auto threshold_below_specialized_handler = [](std::shared_ptr<event> evt) {
evt->get_data(data);
fmt::println("SPECIALIZED HANDLER: Low resistance detected! Current: {:.2f} ohms (below {:.2f})",
data.value, data.criteria);
// In a real application, this handler can trigger an alarm or emergency response
if (data.value < 50.0) {
fmt::println("WARNING: Extremely low resistance detected!");
}
};
// Register both handlers for threshold_below events
queue->add_handler(two_wire_source, event_type::threshold_below, event_handler);
queue->add_handler(two_wire_source, event_type::threshold_below, threshold_below_specialized_handler);
// Register regular handler for other event types
queue->add_handler(two_wire_source, event_type::threshold_above, event_handler);
queue->add_handler(two_wire_source, event_type::in_range, event_handler);
queue->add_handler(two_wire_source, event_type::out_of_range, event_handler);
// Set up thresholds for continuous monitoring
constexpr double LOW_THRESHOLD = 250.0;
constexpr double HIGH_THRESHOLD = 100.0;
constexpr double NORMAL_MIN = 100.0;
constexpr double NORMAL_MAX = 150.0;
// Set up the same for two-wire sensor
fmt::println("\nSetting up notifications for two-wire sensor:");
fmt::println(" - Threshold below: {:.2f} ohms", LOW_THRESHOLD);
fmt::println(" - Threshold above: {:.2f} ohms", HIGH_THRESHOLD);
fmt::println(" - Normal range: [{:.2f}, {:.2f}] ohms", NORMAL_MIN, NORMAL_MAX);
analog->add_notification({
.queue = queue,
.source = two_wire_source,
.schedule = { .freq = event_notification_frequency::continuous, .interval = 500ms },
.value = LOW_THRESHOLD,
});
analog->add_notification({
.queue = queue,
.source = two_wire_source,
.value = HIGH_THRESHOLD,
});
analog->add_notification({
.queue = queue,
.source = two_wire_source,
.value = range_value{NORMAL_MIN, NORMAL_MAX},
});
analog->add_notification({
.queue = queue,
.source = two_wire_source,
.schedule = { .freq = event_notification_frequency::continuous, .interval = 100ms },
.value = range_value{NORMAL_MIN, NORMAL_MAX},
});
// Start notifications
fmt::println("\nStarting notification monitoring. Press Ctrl+C to stop.");
analog->start_notifications();
// Sleep for a bit to allow notifications to be processed
// If the optional argument to run for a limited duration is used, block main thread and automatically timeout
// In a real application, you would have a more sophisticated event loop
// Here we just sleep till the user presses Ctrl+C
while (!should_stop) {
std::unique_lock<std::mutex> lock(should_stop_mtx);
if(stop_cv.wait_for(lock, std::chrono::seconds(run_duration)) == std::cv_status::timeout && has_time_limit) {
break;
}
}
// Stop notifications
analog->stop_notifications();
fmt::println("Analog event monitoring stopped.");
} catch (const std::exception& e) {
fmt::println("Error: {}", e.what());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Describes the source of an event.
Definition io_event_source.h:25
bool add_two_wire_resistive_sensor(std::string label, analog::pin_t positive_a)
Add a two wire resistive sensor which uses RREF for a more accurate reading. The trade-off is that on...
The range_event_data class.
Definition io_range_event.h:110
double value
value The value used for evaluating the event
Definition io_range_event.h:128
range_value criteria
criteria The event criteria
Definition io_range_event.h:124
The threshold_event_data class.
Definition io_threshold_event.h:110
double value
value The value used for evaluating the event
Definition io_threshold_event.h:128
double criteria
criteria The event criteria
Definition io_threshold_event.h:124
Include this file to your file so you have access to fmtlib header-only implementation.
std::function< void(std::shared_ptr< event >)> event_handler
Event handler function definition.
Definition io_event_queue.h:27
@ in_range
any value inside of [start, end) - including start, excluding end.
Definition io_event_common.h:46
@ out_of_range
any value outside of (start, end) - excluding start and end.
Definition io_event_common.h:45
@ threshold_below
any value less than the threshold specified.
Definition io_event_common.h:44
@ threshold_above
any value greater than the threshold specified.
Definition io_event_common.h:43
@ single_shot
single_shot means a notification is generated once
Definition io_event_notification.h:35
@ continuous
continuous means a notification will be rescheduled
Definition io_event_notification.h:34
IO range event interface.
IO threshold event interface.
@ stop
stop operation failed
Definition io_error_codes.h:46
A range value start-end pair.
Definition io_event_common.h:54
double start
Start of range.
Definition io_event_common.h:74
double end
End of range.
Definition io_event_common.h:78

Digital I/O

The example code in cli-digital.cpp demonstrates using the digital inputs and digital outputs by mirroring the input on channel DIN0 to the output on channel DOUT0.

Test harness

This example uses pins "DIN0" and "DOUT0", which correspond to pins 35 and 25 on the AMPSEAL 35-pin connector on the D7, to mirror the digital input (on/off) from DIN0 to the digital output on DOUT0.

You will need a small consumer like a 12V LED strip or an LED + pulldown resistor between pins 25 and 30 on the AMPSEAL 35-pin connector. You must have a resistor between the DOUT0 and PWRIN- pins.

To turn the input "on", apply 12V to pin 35 on the AMPSEAL 35 connector; to turn the input "off", you can leave it floating. Please refer to I/O interfaces to locate pins 25 and 30 on the AMPSEAL 35-pin connector.

CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(
cli-digital-io
VERSION 0.1
LANGUAGES CXX)
# Set C++ standard to C++17
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 17)
# Project name
set(APPNAME cli-digital-io-app)
# Find VSDK packages
find_package(vsdk REQUIRED CONFIG COMPONENTS libio)
# Add executable and link against VSDK libraries
add_executable(${APPNAME} cli-digital.cpp)
target_link_libraries(${APPNAME} PRIVATE vsdk::libio)
## Deploy to target from Qt Creator
include(GNUInstallDirs)
install(TARGETS ${APPNAME}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
cli-digital.cpp
#include <atomic>
#include <csignal>
#include <unistd.h>
using namespace vsdk::io;
std::atomic_bool shouldStop = false;
void stop(int signal);
// This example mirrors the input from pin DIN0 to the output pin DOUT0
int main(int argc, char *argv[]) {
// By default the program mirrors digital channels for an infinite duration or until Ctrl+C is pressed
// The program takes an optional argument: '--run-once' to run to mirror digital channels only once
if (argc == 2 && strcmp(argv[1], "--run-once") == 0) {
shouldStop = true;
}
fmt::println("Starting Digital INOUT example...");
// Setup the input channel
auto in_descriptor =
digital_in_descriptor{.channel = input, .mode = digin::mode::active_high};
auto in_channel = digital_in_channel(in_descriptor);
// Setup the output channel
auto out_descriptor = digital_out_descriptor{
.channel = output, .mode = digout::mode::active_high};
auto out_channel = digital_out_channel(out_descriptor);
// Stop gracefully to allow cleanup
// Handle SIGINT (Ctrl-C) and SIGTERM ("politely" asking the process to stop)
std::signal(SIGINT, stop);
std::signal(SIGTERM, stop);
do {
// This is an example of a blocking read.
// The library also supports asynchronous event-based processing.
const auto reading_result = in_channel.read();
if (reading_result.status != io_status::ok) {
fmt::println("Error reading from {}: {}", input, to_string(reading_result.status));
return 1;
}
const bool reading = reading_result.value;
fmt::println("Read {} from channel digital in channel", reading);
out_channel.set_value(reading);
fmt::println("Set digital out channel to {}", reading);
usleep(100000);
} while (!shouldStop);
}
void stop(int signal) {
if (signal == SIGTERM || signal == SIGINT) {
fmt::println("Stopping...");
shouldStop = true;
}
}
The digital_in_channel class.
Definition digital_in_channel.h:25
The digital_out_channel class.
Definition digital_out_channel.h:23
Digital input channel interface.
Digital output channel interface.
@ output
Flush output buffer only.
Definition serial_port_common.h:123
channel
Digital input channels.
Definition digital_common.h:63
channel
Digital output channels.
Definition digital_common.h:19
@ ch0
channel 0
Definition digital_common.h:65
@ ch0
channel 0
Definition digital_common.h:21
@ active_high
active high mode
Definition digital_common.h:92
@ active_high
active high mode
Definition digital_common.h:49
The digital_in_descriptor class.
Definition digital_common.h:194
The digital_out_descriptor class.
Definition digital_common.h:183

PWM I/O

The example code in cli-pwm.cpp demonstrates:

  • How to configure PWM output channels, their periods and duty cycles.
  • Output channels will be enabled for 10s and then disabled.
  • How to configure PWM input channels and sample every 10ms.

Test harness

This example uses PWM input pins and output pins on the AMPSEAL 35-pin connector:

PWM Inputs:

  • Pin 29: FREQIN0 (Frequency Input Channel 0)
  • Pin 28: FREQIN1 (Frequency Input Channel 1)

PWM Outputs:

  • Pin 27: FREQOUT0 (Frequency Output Channel 0)
  • Pin 26: FREQOUT1 (Frequency Output Channel 1)

To test PWM functionality, you can:

  1. Connect a signal generator to pins 29 or 28 to provide PWM input signals
  2. Use an oscilloscope or frequency counter on pins 27 or 26 to observe PWM output signals

Please refer to PWM for details on PWM pins

CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(
cli-pwm-io
VERSION 0.1
LANGUAGES CXX)
# Set C++ standard to C++17
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 17)
# Project name
set(APPNAME cli-pwm-io-app)
# Find VSDK packages
find_package(vsdk REQUIRED CONFIG COMPONENTS libio utils)
# Add executable and link against VSDK libraries
add_executable(${APPNAME} cli-pwm.cpp)
target_link_libraries(${APPNAME} PRIVATE vsdk::libio vsdk::utils)
## Deploy to target from Qt Creator
include(GNUInstallDirs)
install(TARGETS ${APPNAME}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
cli-pwm.cpp
#include <atomic>
#include <csignal>
#include <thread>
using namespace vsdk::io;
using namespace std::chrono_literals;
int pwm_out_example() {
fmt::println("Starting PWM output example...");
// Create PWM output channels
.channel = digout::pwm::pwm0,
.frequency = 1.0, // 1 Hz
.duty_cycle = 0.5 // 50% duty cycle
});
.channel = digout::pwm::pwm1,
.frequency = 0.5, // 0.5 Hz
.duty_cycle = 0.5 // 50% duty cycle
});
fmt::println("Enabling PWM outputs for 10 seconds...");
fmt::println("PWM0: 1 Hz at 50% duty cycle");
fmt::println("PWM1: 0.5 Hz at 50% duty cycle");
// Enable PWM outputs
pwm0.set_on();
pwm1.set_on();
// Run for 10 seconds or until interrupted
for (int i = 0; i < 10; ++i) {
fmt::print(".");
std::this_thread::sleep_for(1s);
}
fmt::println("");
// Disable PWM outputs
pwm0.set_off();
pwm1.set_off();
fmt::println("PWM outputs disabled.");
return 0;
}
int pwm_in_example() {
fmt::println("Starting PWM input example...");
fmt::println("Reading PWM input frequencies from channels PWM0 and PWM1");
// Configure PWM input channels with 10ms sampling rate
.channel = digin::pwm::pwm0,
.frequency = 10
});
.channel = digin::pwm::pwm1,
.frequency = 10
});
fmt::println("{:<15} {:<15}", "FREQIN0 (Hz)", "FREQIN1 (Hz)");
fmt::println("{:<15} {:<15}", "------------", "------------");
// Read values from PWM inputs every 200ms
for (int i = 0; i < 10; ++i) {
// Before reading the value, you need to check the status of the reading,
//to check if the hardware is connected properly
const auto reading0_result = pwm0.read();
if (reading0_result.status != io_status::ok) {
fmt::println("PWM0 status: {}", to_string(reading0_result.status));
return 1;
}
const auto reading0 = reading0_result.value;
const auto reading1_result = pwm1.read();
if (reading1_result.status != io_status::ok) {
fmt::println("PWM1 status: {}", to_string(reading1_result.status));
return 1;
}
const auto reading1 = reading1_result.value;
fmt::println("{:<15.4f} {:<15.4f}", reading0, reading1);
std::this_thread::sleep_for(10ms);
}
fmt::println("PWM input monitoring stopped.");
return 0;
}
int main() {
pwm_out_example();
pwm_in_example();
return 0;
}
The pwm_in_channel class.
Definition pwm_in_channel.h:23
The pwm_out_channel class.
Definition pwm_out_channel.h:23
@ pwm1
pwm channel 1
Definition digital_common.h:38
@ pwm0
pwm channel 0
Definition digital_common.h:37
@ pwm1
pwm channel 1
Definition digital_common.h:81
@ pwm0
pwm channel 0
Definition digital_common.h:80
PWM input channel interface.
PWM output channel interface.
The pwm_in_descriptor class.
Definition digital_common.h:218
The pwm_out_descriptor classHolds the configuration for a pwm_out_channel.
Definition digital_common.h:204

4-20mA

4-20mA CLI example

The example code in cli-i420.cpp demonstrates reading 1 value from pin sns0 of the 4-20mA interface.

Test Harness

Input sns0 maps to Ampseal 35-way connector pins 12 (420MA_0+) and 23 (420MA_0-). Those pins must be connected to a current sender/source/generator/sensor.

Connect the negative pin (420MA_0-) to the current loop in such a way that the current flows into the pin. The 420MA_0- pin must be the final device on the current loop.

For loop-powered current senders, the positive pin (420MA_0+) may be used to power the loop. This pin produces a voltage output equal to D7 supply voltage, limited to 33mA.

For externally powered current senders, leave 420MA_0+ disconnected.

CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(
cli-i420-read
VERSION 0.1
LANGUAGES CXX)
# Set C++ standard to C++17
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 17)
# Project name
set(APPNAME cli-i420-app)
# Find VSDK packages
find_package(vsdk REQUIRED CONFIG COMPONENTS libio utils)
# Add executable and link against VSDK libraries
add_executable(${APPNAME} cli-i420.cpp)
target_link_libraries(${APPNAME} PRIVATE vsdk::libio vsdk::utils)
## Deploy to target from Qt Creator
include(GNUInstallDirs)
install(TARGETS ${APPNAME}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
cli-i420.cpp
#include <libio/i420.h>
int main() {
using namespace vsdk::io;
// There should only be *one* i420 instance on the entire machine.
i420 i;
// Unlike the analog IO library, the pins of the 4-20mA interface can only
// read 1 type of value so there is no configuration to require any
// registration.
//
// The call can only throw in the case of a fatal error like, for instance,
// trying to read before the library is initialized or trying to read from an
// invalid pin.
//
// To read a value, call
// `read_from` on the instance
fmt::println("{}: {} mA", i420_input::sns0, result.value);
}
The i420 class.
Definition i420.h:32
analog_result read_from(i420_input input) const
Read the selected input.
@ sns0
input 0 in mA
Definition i420_common.h:22
i420 interface
ValueType value
Value of the result.
Definition io_common.h:61

4-20mA GUI example

UI example project using QML and the D7 SDK

This is a minimal starter project that uses Qt with QML to create a UI application on the D7.

Scope of the example

The example demonstrates:

  • a minimal QML application that displays a graphical user interface on the D7
  • reading from multiple 4-20mA inputs on a separate thread to avoid blocking the UI main thread

It does not demonstrate:

  • installing the D7 SDK
  • adding D7 SDK as a Qt Kit in Qt Creator (or any other editor)
  • any test harness

Dependencies

  • Qt 6.10.2 - Requires QtQuick
  • Building for the host requires the Qt version installed on the host matches the version in the D7 SDK, currently 6.10.2.

Build instructions

Please refer to the minimal CLI example. The instructions to configure and build the project are identical.

Notable remark

Reading from the sensors on a separate thread

Reading from a sensor is slower than accessing a regular file, as such it should not be done on the main UI thread to avoid blocking it and making the UI lag.

This example show a different approach to the analog read example. Instead of using a "centralized" cache for keeping all the sensor readings, here the SensorReader class is exposed to QML directly and each instance of it is configured to read from a different sensor.

Each instance maintains its own QThread on which it does the reading and which emits the valueChanged(double) signal. When the signal is emitted, the UI will redraw the elements that depend on the value property of that specific SensorReader instance.

To better understand the mechanism, please look in SensorsView.qml, lines 84-88 to see the SensorReader class being instantiated and then at lines 13-19 in the same file to see how the SensorCell view depends on sns0Reader.

CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(
qml-i420-read
VERSION 0.1
LANGUAGES CXX)
# Project name
set(APPNAME qml-i420-app)
# Set C++ standard to C++17
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 17)
# Find QT and VSDK packages
find_package(Qt6 REQUIRED COMPONENTS Quick)
find_package(vsdk REQUIRED CONFIG COMPONENTS utils libio)
qt_standard_project_setup(REQUIRES 6.8)
qt_add_executable(${APPNAME} main.cpp)
qt_add_qml_module(
${APPNAME}
URI
qml_i420_read
VERSION
1.0
QML_FILES
ui/Main.qml
ui/SensorsView.qml
ui/SensorCell.qml
SOURCES
sensor_reader.cpp)
target_include_directories(${APPNAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(${APPNAME} PRIVATE Qt6::Quick vsdk::utils vsdk::libio)
## Deploy to target from Qt Creator
include(GNUInstallDirs)
install(TARGETS ${APPNAME}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
sensor_reader.h
#ifndef SENSOR_READER_H
#define SENSOR_READER_H
#include <QObject>
#include <QQmlEngine>
#include <QThread>
#include <libio/i420.h>
class SensorReader : public QObject {
Q_OBJECT
QML_ELEMENT
Q_PROPERTY(Pin sensor MEMBER _sensor READ sensor WRITE setSensor NOTIFY
sensorChanged FINAL)
Q_PROPERTY(QString value MEMBER _value READ value NOTIFY valueChanged FINAL)
Q_PROPERTY(QString unit MEMBER _unit READ unit WRITE setUnit NOTIFY
unitChanged FINAL)
public:
enum Pin {
Sns0,
Sns1,
Sns2,
Sns3,
Sns4,
Sns5,
Cal_1v65,
Cal_0v15,
Vsns_main,
Isns_main
};
Q_ENUM(Pin)
explicit SensorReader(QObject *parent = nullptr);
~SensorReader();
Pin sensor() const;
QString value() const;
QString unit() const;
void setSensor(const Pin sensor);
void setUnit(const QString &unit);
Q_INVOKABLE QString sensorName() const;
signals:
void sensorChanged(const Pin sensor);
void valueChanged(const QString &value);
void unitChanged(const QString &unit);
private:
void readValue();
Pin _sensor;
QString _value;
QString _unit;
QThread *_readerThread;
};
#endif // SENSOR_READER_H