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(
VERSION 0.1
LANGUAGES CXX)
# Set C++ standard to C++17
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 17)
# Project name
# 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>
int main() {
constexpr auto sns_name = "rsns0";
std::cerr << fmt::format("Failed to add sensor '{}'\n", sns_name);
return EXIT_FAILURE;
}
lib_analog->init(analog_profile);
auto rsns_handle = lib_analog->get_handle(sns_name);
assert(rsns_handle != -1);
const auto reading = lib_analog->read_from(rsns_handle);
std::cerr << fmt::format("Error while reading from {}: {}\n", sns_name,
return EXIT_FAILURE;
}
fmt::println("{} (vrsns0): {:.2f} ", sns_name, reading.value,
return EXIT_SUCCESS;
}
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(
VERSION 0.1
LANGUAGES CXX)
# Project name
# 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 <mutex>
#include <thread>
#include <unordered_map>
class SensorModel : public QAbstractTableModel {
Q_OBJECT
public:
explicit SensorModel(QObject *parent = nullptr);
~SensorModel() override;
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 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
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(
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 <atomic>
#include <csignal>
#include <limits>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std::chrono_literals;
std::atomic_bool should_stop = false;
std::condition_variable stop_cv;
std::mutex should_stop_mtx;
if (signal == SIGTERM || signal == SIGINT) {
fmt::println("Stopping analog event monitoring...");
stop_cv.notify_one();
should_stop = true;
}
}
int main(int argc, char *argv[]) {
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;
}
}
std::signal(SIGINT,
stop);
std::signal(SIGTERM,
stop);
fmt::println("Starting Analog Events example...");
try {
constexpr auto two_wire_sensor = "rsns_two_wire";
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");
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;
}
const auto two_wire_source =
event_source{event_source::source::analog, two_wire_handle};
fmt::println("\nSetting up event handlers");
auto queue = std::make_shared<event_queue>();
switch (evt->type()) {
evt->get_data(data);
fmt::println("in-range event triggered: value {:.2f} in range [{:.2f}, {:.2f}]",
break;
}
evt->get_data(data);
fmt::println("out-of-range triggered: value {:.2f}, outside range [{:.2f}, {:.2f}]",
break;
}
evt->get_data(data);
fmt::println("threshold-above triggered: value {:.2f} > threshold {:.2f}",
break;
}
evt->get_data(data);
fmt::println("threshold-below triggered: value {:.2f} < threshold {:.2f}",
break;
}
default:
return;
}
};
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})",
fmt::println("WARNING: Extremely low resistance detected!");
}
};
constexpr double LOW_THRESHOLD = 250.0;
constexpr double HIGH_THRESHOLD = 100.0;
constexpr double NORMAL_MIN = 100.0;
constexpr double NORMAL_MAX = 150.0;
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);
.queue = queue,
.source = two_wire_source,
.value = LOW_THRESHOLD,
});
.queue = queue,
.source = two_wire_source,
.value = HIGH_THRESHOLD,
});
.queue = queue,
.source = two_wire_source,
});
.queue = queue,
.source = two_wire_source,
});
fmt::println("\nStarting notification monitoring. Press Ctrl+C to stop.");
analog->start_notifications();
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;
}
}
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>
std::atomic_bool shouldStop = false;
int main(int argc, char *argv[]) {
if (argc == 2 && strcmp(argv[1], "--run-once") == 0) {
shouldStop = true;
}
fmt::println("Starting Digital INOUT example...");
auto in_descriptor =
std::signal(SIGINT,
stop);
std::signal(SIGTERM,
stop);
do {
const auto reading_result = in_channel.read();
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);
}
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:
- Connect a signal generator to pins 29 or 28 to provide PWM input signals
- 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 std::chrono_literals;
int pwm_out_example() {
fmt::println("Starting PWM output example...");
.frequency = 1.0,
.duty_cycle = 0.5
});
.frequency = 0.5,
.duty_cycle = 0.5
});
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");
for (int i = 0; i < 10; ++i) {
fmt::print(".");
std::this_thread::sleep_for(1s);
}
fmt::println("");
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");
.frequency = 10
});
.frequency = 10
});
fmt::println("{:<15} {:<15}", "FREQIN0 (Hz)", "FREQIN1 (Hz)");
fmt::println("{:<15} {:<15}", "------------", "------------");
for (int i = 0; i < 10; ++i) {
const auto reading0_result =
pwm0.read();
fmt::println(
"PWM0 status: {}",
to_string(reading0_result.status));
return 1;
}
const auto reading0 = reading0_result.value;
const auto reading1_result =
pwm1.read();
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
int main() {
}
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
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>
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