Yocto-3d-v2 : user's guide

Yocto-3D-V2 : User's guide

1. Introduction
1.1 Safety Information
1.2 Environmental conditions
2. Presentation
2.1 Common elements
2.2 Specific elements
3. The Yocto-3D-V2 functions
3.1 The 3D accelerometer
3.2 The 3D magnetometer
3.3 The 3D gyroscope
3.4 The reference frame
3.5 The 2D inclinometer (tilt sensor)
3.6 The magnetic compass
3.7 The estimated attitude quaternion
3.8 Optional accessories
4. First steps
4.1 Prerequisites
4.2 Testing USB connectivity
4.3 Localization
4.4 Test of the module
4.5 Configuration
5. Assembly and connections
5.1 Fixing
5.2 Moving the sensor away
5.3 USB power distribution
5.4 Electromagnetic compatibility (EMI)
6. Programming, general concepts
6.1 Programming paradigm
6.2 The Yocto-3D-V2 module
6.3 Module
6.4 Accelerometer
6.5 Magnetometer
6.6 Gyro
6.7 RefFrame
6.8 Tilt
6.9 Compass
6.10 DataLogger
6.11 What interface: Native, DLL or Service ?
6.12 Programming, where to start?
7. Using the Yocto-3D-V2 in command line
7.1 Installing
7.2 Use: general description
7.3 Control of the Tilt function
7.4 Control of the module part
7.5 Limitations
8. Using the Yocto-3D-V2 with Python
8.1 Source files
8.2 Dynamic library
8.3 Control of the Tilt function
8.4 Control of the module part
8.5 Error handling
9. Using Yocto-3D-V2 with C++
9.1 Control of the Tilt function
9.2 Control of the module part
9.3 Error handling
9.4 Integration variants for the C++ Yoctopuce library
10. Using Yocto-3D-V2 with C#
10.1 Installation
10.2 Using the Yoctopuce API in a Visual C# project
10.3 Control of the Tilt function
10.4 Control of the module part
10.5 Error handling
11. Using the Yocto-3D-V2 with LabVIEW
11.1 Architecture
11.2 Compatibility
11.3 Installation
11.4 Presentation of Yoctopuce VIs
11.5 Functioning and use of VIs
11.6 Using Proxy objects
11.7 Managing the data logger
11.8 Function list
11.9 A word on performances
11.10 A full example of a LabVIEW program
11.11 Differences from other Yoctopuce APIs
12. Using the Yocto-3D-V2 with Java
12.1 Getting ready
12.2 Control of the Tilt function
12.3 Control of the module part
12.4 Error handling
13. Using the Yocto-3D-V2 with Android
13.1 Native access and VirtualHub
13.2 Getting ready
13.3 Compatibility
13.4 Activating the USB port under Android
13.5 Control of the Tilt function
13.6 Control of the module part
13.7 Error handling
14. Using Yocto-3D-V2 with TypeScript
14.1 Using the Yoctopuce library for TypeScript
14.2 Refresher on asynchronous I/O in JavaScript
14.3 Control of the Tilt function
14.4 Control of the module part
14.5 Error handling
15. Using Yocto-3D-V2 with JavaScript / EcmaScript
15.1 Blocking I/O versus Asynchronous I/O in JavaScript
15.2 Using Yoctopuce library for JavaScript / EcmaScript 2017
15.3 Control of the Tilt function
15.4 Control of the module part
15.5 Error handling
16. Using Yocto-3D-V2 with PHP
16.1 Getting ready
16.2 Control of the Tilt function
16.3 Control of the module part
16.4 HTTP callback API and NAT filters
16.5 Error handling
17. Using Yocto-3D-V2 with Visual Basic .NET
17.1 Installation
17.2 Using the Yoctopuce API in a Visual Basic project
17.3 Control of the Tilt function
17.4 Control of the module part
17.5 Error handling
18. Using Yocto-3D-V2 with Delphi
18.1 Preparation
18.2 Control of the Tilt function
18.3 Control of the module part
18.4 Error handling
19. Using the Yocto-3D-V2 with Universal Windows Platform
19.1 Blocking and asynchronous functions
19.2 Installation
19.3 Using the Yoctopuce API in a Visual Studio project
19.4 Control of the Tilt function
19.5 A real example
19.6 Control of the module part
19.7 Error handling
20. Using Yocto-3D-V2 with Objective-C
20.1 Control of the Tilt function
20.2 Control of the module part
20.3 Error handling
21. Using with unsupported languages
21.1 Command line
21.2 .NET Assembly
21.3 VirtualHub and HTTP GET
21.4 Using dynamic libraries
21.5 Porting the high level library
22. Firmware Update
22.1 The VirtualHub or the YoctoHub
22.2 The command line library
22.3 The Android application Yocto-Firmware
22.4 Updating the firmware with the programming library
22.5 The "update" mode
23. Advanced programming
23.1 Event programming
23.2 The data logger
24. High-level API Reference
24.1 Class YAPI
24.2 Class YModule
24.3 Class YAccelerometer
24.4 Class YMagnetometer
24.5 Class YRefFrame
24.6 Class YTilt
24.7 Class YCompass
24.8 Class YGyro
24.9 Class YDataLogger
24.10 Class YDataSet
24.11 Class YMeasure
25. Troubleshooting
25.1 Where to start?
25.2 Programming examples don't seem to work
25.3 Linux and USB
25.4 ARM Platforms: HF and EL
25.5 Powered module but invisible for the OS
25.6 Another process named xxx is already using yAPI
25.7 Disconnections, erratic behavior
25.8 Registering a VirtualHub disconnect an other one
25.9 Dropped commands
25.10 Damaged device
26. Characteristics
27. Index

1. Introduction

The Yocto-3D-V2 is a 51x20mm electronic module which contains an accelerometer, a gyroscope, and a magnetometer. The three sensors are three-dimensional. The Yocto-3D-V2 uses these three sensors to measure the inclination with regards to the horizontal plane (tilt sensor), the magnetic heading (tilt-compensated compass), the acceleration, and the magnetic field to which the module is subjected as well as the angular velocity on each axis.

Moreover, the module is able to instantly estimate its orientation by combining the integration of gyroscopic measures with the static orientation measurements. The device attitude is provided directly as a quaternion, and as aeronautical angles (using Tait-Bryan's angles: roll, pitch, and heading). No extra math is required in the application to get this information.

Contrarily to the first version of the Yocto-3D, this version 2 is capable of performing constant auto-calibration, in particular to enable the use of the compass even in presence of hard-iron distortions, caused by magnetic sources that move together with the Yocto-3D-V2. However, soft-iron distortions, caused by ferromagnetic materials near to the sensor which alter the magnetic field, are not compensated for.

A flash memory is provided in the module, enabling it to autonomously store the measures for later retrieval, and to save the orientation sensor calibration so that it is functional immediately at power-on.


The Yocto-3D-V2 module

The Yocto-3D-V2 is not in itself a complete product. It is a component intended to be integrated into a solution used in laboratory equipments, or in industrial process-control equipments, or for similar applications in domestic and commercial environments. In order to use it, you must at least install it in a protective enclosure and connect it to a host computer.

Yoctopuce thanks you for buying this Yocto-3D-V2 and sincerely hopes that you will be satisfied with it. The Yoctopuce engineers have put a large amount of effort to ensure that your Yocto-3D-V2 is easy to install anywhere and easy to drive from a maximum of programming languages. If you are nevertheless disappointed with this module, or if you need additional information, do not hesitate to contact Yoctopuce support:

E-mail address:support@yoctopuce.com
Web site:www.yoctopuce.com
Postal address:Chemin des Journaliers, 1
ZIP code, city:1236 Cartigny
Country:Switzerland

1.1. Safety Information

The Yocto-3D-V2 is designed to meet the requirements of IEC 61010-1:2010 safety standard. It does not create any serious hazards to the operator and surrounding area, even in single fault condition, as long as it is integrated and used according to the instructions contained in this documentation, and in this section in particular.

Protective enclosure

The Yocto-3D-V2 should not be used without a protective enclosure, because of the accessible bare electronic components. For optimal safety, it should be put into a non-metallic, non-inflammable enclosure, resistant to a mechanical stress level of 5 J. For instance, use a polycarbonate (e.g. LEXAN) enclosure rated IK08 with a IEC 60695-11-10 flammability rating of V-1 or better. Using a lower quality enclosure may require specific warnings for the operator and/or compromise conformity with the safety standard.

Maintenance

If a damage is observed on the electronic board or on the enclosure, it should be replaced in order to ensure continued safety of the equipment, and to prevent damaging other parts of the system due to overload that a short circuit could cause.

Identification

In order to ease the maintenance and the identification of risks during maintenance, you should affixate the water-resistant identification label provided together with the electronic board as close as possible to the device. If the device is put in a dedicated enclosure, the identification label should be affixated on the outside of the enclosure. This label is resistant to humidity, and can hand rubbing with a piece of cloth soaked with water.


Identification label is integrated in the package label.

Application

The safety standard applied is intended to cover laboratory equipment, industrial process-control equipment and similar applications in residential or commercial environment. If you intend to use the Yocto-3D-V2 for another kind of application, you should check the safety regulations according to the standard applicable to your application.

In particular, the Yocto-3D-V2 is not certified for use in medical environments or for life-support applications.

Environment

The Yocto-3D-V2 is not certified for use in hazardous locations, explosive environments, or life-threatening applications. Environmental ratings are provided below.

1.2. Environmental conditions

Yoctopuce devices have been designed for indoor use in a standard office or laboratory environment (IEC 60664 pollution degree 2): air pollution is expected to be limited and mainly non-conductive. Relative humidity is expected to be between 10% and 90% RH, non condensing. Use in environments with significant solid pollution or conductive pollution requires a protection from such pollution using an IP67 or IP68 enclosure. The products are designed for use up to altitude 2000m.

All Yoctopuce devices are warranted to perform according to their documentation and technical specifications under normal temperature conditions according to IEC61010-1, i.e. 5°C to 40°C. In addition, most devices can also be used on an extended temperature range, where some limitations may apply from case to case.

The extended operating temperature range for the Yocto-3D-V2 is -30...85°C. This temperature range has been determined based on components manufacturer recommendations, and on controlled environment tests performed during a limited duration (1h). If you plan to use the Yocto-3D-V2 in harsh environments for a long period of time, we strongly advise you to run extensive tests before going to production.

2. Presentation


1:Micro-B USB socket 4:Picoflex header locations
2:Yocto-button 5:Sensor
3:Yocto-led

2.1. Common elements

All Yocto-modules share a number of common functionalities.

USB connector

Yoctopuce modules all come with a USB 2.0 micro-B socket. Warning: the USB connector is simply soldered in surface and can be pulled out if the USB plug acts as a lever. In this case, if the tracks stayed in position, the connector can be soldered back with a good iron and using flux to avoid bridges. Alternatively, you can solder a USB cable directly in the 1.27mm-spaced holes near the connector.

If you plan to use a power source other then a standard USB host port to power the device through the USB connector, that power source must respect the assigned values of USB 2.0 specifications:

A higher voltage is likely to destroy the device. THe behaviour with a lower voltage is not specified, but it can result firmware corruption.

Yocto-button

The Yocto-button has two functionalities. First, it can activate the Yocto-beacon mode (see below under Yocto-led). Second, if you plug in a Yocto-module while keeping this button pressed, you can then reprogram its firmware with a new version. Note that there is a simpler UI-based method to update the firmware, but this one works even in case of severely damaged firmware.

Yocto-led

Normally, the Yocto-led is used to indicate that the module is working smoothly. The Yocto-led then emits a low blue light which varies slowly, mimicking breathing. The Yocto-led stops breathing when the module is not communicating any more, as for instance when powered by a USB hub which is disconnected from any active computer.

When you press the Yocto-button, the Yocto-led switches to Yocto-beacon mode. It starts flashing faster with a stronger light, in order to facilitate the localization of a module when you have several identical ones. It is indeed possible to trigger off the Yocto-beacon by software, as it is possible to detect by software that a Yocto-beacon is on.

The Yocto-led has a third functionality, which is less pleasant: when the internal software which controls the module encounters a fatal error, the Yocto-led starts emitting an SOS in morse 1. If this happens, unplug and re-plug the module. If it happens again, check that the module contains the latest version of the firmware, and, if it is the case, contact Yoctopuce support2.

Current sensor

Each Yocto-module is able to measure its own current consumption on the USB bus. Current supply on a USB bus being quite critical, this functionality can be of great help. You can only view the current consumption of a module by software.

Serial number

Each Yocto-module has a unique serial number assigned to it at the factory. For Yocto-3D-V2 modules, this number starts with Y3DMK002. The module can be software driven using this serial number. The serial number cannot be modified.

Logical name

The logical name is similar to the serial number: it is a supposedly unique character string which allows you to reference your module by software. However, in the opposite of the serial number, the logical name can be modified at will. The benefit is to enable you to build several copies of the same project without needing to modify the driving software. You only need to program the same logical name in each copy. Warning: the behavior of a project becomes unpredictable when it contains several modules with the same logical name and when the driving software tries to access one of these modules through its logical name. When leaving the factory, modules do not have an assigned logical name. It is yours to define.

2.2. Specific elements

The sensors

The Yocto-3D-V2 uses a BNO055 sensor manufactured by Bosch. It is a 3D accelerometer coupled with a 3D magnetometer and 3D gyro. This sensor handles internally the fusion of all sensors in real time, and performs continuous auto-calibration. Be aware that it is a relatively fragile component: an acceleration above 2000g for more than 1 [ms], or an acceleration of 10000g for more than 0.2 [ms] would damage the sensor. For instance, a free fall onto a hard surface from a height above 1.80m could damage the sensor.

3. The Yocto-3D-V2 functions

The Yocto-3D-V2 has many distinct functions, providing various interfaces to its inertial sensors as may be required by the target application.

3.1. The 3D accelerometer

This function shows the acceleration to which the module is submitted, in multiples of the gravitational acceleration (g). The main value is the norm of the acceleration vector, but you can obtain X, Y, and Z components individually. The maximal measured value is of about 16g. Be aware that the Yocto-3D-V2 accelerometer may detect a calibration loss in case an acceleration over 16g is detected. This would result in an immediate reduction of capabilities on all Yocto-3D-V2 functions which depend directly or indirectly on the orientation estimate.

On the Yocto-3D-V2, it is possible to configure the acceleration report frequency between 1Hz and 100Hz. Internally, the measure is sampled at 100Hz, but when a lower frequency is selected, measures are averaged over the selected period.

To obtain a very precise value taking into account the gravitational force at the location where the module is used, you can perform a semi-automatic calibration of the accelerometer.

3.2. The 3D magnetometer

This function shows the magnetic field intensity to which the module is subjected, in Gauss. The main value is the field vector, but you can obtain the X, Y, and Z values individually. To be as precise as possible to detect the earth magnetic field, the magnetometer is limited to +/- 2 Gauss.

Beware, this function is easily perturbed in the proximity of ferromagnetic objects (such as steel screws) which modify the field lines.

Contrarily to the first version of the Yocto-3D, this version 2 is capable of performing constant auto-calibration, in particular to enable the use of the compass even in presence of hard-iron distortions, caused by magnetic sources that move together with the Yocto-3D-V2. However, soft-iron distortions, caused by ferromagnetic materials near to the sensor which alter the magnetic field, are not compensated for. If you intend to use the magnetometer function, it is therefore important to use only non-ferrous metals near to the sensor. For instance, aluminium, copper, zinc, brass and silver are good. Make sure to avoid iron, nickel, steel and cobalt.

On the Yocto-3D-V2, it is possible to configure the magnetometer report frequency between 1Hz and 20Hz. Internally, the measure is sampled at 20Hz, but when a lower frequency is selected, measures are averaged over the selected period.

3.3. The 3D gyroscope

This function shows the angular velocity of the device, in degrees per second. The main value is the norm of the angular velocity vector, but you can also obtain the angular velocity around individual axis X, Y, and Z. The maximal measured valus is about 2000 degrees per second.

In order to counter the natural drift of the gyroscope, the Yocto-3D-V2 automatically zeroes the measured value when the device detects that it is not moving (acceleration vector staying still and around 1g for several tenths of seconds at least).

On the Yocto-3D-V2, it is possible to configure the gyroscope report frequency between 1Hz and 100Hz. Internally, the measure is sampled at 100Hz, but when a lower frequency is selected, measures are averaged over the selected period.

3.4. The reference frame

You can freely choose the reference frame in which the Yocto-3D-V2 is going to work, that is the orientation in which it is assembled with regards to the natural movement direction. Indeed, the module orientation intervenes directly in the tilt measure computations (which are measured with regards to the horizontal plane), as well as for angle measures. In all, there are 24 orthogonal references you can select from. They can be simplified into 6 groups of positions (corresponding to the 6 sides of a cube), each including 4 distinct references for the 4 possible 90° rotations around the module Z axis.

Let us imagine that the Yocto-3D-V2 is assembled into a plane. It can be fixed on the left wall (LEFT), on the right wall (RIGHT), on the floor (BOTTOM), on the ceiling (TOP), at the front (FRONT), or at the rear (REAR).


The module 6 assembly positions

For each assembly position, there are 4 orthogonal orientations, which are defined by analogy with a clock: 12:00, 3:00, 6:00, and 9:00.


The 4 assembly orientations

The orientation of each of the 6 clocks is defined in a natural way with regards to what the pilot of the plane would see.


Orientation of the six clocks

Make sure to configure the Yocto-3D-V2 orientation after it is assembled, as all functions listed below in this sections depend on this settings. Do not forget to save this configuration in the module flash memory. Otherwise, the Yocto-3D-V2 will take the default configuration (BOTTOM, TWELVE) the next time it starts.

Whenever you change the configuration of the Yocto-3D-V2 orientation, make sure to rerun an explicit calibration procedure to ensure that the calibration values saved in the flash memory correspond to the selected orientation.

3.5. The 2D inclinometer (tilt sensor)

The Yocto-3D-V2 can measure the tilt with regards to the horizontal plane, with the help of a gravity measure. You can configure the choice of the reference horizontal plane in the refFram function described above. By default, it is the module X/Y plane.

The tilt1 function corresponds to roll, while the tilt2 function corresponds to pitch. Roll is a positive angle when the left side of the module rises. And pitch is a positive angle when the front of the module rises.

On the Yocto-3D-V2, it is possible to configure the inclinometer report frequency between 1Hz and 100Hz. Internally, the measure is sampled at 100Hz, but when a lower frequency is selected, measures are averaged over the selected period.

3.6. The magnetic compass

This function provides the module bearing, such as determined thanks to the earth magnetic field (as with a compass). The bearing is an angle in degrees, from 0° to 360°, clockwise. The magnetic field measure is compensated to take into account the module tilt. The module does not need, therefore, to be horizontal for the value to be correct. In case you observe a bearing change when the device is tilted, it probably means that you are experiencing soft iron distortions due to some nearby ferrous metal.

By default, bearing is computed on the module X/Y plane, but this plan can be changed by modifying the orientation defined with the refFrame function. Likewise, by default, 0° corresponds to the magnetic North, but it is possible to configure a different reference angle, for instance to compensate for the local magnetic declination and to point to the geographic North.

Beware, this function is easily perturbed in the proximity of ferromagnetic objects (such as steel screws) which modify the field lines.

Contrarily to the first version of the Yocto-3D, this version 2 is capable of performing constant auto-calibration, in particular to enable the use of the compass even in presence of hard-iron distortions, caused by magnetic sources that move together with the Yocto-3D-V2. However, soft-iron distortions, caused by ferromagnetic materials near to the sensor which alter the magnetic field, are not compensated for. If you intend to use the magnetometer function, it is therefore important to use only non-ferrous metals near to the sensor. For instance, aluminium, copper, zinc, brass and silver are good. Make sure to avoid iron, nickel, steel and cobalt.

On the Yocto-3D-V2, it is possible to configure the compass report frequency between 1Hz and 20Hz. Internally, the measure is sampled at 20Hz, but when a lower frequency is selected, measures are averaged over the selected period.

3.7. The estimated attitude quaternion

The four functions qt1 to qt4 correspond to the four components of the hypercomplex quaternion (also known as w, x, y and z) describing the estimated attitude of the device, based on a 95Hz gyroscopic integration. To counter the natural drift of the integration process, the Yocto-3D-V2 combines it with tilt and compass measurements using a complimentary filter.

The YGyro class of the programming library provides a simple API to access the quaternion, including its conversion into Tait-Bryan's roll, pitch, and heading angles). In the Yocto-3D-V2, angles returned by the inclinometers and the magnetic compass correspond directly to the values that can be derived from the quaternion.

3.8. Optional accessories

The accessories below are not necessary to use the Yocto-3D-V2 module but might be useful depending on your project. These are mostly common products that you can buy from your favorite hacking store. To save you the tedious job of looking for them, most of them are also available on the Yoctopuce shop.

Screws and spacers

In order to mount the Yocto-3D-V2 module, you can put small screws in the 2.5mm assembly holes, with a screw head no larger than 4.5mm. The best way is to use threaded spacers, which you can then mount wherever you want. You can find more details on this topic in the chapter about assembly and connections.

Micro-USB hub

If you intend to put several Yoctopuce modules in a very small space, you can connect them directly to a micro-USB hub. Yoctopuce builds a USB hub particularly small for this purpose (down to 20mmx36mm), on which you can directly solder a USB cable instead of using a USB plug. For more details, see the micro-USB hub information sheet.

YoctoHub-Ethernet, YoctoHub-Wireless and YoctoHub-GSM

You can add network connectivity to your Yocto-3D-V2, thanks to the YoctoHub-Ethernet, the YoctoHub-Wireless and the YoctoHub-GSM which provides repectiveley Ethernet, WiFi and GSM connectivity. All of them can drive up to three devices and behave exactly like a regular computer running a VirtualHub.

1.27mm (or 1.25mm) connectors

In case you wish to connect your Yocto-3D-V2 to a Micro-hub USB or a YoctoHub without using a bulky USB connector, you can use the four 1.27mm pads just behind the USB connector. There are two options.

You can mount the Yocto-3D-V2 directly on the hub using screw and spacers, and connect it using 1.27mm board-to-board connectors. To prevent shortcuts, it is best to solder the female connector on the hub and the male connector on the Yocto-3D-V2.

You can also use a small 4-wires cable with a 1.27mm connector. 1.25mm works as well, it does not make a difference for 4 pins. This makes it possible to move the device a few inches away. Don't put it too far away if you use that type of cable, because as the cable is not shielded, it may cause undesirable electromagnetic emissions.

Enclosure

Your Yocto-3D-V2 has been designed to be installed as is in your project. Nevertheless, Yoctopuce sells enclosures specifically designed for Yoctopuce devices. These enclosures have removable mounting brackets and magnets allowing them to stick on ferromagnetic surfaces. More details are available on the Yoctopuce web site 3. The suggested enclosure model for your Yocto-3D-V2 is the YoctoBox-3D-Black.


You can install your Yocto-3D-V2 in an optional enclosure

Picoflex connectors and flexible ribbon cable

If you intend to move the sensor component away from the rest of the Yocto-3D-V2 module using a pluggable cable, you will need 4-wire ribbon cable of 1.27mm pitch, and Picoflex connectors.4 You can find more details on this topic in the chapter about assembly and connections.

Be aware that picoflex connectors are ferromagnetic and may alter the compass function. Only use it on the sensor side if you only need accelerometer and gyroscope functions. If you need the compass to work properly, you should solder the ribbon cable directly on the PCB on the sensor side.

4. First steps

By design, all Yoctopuce modules are driven the same way. Therefore, user's guides for all the modules of the range are very similar. If you have already carefully read through the user's guide of another Yoctopuce module, you can jump directly to the description of the module functions.

4.1. Prerequisites

In order to use your Yocto-3D-V2 module, you should have the following items at hand.

A computer

Yoctopuce modules are intended to be driven by a computer (or possibly an embedded microprocessor). You will write the control software yourself, according to your needs, using the information provided in this manual.

Yoctopuce provides software libraries to drive its modules for the following operating systems: Windows, macOS X, Linux, and Android. Yoctopuce modules do not require installing any specific system driver, as they leverage the standard HID driver5 provided with every operating system.

Windows versions currently supported are: Windows XP, Windows 2003, Windows Vista, Windows 7, Windows 8 and Windows 10. Both 32 bit and 64 bit versions are supported. The programming library is also available for the Universal Windows Platform (UWP), which is supported by all flavors of Windows 10, including Windows 10 IoT. Yoctopuce is frequently testing its modules on Windows 7 and Windows 10.

MacOS versions currently supported are: Mac OS X 10.9 (Maverick), 10.10 (Yosemite), 10.11 (El Capitan), macOS 10.12 (Sierra), macOS 10.13 (High Sierra) and macOS 10.14 (Mojave). Yoctopuce is frequently testing its modules on macOS 10.14.

Linux kernels currently supported are the 2.6 branch, the 3.x branch and the 4.x branch. Other versions of the Linux kernel, and even other UNIX variants, are very likely to work as well, as Linux support is implemented through the standard libusb API. Yoctopuce is frequently testing its modules on Linux kernel 4.15 (Ubuntu 18.04 LTS).

Android versions currently supported are: Android 3.1 and later. Moreover, it is necessary for the tablet or phone to support the Host USB mode. Yoctopuce is frequently testing its modules on Android 7.x on a Samsung Galaxy A6 with the Java for Android library.

A USB 2.0 cable, type A-micro B

USB 2.0 connectors exist in three sizes: the "standard" size that you probably use to connect your printer, the very common mini size to connect small devices, and finally the micro size often used to connect mobile phones, as long as they do not exhibit an apple logo. All USB modules manufactured by Yoctopuce use micro size connectors.


The most common USB 2.0 connectors: A, B, Mini B, Micro A, Micro B6

To connect your Yocto-3D-V2 module to a computer, you need a USB 2.0 cable of type A-micro B. The price of this cable may vary a lot depending on the source, look for it under the name USB 2.0 A to micro B Data cable. Make sure not to buy a simple USB charging cable without data connectivity. The correct type of cable is available on the Yoctopuce shop.


You must plug in your Yocto-3D-V2 module with a USB 2.0 cable of type A - micro B

If you insert a USB hub between the computer and the Yocto-3D-V2 module, make sure to take into account the USB current limits. If you do not, be prepared to face unstable behaviors and unpredictable failures. You can find more details on this topic in the chapter about assembly and connections.

4.2. Testing USB connectivity

At this point, your Yocto-3D-V2 should be connected to your computer, which should have recognized it. It is time to make it work.

Go to the Yoctopuce web site and download the Virtual Hub software7. It is available for Windows, Linux, and Mac OS X. Normally, the Virtual Hub software serves as an abstraction layer for languages which cannot access the hardware layers of your computer. However, it also offers a succinct interface to configure your modules and to test their basic functions. You access this interface with a simple web browser8. Start the Virtual Hub software in a command line, open your preferred web browser and enter the URL http://127.0.0.1:4444. The list of the Yoctopuce modules connected to your computer is displayed.


Module list as displayed in your web bowser

4.3. Localization

You can then physically localize each of the displayed modules by clicking on the beacon button. This puts the Yocto-led of the corresponding module in Yocto-beacon mode. It starts flashing, which allows you to easily localize it. The second effect is to display a little blue circle on the screen. You obtain the same behavior when pressing the Yocto-button of the module.

4.4. Test of the module

The first item to check is that your module is working well: click on the serial number corresponding to your module. This displays a window summarizing the properties of your Yocto-3D-V2.


Properties of the Yocto-3D-V2 module

This window allows you to play with your module to check how it is working. Values measured by the Yocto-3D-V2 are indeed displayed in real time, both as numerical values and as a graph.

4.5. Configuration

When, in the module list, you click on the configure button corresponding to your module, the configuration window is displayed.


Yocto-3D-V2 module configuration.

Firmware

The module firmware can easily be updated with the help of the interface. Firmware destined for Yoctopuce modules are available as .byn files and can be downloaded from the Yoctopuce web site.

To update a firmware, simply click on the upgrade button on the configuration window and follow the instructions. If the update fails for one reason or another, unplug and re-plug the module and start the update process again. This solves the issue in most cases. If the module was unplugged while it was being reprogrammed, it does probably not work anymore and is not listed in the interface. However, it is always possible to reprogram the module correctly by using the Virtual Hub software 9 in command line 10.

Logical name of the module

The logical name is a name that you choose, which allows you to access your module, in the same way a file name allows you to access its content. A logical name has a maximum length of 19 characters. Authorized characters are A..Z, a..z, 0..9, _, and -. If you assign the same logical name to two modules connected to the same computer and you try to access one of them through this logical name, behavior is undetermined: you have no way of knowing which of the two modules answers.

Luminosity

This parameter allows you to act on the maximal intensity of the leds of the module. This enables you, if necessary, to make it a little more discreet, while limiting its power consumption. Note that this parameter acts on all the signposting leds of the module, including the Yocto-led. If you connect a module and no led turns on, it may mean that its luminosity was set to zero.

Logical names of functions

Each Yoctopuce module has a serial number and a logical name. In the same way, each function on each Yoctopuce module has a hardware name and a logical name, the latter can be freely chosen by the user. Using logical names for functions provides a greater flexibility when programming modules.

The Yocto-3D-V2 module has 9 functions. Simply click on the corresponding "rename" buttons to assign them new logical names.

You can also configure the reference frame used by the module for the tilt sensors, the compass, and the gyroscopic estimate of the module orientation.

5. Assembly and connections

This chapter provides important information regarding the use of the Yocto-3D-V2 module in real-world situations. Make sure to read it carefully before going too far into your project if you want to avoid pitfalls.

5.1. Fixing

While developing your project, you can simply let the module hang at the end of its cable. Check only that it does not come in contact with any conducting material (such as your tools). When your project is almost at an end, you need to find a way for your modules to stop moving around.


Examples of assembly on supports

The Yocto-3D-V2 module contains 2.5mm assembly holes. You can use these holes for screws. The screw head diameter must not be larger than 4.5mm or they will damage the module circuits. Make sure that the lower surface of the module is not in contact with the support. We recommend using spacers, but other methods are possible. Nothing prevents you from fixing the module with a glue gun; it will not be good-looking, but it will hold.

If your intend to screw your module directly against a conducting part, for example a metallic frame, insert an isolating layer in between. Otherwise you are bound to induce a short circuit: there are naked pads under your module. Simple insulating tape should be enough.

The use of mounting elements made of ferrous material, such as steel screws, is likely to prevent the magnetometer and the compass from working correctly.

5.2. Moving the sensor away

The Yocto-3D-V2 module is designed so that you can split it into two parts, allowing you to move away the sensor from the command sub-module. You can split the module by simply breaking the circuit. However, you can obtain better results if you use a good pincer, or cutting pliers. When you have split the sub-modules, you can sandpaper the protruding parts without risk.


The Yocto-3D-V2 module is designed so that you can split it into two parts.


Wiring under the sub-modules once separated.

Once the module is split into two, you must rewire the sub-modules. You can connect the sub-modules by soldering simple electric wires, but you can obtain a better result with 1.27 pitch ribbon cable. Consider using solid copper cables, rather than threaded ones: solid copper cables are somewhat less flexible, but much easier to solder.


Moving the sensor away with a ribbon cable.

You can also use ribbon cable with Picoflex connectors. You will obtain a slightly larger system, but the Picoflex headers are much easier to solder than ribbon cable. More over, the result can be disassembled. However, if you intend to use the magnetic compass function, make sure not to put a Picoflex connector on the sensor side. Picoflex connectors include ferrous metal which can alter the shape of magnetic field. It is therefore better to leave the Picoflex connector on the device side only, and solder the copper cable directly on the sensor side.


Moving the sensor away with Picoflex connectors.

Make sure to keep the sensor part away from ferromagnetic elements: a simple steel screw can considerably alter the magnetometer values, and therefore the compass.

Warning: divisible Yoctopuce modules very often have very similar connection systems. Nevertheless, sub-modules from different models are not all compatible. If you connect your Yocto-3D-V2 sub-module to another type of module, such as a Yocto-Temperature for instance, it will not work, and you run a high risk of damaging your equipment.

5.3. USB power distribution

Although USB means Universal Serial BUS, USB devices are not physically organized as a flat bus but as a tree, using point-to-point connections. This has consequences on power distribution: to make it simple, every USB port must supply power to all devices directly or indirectly connected to it. And USB puts some limits.

In theory, a USB port provides 100mA, and may provide up to 500mA if available and requested by the device. In the case of a hub without external power supply, 100mA are available for the hub itself, and the hub should distribute no more than 100mA to each of its ports. This is it, and this is not much. In particular, it means that in theory, it is not possible to connect USB devices through two cascaded hubs without external power supply. In order to cascade hubs, it is necessary to use self-powered USB hubs, that provide a full 500mA to each subport.

In practice, USB would not have been as successful if it was really so picky about power distribution. As it happens, most USB hub manufacturers have been doing savings by not implementing current limitation on ports: they simply connect the computer power supply to every port, and declare themselves as self-powered hub even when they are taking all their power from the USB bus (in order to prevent any power consumption check in the operating system). This looks a bit dirty, but given the fact that computer USB ports are usually well protected by a hardware current limitation around 2000mA, it actually works in every day life, and seldom makes hardware damage.

What you should remember: if you connect Yoctopuce modules through one, or more, USB hub without external power supply, you have no safe-guard and you depend entirely on your computer manufacturer attention to provide as much current as possible on the USB ports, and to detect overloads before they lead to problems or to hardware damages. When modules are not provided enough current, they may work erratically and create unpredictable bugs. If you want to prevent any risk, do not cascade hubs without external power supply, and do not connect peripherals requiring more than 100mA behind a bus-powered hub.

In order to help you controlling and planning overall power consumption for your project, all Yoctopuce modules include a built-in current sensor that indicates (with 5mA precision) the consumption of the module on the USB bus.

Note also that the USB cable itself may also cause power supply issues, in particular when the wires are too thin or when the cable is too long 11. Good cables are usually made using AWG 26 or AWG 28 wires for data lines and AWG 24 wires for power.

5.4. Electromagnetic compatibility (EMI)

Connection methods to integrate the Yocto-3D-V2 obviously have an impact on the system overall electromagnetic emissions, and therefore also impact the conformity with international standards.

When we perform reference measurements to validate the conformity of our products with IEC CISPR 11, we do not use any enclosure but connect the devices using a shielded USB cable, compliant with USB 2.0 specifications: the cable shield is connected to both connector shells, and the total resistance from shell to shell is under 0.6Ω. The USB cable length is 3m, in order to expose one meter horizontally, one meter vertically and keep the last meter close to the host computer within a ferrite bead.

If you use a non-shielded USB cable, or an improperly shielded cable, your system will work perfectly well but you may not remain in conformity with the emission standard. If you are building a system made of multiple devices connected using 1.27mm pitch connectors, or with a sensor moved away from the device CPU, you can generally recover the conformity by using a metallic enclosure acting as an external shield.

Still on the topic of electromagnetic compatibility, the maximum supported length of the USB cable is 3m. In addition to the voltage drop issue mentionned above, using longer wires would require to run extra tests to assert compatibility with the electromagnetic immunity standards.

6. Programming, general concepts

The Yoctopuce API was designed to be at the same time simple to use and sufficiently generic for the concepts used to be valid for all the modules in the Yoctopuce range, and this in all the available programming languages. Therefore, when you have understood how to drive your Yocto-3D-V2 with your favorite programming language, learning to use another module, even with a different language, will most likely take you only a minimum of time.

6.1. Programming paradigm

The Yoctopuce API is object oriented. However, for simplicity's sake, only the basics of object programming were used. Even if you are not familiar with object programming, it is unlikely that this will be a hinderance for using Yoctopuce products. Note that you will never need to allocate or deallocate an object linked to the Yoctopuce API: it is automatically managed.

There is one class per Yoctopuce function type. The name of these classes always starts with a Y followed by the name of the function, for example YTemperature, YRelay, YPressure, etc.. There is also a YModule class, dedicated to managing the modules themselves, and finally there is the static YAPI class, that supervises the global workings of the API and manages low level communications.


Structure of the Yoctopuce API.

The YSensor class

Each Yoctopuce sensor function has its dedicated class: YTemperature to measure the temperature, YVoltage to measure a voltage, YRelay to drive a relay, etc. However there is a special class that can do more: YSensor.

The YSensor class is the parent class for all Yoctopuce sensors, and can provide access to any sensor, regardless of its type. It includes methods to access all common functions. This makes it easier to create applications that use many different sensors. Moreover, if you create an application based on YSensor, it will work with all Yoctopuce sensors, even those which do no yet exist.

Programmation

In the Yoctopuce API, priority was put on the ease of access to the module functions by offering the possibility to make abstractions of the modules implementing them. Therefore, it is quite possible to work with a set of functions without ever knowing exactly which module are hosting them at the hardware level. This tremendously simplifies programming projects with a large number of modules.

From the programming stand point, your Yocto-3D-V2 is viewed as a module hosting a given number of functions. In the API, these functions are objects which can be found independently, in several ways.

Access to the functions of a module

Access by logical name

Each function can be assigned an arbitrary and persistent logical name: this logical name is stored in the flash memory of the module, even if this module is disconnected. An object corresponding to an Xxx function to which a logical name has been assigned can then be directly found with this logical name and the YXxx.FindXxx method. Note however that a logical name must be unique among all the connected modules.

Access by enumeration

You can enumerate all the functions of the same type on all the connected modules with the help of the classic enumeration functions FirstXxx and nextXxxx available for each YXxx class.

Access by hardware name

Each module function has a hardware name, assigned at the factory and which cannot be modified. The functions of a module can also be found directly with this hardware name and the YXxx.FindXxx function of the corresponding class.

Difference between Find and First

The YXxx.FindXxxx and YXxx.FirstXxxx methods do not work exactly the same way. If there is no available module, YXxx.FirstXxxx returns a null value. On the opposite, even if there is no corresponding module, YXxx.FindXxxx returns a valid object, which is not online but which could become so if the corresponding module is later connected.

Function handling

When the object corresponding to a function is found, its methods are available in a classic way. Note that most of these subfunctions require the module hosting the function to be connected in order to be handled. This is generally not guaranteed, as a USB module can be disconnected after the control software has started. The isOnline method, available in all the classes, is then very helpful.

Access to the modules

Even if it is perfectly possible to build a complete project while making a total abstraction of which function is hosted on which module, the modules themselves are also accessible from the API. In fact, they can be handled in a way quite similar to the functions. They are assigned a serial number at the factory which allows you to find the corresponding object with YModule.Find(). You can also assign arbitrary logical names to the modules to make finding them easier. Finally, the YModule class contains the YModule.FirstModule() and nextModule() enumeration methods allowing you to list the connected modules.

Functions/Module interaction

From the API standpoint, the modules and their functions are strongly uncorrelated by design. Nevertheless, the API provides the possibility to go from one to the other. Thus, the get_module() method, available for each function class, allows you to find the object corresponding to the module hosting this function. Inversely, the YModule class provides several methods allowing you to enumerate the functions available on a module.

6.2. The Yocto-3D-V2 module

The Yocto-3D-V2 device provides multiple measures. Raw sensor values can be obtained through the accelerometer, magnetometer and gyro interfaces. Computed inclination relative to the horizontal plane can be obtained through the tilt1 and tilt2 interfaces, as well as heading relative to the horizontal magnetic field. The device also provides an estimate of its 3D orientation based on the mathematical fusion of all sensors.

module : Module

attributetypemodifiable ?
productName  String  read-only
serialNumber  String  read-only
logicalName  String  modifiable
productId  Hexadecimal number  read-only
productRelease  Hexadecimal number  read-only
firmwareRelease  String  read-only
persistentSettings  Enumerated  modifiable
luminosity  0..100%  modifiable
beacon  On/Off  modifiable
upTime  Time  read-only
usbCurrent  Used current (mA)  read-only
rebootCountdown  Integer  modifiable
userVar  Integer  modifiable

accelerometer : Accelerometer
attributetypemodifiable ?
logicalName  String  modifiable
advertisedValue  String  modifiable
unit  String  read-only
currentValue  Fixed-point number  read-only
lowestValue  Fixed-point number  modifiable
highestValue  Fixed-point number  modifiable
currentRawValue  Fixed-point number  read-only
logFrequency  Frequency  modifiable
reportFrequency  Frequency  modifiable
advMode  Enumerated  modifiable
calibrationParam  Calibration parameters  modifiable
resolution  Fixed-point number  modifiable
sensorState  Integer  read-only
bandwidth  Integer  modifiable
xValue  Fixed-point number  read-only
yValue  Fixed-point number  read-only
zValue  Fixed-point number  read-only
gravityCancellation  On/Off  modifiable

magnetometer : Magnetometer
attributetypemodifiable ?
logicalName  String  modifiable
advertisedValue  String  modifiable
unit  String  read-only
currentValue  Fixed-point number  read-only
lowestValue  Fixed-point number  modifiable
highestValue  Fixed-point number  modifiable
currentRawValue  Fixed-point number  read-only
logFrequency  Frequency  modifiable
reportFrequency  Frequency  modifiable
advMode  Enumerated  modifiable
calibrationParam  Calibration parameters  modifiable
resolution  Fixed-point number  modifiable
sensorState  Integer  read-only
bandwidth  Integer  modifiable
xValue  Fixed-point number  read-only
yValue  Fixed-point number  read-only
zValue  Fixed-point number  read-only

gyro : Gyro
attributetypemodifiable ?
logicalName  String  modifiable
advertisedValue  String  modifiable
unit  String  read-only
currentValue  Fixed-point number  read-only
lowestValue  Fixed-point number  modifiable
highestValue  Fixed-point number  modifiable
currentRawValue  Fixed-point number  read-only
logFrequency  Frequency  modifiable
reportFrequency  Frequency  modifiable
advMode  Enumerated  modifiable
calibrationParam  Calibration parameters  modifiable
resolution  Fixed-point number  modifiable
sensorState  Integer  read-only
bandwidth  Integer  modifiable
xValue  Fixed-point number  read-only
yValue  Fixed-point number  read-only
zValue  Fixed-point number  read-only

refFrame : RefFrame
attributetypemodifiable ?
logicalName  String  modifiable
advertisedValue  String  modifiable
mountPos  Integer  modifiable
bearing  Fixed-point number  modifiable
calibrationParam  Calibration parameters  modifiable
fusionMode  Fusion mode  modifiable

tilt1 : Tilt
tilt2 : Tilt
attributetypemodifiable ?
logicalName  String  modifiable
advertisedValue  String  modifiable
unit  String  read-only
currentValue  Fixed-point number  read-only
lowestValue  Fixed-point number  modifiable
highestValue  Fixed-point number  modifiable
currentRawValue  Fixed-point number  read-only
logFrequency  Frequency  modifiable
reportFrequency  Frequency  modifiable
advMode  Enumerated  modifiable
calibrationParam  Calibration parameters  modifiable
resolution  Fixed-point number  modifiable
sensorState  Integer  read-only
bandwidth  Integer  modifiable
axis  Rotation axis  read-only

compass : Compass
attributetypemodifiable ?
logicalName  String  modifiable
advertisedValue  String  modifiable
unit  String  read-only
currentValue  Fixed-point number  read-only
lowestValue  Fixed-point number  modifiable
highestValue  Fixed-point number  modifiable
currentRawValue  Fixed-point number  read-only
logFrequency  Frequency  modifiable
reportFrequency  Frequency  modifiable
advMode  Enumerated  modifiable
calibrationParam  Calibration parameters  modifiable
resolution  Fixed-point number  modifiable
sensorState  Integer  read-only
bandwidth  Integer  modifiable
axis  Rotation axis  read-only
magneticHeading  Fixed-point number  read-only

qt1 : Qt
qt2 : Qt
qt3 : Qt
qt4 : Qt
attributetypemodifiable ?
logicalName  String  modifiable
advertisedValue  String  modifiable
unit  String  read-only
currentValue  Fixed-point number  read-only
lowestValue  Fixed-point number  modifiable
highestValue  Fixed-point number  modifiable
currentRawValue  Fixed-point number  read-only
logFrequency  Frequency  modifiable
reportFrequency  Frequency  modifiable
advMode  Enumerated  modifiable
calibrationParam  Calibration parameters  modifiable
resolution  Fixed-point number  modifiable
sensorState  Integer  read-only

dataLogger : DataLogger
attributetypemodifiable ?
logicalName  String  modifiable
advertisedValue  String  modifiable
currentRunIndex  Integer  read-only
timeUTC  UTC time  modifiable
recording  Enumerated  modifiable
autoStart  On/Off  modifiable
beaconDriven  On/Off  modifiable
usage  0..100%  read-only
clearHistory  Boolean  modifiable

6.3. Module

Global parameters control interface for all Yoctopuce devices

The YModule class can be used with all Yoctopuce USB devices. It can be used to control the module global parameters, and to enumerate the functions provided by each module.

productName

Character string containing the commercial name of the module, as set by the factory.

serialNumber

Character string containing the serial number, unique and programmed at the factory. For a Yocto-3D-V2 module, this serial number always starts with Y3DMK002. You can use the serial number to access a given module by software.

logicalName

Character string containing the logical name of the module, initially empty. This attribute can be modified at will by the user. Once initialized to an non-empty value, it can be used to access a given module. If two modules with the same logical name are in the same project, there is no way to determine which one answers when one tries accessing by logical name. The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and -.

productId

USB device identifier of the module, preprogrammed to 106 at the factory.

productRelease

Release number of the module hardware, preprogrammed at the factory. The original hardware release returns value 1, revision B returns value 2, etc.

firmwareRelease

Release version of the embedded firmware, changes each time the embedded software is updated.

persistentSettings

State of persistent module settings: loaded from flash memory, modified by the user or saved to flash memory.

luminosity

Lighting strength of the informative leds (e.g. the Yocto-Led) contained in the module. It is an integer value which varies between 0 (LEDs turned off) and 100 (maximum led intensity). The default value is 50. To change the strength of the module LEDs, or to turn them off completely, you only need to change this value.

beacon

Activity of the localization beacon of the module.

upTime

Time elapsed since the last time the module was powered on.

usbCurrent

Current consumed by the module on the USB bus, in milli-amps.

rebootCountdown

Countdown to use for triggering a reboot of the module.

userVar

32bit integer variable available for user storage.

6.4. Accelerometer

accelerometer control interface, available for instance in the Yocto-3D-V2 or the Yocto-Inclinometer

The YAccelerometer class allows you to read and configure Yoctopuce accelerometers. It inherits from YSensor class the core functions to read measurements, to register callback functions, and to access the autonomous datalogger. This class adds the possibility to access x, y and z components of the acceleration vector separately.

logicalName

Character string containing the logical name of the accelerometer, initially empty. This attribute can be modified at will by the user. Once initialized to an non-empty value, it can be used to access the accelerometer directly. If two accelerometers with the same logical name are used in the same project, there is no way to determine which one answers when one tries accessing by logical name. The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and -.

advertisedValue

Short character string summarizing the current state of the accelerometer, that is automatically advertised up to the parent hub. For an accelerometer, the advertised value is the current value of the acceleration.

unit

Short character string representing the measuring unit for the acceleration.

currentValue

Current value of the acceleration, in g, as a floating point number.

lowestValue

Minimal value of the acceleration, in g, as a floating point number.

highestValue

Maximal value of the acceleration, in g, as a floating point number.

currentRawValue

Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.

logFrequency

Datalogger recording frequency, or "OFF" when measures should not be stored in the data logger flash memory.

reportFrequency

Timed value notification frequency, or "OFF" when timed value notifications are disabled for this function.

advMode

Measuring mode for the advertised value pushed to the parent hub.

calibrationParam

Extra calibration parameters (for instance to compensate for the effects of an enclosure), as an array of 16 bit words.

resolution

Measure resolution (i.e. precision of the numeric representation, not necessarily of the measure itself).

sensorState

Sensor health state (zero when a current measure is available).

bandwidth

Measure update frequency.

xValue

X component of the acceleration, as a floating point number.

yValue

Y component of the acceleration, as a floating point number.

zValue

Z component of the acceleration, as a floating point number.

6.5. Magnetometer

magnetometer control interface, available for instance in the Yocto-3D-V2

The YSensor class is the parent class for all Yoctopuce sensor types. It can be used to read the current value and unit of any sensor, read the min/max value, configure autonomous recording frequency and access recorded data. It also provide a function to register a callback invoked each time the observed value changes, or at a predefined interval. Using this class rather than a specific subclass makes it possible to create generic applications that work with any Yoctopuce sensor, even those that do not yet exist. Note: The YAnButton class is the only analog input which does not inherit from YSensor.

logicalName

Character string containing the logical name of the magnetometer, initially empty. This attribute can be modified at will by the user. Once initialized to an non-empty value, it can be used to access the magnetometer directly. If two magnetometers with the same logical name are used in the same project, there is no way to determine which one answers when one tries accessing by logical name. The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and -.

advertisedValue

Short character string summarizing the current state of the magnetometer, that is automatically advertised up to the parent hub. For a magnetometer, the advertised value is the current value of the magnetic field.

unit

Short character string representing the measuring unit for the magnetic field.

currentValue

Current value of the magnetic field, in mT, as a floating point number.

lowestValue

Minimal value of the magnetic field, in mT, as a floating point number.

highestValue

Maximal value of the magnetic field, in mT, as a floating point number.

currentRawValue

Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.

logFrequency

Datalogger recording frequency, or "OFF" when measures should not be stored in the data logger flash memory.

reportFrequency

Timed value notification frequency, or "OFF" when timed value notifications are disabled for this function.

advMode

Measuring mode for the advertised value pushed to the parent hub.

calibrationParam

Extra calibration parameters (for instance to compensate for the effects of an enclosure), as an array of 16 bit words.

resolution

Measure resolution (i.e. precision of the numeric representation, not necessarily of the measure itself).

sensorState

Sensor health state (zero when a current measure is available).

bandwidth

Measure update frequency.

xValue

X component of the magnetic field, as a floating point number.

yValue

Y component of the magnetic field, as a floating point number.

zValue

Z component of the magnetic field, as a floating point number.

6.6. Gyro

gyroscope control interface, available for instance in the Yocto-3D-V2

The YGyro class allows you to read and configure Yoctopuce gyroscopes. It inherits from YSensor class the core functions to read measurements, to register callback functions, and to access the autonomous datalogger. This class adds the possibility to access x, y and z components of the rotation vector separately, as well as the possibility to deal with quaternion-based orientation estimates.

logicalName

Character string containing the logical name of the gyroscope, initially empty. This attribute can be modified at will by the user. Once initialized to an non-empty value, it can be used to access the gyroscope directly. If two gyroscopes with the same logical name are used in the same project, there is no way to determine which one answers when one tries accessing by logical name. The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and -.

advertisedValue

Short character string summarizing the current state of the gyroscope, that is automatically advertised up to the parent hub. For a gyroscope, the advertised value is the current value of the angular velocity.

unit

Short character string representing the measuring unit for the angular velocity.

currentValue

Current value of the angular velocity, in degrees per second, as a floating point number.

lowestValue

Minimal value of the angular velocity, in degrees per second, as a floating point number.

highestValue

Maximal value of the angular velocity, in degrees per second, as a floating point number.

currentRawValue

Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.

logFrequency

Datalogger recording frequency, or "OFF" when measures should not be stored in the data logger flash memory.

reportFrequency

Timed value notification frequency, or "OFF" when timed value notifications are disabled for this function.

advMode

Measuring mode for the advertised value pushed to the parent hub.

calibrationParam

Extra calibration parameters (for instance to compensate for the effects of an enclosure), as an array of 16 bit words.

resolution

Measure resolution (i.e. precision of the numeric representation, not necessarily of the measure itself).

sensorState

Sensor health state (zero when a current measure is available).

bandwidth

Measure update frequency.

xValue

Angular velocity around the X axis of the device, as a floating point number.

yValue

Angular velocity around the Y axis of the device, as a floating point number.

zValue

Angular velocity around the Z axis of the device, as a floating point number.

6.7. RefFrame

3D reference frame configuration interface, available for instance in the Yocto-3D-V2 or the Yocto-Inclinometer

The YRefFrame class is used to setup the base orientation of the Yoctopuce inertial sensors. Thanks to this, orientation functions relative to the earth surface plane can use the proper reference frame. For some devices, the class also implements a tridimensional sensor calibration process, which can compensate for local variations of standard gravity and improve the precision of the tilt sensors.

logicalName

Character string containing the logical name of the reference frame, initially empty. This attribute can be modified at will by the user. Once initialized to an non-empty value, it can be used to access the reference frame directly. If two reference frames with the same logical name are used in the same project, there is no way to determine which one answers when one tries accessing by logical name. The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and -.

advertisedValue

Short character string summarizing the current reference frame, that is automatically advertised up to the parent hub. For a reference frame, the advertised value is its the ordered list of axis device corresponding to roll, pitch and heading.

mountPos

Installation position of the device, defining the reference frame for the compass and the pitch/roll tilt sensors.

bearing

Reference bearing used by the compass (if present).

calibrationParam

Low-level calibration parameters for the accelerometer and magnetometer used by the compass and pitch/roll tilt sensors (when supported).

fusionMode

Fusion algorithm used to combine the accelerometer, gyroscope and compass data (when supported).

6.8. Tilt

tilt sensor control interface, available for instance in the Yocto-3D-V2 or the Yocto-Inclinometer

The YSensor class is the parent class for all Yoctopuce sensor types. It can be used to read the current value and unit of any sensor, read the min/max value, configure autonomous recording frequency and access recorded data. It also provide a function to register a callback invoked each time the observed value changes, or at a predefined interval. Using this class rather than a specific subclass makes it possible to create generic applications that work with any Yoctopuce sensor, even those that do not yet exist. Note: The YAnButton class is the only analog input which does not inherit from YSensor.

logicalName

Character string containing the logical name of the tilt sensor, initially empty. This attribute can be modified at will by the user. Once initialized to an non-empty value, it can be used to access the tilt sensor directly. If two tilt sensors with the same logical name are used in the same project, there is no way to determine which one answers when one tries accessing by logical name. The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and -.

advertisedValue

Short character string summarizing the current state of the tilt sensor, that is automatically advertised up to the parent hub. For a tilt sensor, the advertised value is the current value of the inclination.

unit

Short character string representing the measuring unit for the inclination.

currentValue

Current value of the inclination, in degrees, as a floating point number.

lowestValue

Minimal value of the inclination, in degrees, as a floating point number.

highestValue

Maximal value of the inclination, in degrees, as a floating point number.

currentRawValue

Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.

logFrequency

Datalogger recording frequency, or "OFF" when measures should not be stored in the data logger flash memory.

reportFrequency

Timed value notification frequency, or "OFF" when timed value notifications are disabled for this function.

advMode

Measuring mode for the advertised value pushed to the parent hub.

calibrationParam

Extra calibration parameters (for instance to compensate for the effects of an enclosure), as an array of 16 bit words.

resolution

Measure resolution (i.e. precision of the numeric representation, not necessarily of the measure itself).

sensorState

Sensor health state (zero when a current measure is available).

bandwidth

Measure update frequency.

axis

Function working axis for the tilt sensor.

6.9. Compass

compass function control interface, available for instance in the Yocto-3D-V2

The YCompass class allows you to read and configure Yoctopuce compass functions. It inherits from YSensor class the core functions to read measurements, to register callback functions, and to access the autonomous datalogger.

logicalName

Character string containing the logical name of the compass function, initially empty. This attribute can be modified at will by the user. Once initialized to an non-empty value, it can be used to access the compass function directly. If two compass functions with the same logical name are used in the same project, there is no way to determine which one answers when one tries accessing by logical name. The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and -.

advertisedValue

Short character string summarizing the current state of the compass function, that is automatically advertised up to the parent hub. For a compass function, the advertised value is the current value of the relative bearing.

unit

Short character string representing the measuring unit for the relative bearing.

currentValue

Current value of the relative bearing, in degrees, as a floating point number.

lowestValue

Minimal value of the relative bearing, in degrees, as a floating point number.

highestValue

Maximal value of the relative bearing, in degrees, as a floating point number.

currentRawValue

Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.

logFrequency

Datalogger recording frequency, or "OFF" when measures should not be stored in the data logger flash memory.

reportFrequency

Timed value notification frequency, or "OFF" when timed value notifications are disabled for this function.

advMode

Measuring mode for the advertised value pushed to the parent hub.

calibrationParam

Extra calibration parameters (for instance to compensate for the effects of an enclosure), as an array of 16 bit words.

resolution

Measure resolution (i.e. precision of the numeric representation, not necessarily of the measure itself).

sensorState

Sensor health state (zero when a current measure is available).

bandwidth

Measure update frequency.

axis

Function working axis for the compass function.

magneticHeading

Magnetic heading (regardless of the configured bearing)

6.10. DataLogger

DataLogger control interface, available on most Yoctopuce sensors.

A non-volatile memory for storing ongoing measured data is available on most Yoctopuce sensors. Recording can happen automatically, without requiring a permanent connection to a computer. The YDataLogger class controls the global parameters of the internal data logger. Recording control (start/stop) as well as data retreival is done at sensor objects level.

logicalName

Character string containing the logical name of the data logger, initially empty. This attribute can be modified at will by the user. Once initialized to an non-empty value, it can be used to access the data logger directly. If two data loggers with the same logical name are used in the same project, there is no way to determine which one answers when one tries accessing by logical name. The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and -.

advertisedValue

Short character string summarizing the current state of the data logger, that is automatically advertised up to the parent hub. For a data logger, the advertised value is its recording state (ON or OFF).

currentRunIndex

Current run number, corresponding to the number of time the module was powered on with the dataLogger enabled at some point.

timeUTC

Current UTC time, in case it is desirable to bind an absolute time reference to the data stored by the data logger. This time must be set up by software.

recording

Activation state of the data logger. The data logger can be enabled and disabled at will, using this attribute, but its state on power on is determined by the autoStart persistent attribute. When the datalogger is enabled but not yet ready to record data, its state is set to PENDING.

autoStart

Automatic start of the data logger on power on. Setting this attribute ensures that the data logger is always turned on when the device is powered up, without need for a software command. Note: if the device doesn't have any time source at his disposal, it will wait for ~8 seconds before automatically starting to record.

beaconDriven

Synchronize the sate of the localization beacon and the state of the data logger. If this attribute is set, it is possible to start the recording with the Yocto-button or the attribute beacon of the function YModule. In the same way, if the attribute recording is changed, the sate of the localization beacon is updated. Note: when this attribute is set the localization beacon pulses slower than usual.

usage

Percentage of datalogger memory in use.

clearHistory

Attribute that can be set to true to clear recorded data.

6.11. What interface: Native, DLL or Service ?

There are several methods to control you Yoctopuce module by software.

Native control

In this case, the software driving your project is compiled directly with a library which provides control of the modules. Objectively, it is the simplest and most elegant solution for the end user. The end user then only needs to plug the USB cable and run your software for everything to work. Unfortunately, this method is not always available or even possible.


The application uses the native library to control the locally connected module

Native control by DLL

Here, the main part of the code controlling the modules is located in a DLL. The software is compiled with a small library which provides control of the DLL. It is the fastest method to code module support in a given language. Indeed, the "useful" part of the control code is located in the DLL which is the same for all languages: the effort to support a new language is limited to coding the small library which controls the DLL. From the end user stand point, there are few differences: one must simply make sure that the DLL is installed on the end user's computer at the same time as the main software.


The application uses the DLL to natively control the locally connected module

Control by service

Some languages do simply not allow you to easily gain access to the hardware layers of the machine. It is the case for Javascript, for instance. To deal with this case, Yoctopuce provides a solution in the form of a small piece of software called VirtualHub12. It can access the modules, and your application only needs to use a library which offers all necessary functions to control the modules via this VirtualHub. The end users will have to start the VirtualHub before running the project control software itself, unless they decide to install the hub as a service/deamon, in which case the VirtualHub starts automatically when the machine starts up.


The application connects itself to the VirtualHub to gain access to the module

The service control method comes with a non-negligible advantage: the application does not need to run on the machine on which the modules are connected. The application can very well be located on another machine which connects itself to the service to drive the modules. Moreover, the native libraries and DLL mentioned above are also able to connect themselves remotely to one or several machines running VirtualHub.


When a VirtualHub is used, the control application does not need to reside on the same machine as the module.

Whatever the selected programming language and the control paradigm used, programming itself stays strictly identical. From one language to another, functions bear exactly the same name, and have the same parameters. The only differences are linked to the constraints of the languages themselves.

Language Native  Native with DLL  VirtualHub 
Command line -
Python -
C++
C# .Net -
C# UWP -
LabVIEW -
Java -
Java for Android -
TypeScript - -
JavaScript / ECMAScript - -
PHP - -
VisualBasic .Net -
Delphi -
Objective-C -

Support methods for different languages

Limitations of the Yoctopuce libraries

Natives et DLL libraries have a technical limitation. On the same computer, you cannot concurrently run several applications accessing Yoctopuce devices directly. If you want to run several projects on the same computer, make sure your control applications use Yoctopuce devices through a VirtualHub software. The modification is trivial: it is just a matter of parameter change in the yRegisterHub() call.

6.12. Programming, where to start?

At this point of the user's guide, you should know the main theoretical points of your Yocto-3D-V2. It is now time to practice. You must download the Yoctopuce library for your favorite programming language from the Yoctopuce web site13. Then skip directly to the chapter corresponding to the chosen programming language.

All the examples described in this guide are available in the programming libraries. For some languages, the libraries also include some complete graphical applications, with their source code.

When you have mastered the basic programming of your module, you can turn to the chapter on advanced programming that describes some techniques that will help you make the most of your Yocto-3D-V2.

7. Using the Yocto-3D-V2 in command line

When you want to perform a punctual operation on your Yocto-3D-V2, such as reading a value, assigning a logical name, and so on, you can obviously use the Virtual Hub, but there is a simpler, faster, and more efficient method: the command line API.

The command line API is a set of executables, one by type of functionality offered by the range of Yoctopuce products. These executables are provided pre-compiled for all the Yoctopuce officially supported platforms/OS. Naturally, the executable sources are also provided14.

7.1. Installing

Download the command line API15. You do not need to run any setup, simply copy the executables corresponding to your platform/OS in a directory of your choice. You may add this directory to your PATH variable to be able to access these executables from anywhere. You are all set, you only need to connect your Yocto-3D-V2, open a shell, and start working by typing for example:

C:\>YTilt any get_currentValue

To use the command API on Linux, you need either have root privileges or to define an udev rule for your system. See the Troubleshooting chapter for more details.

7.2. Use: general description

All the command line API executables work on the same principle. They must be called the following way


C:\>Executable [options] [target] command [parameter]

[options] manage the global workings of the commands, they allow you, for instance, to pilot a module remotely through the network, or to force the module to save its configuration after executing the command.

[target] is the name of the module or of the function to which the command applies. Some very generic commands do not need a target. You can also use the aliases "any" and "all", or a list of names separated by comas without space.

command is the command you want to run. Almost all the functions available in the classic programming APIs are available as commands. You need to respect neither the case nor the underlined characters in the command name.

[parameters] logically are the parameters needed by the command.

At any time, the command line API executables can provide a rather detailed help. Use for instance:


C:\>executable /help

to know the list of available commands for a given command line API executable, or even:


C:\>executable command /help

to obtain a detailed description of the parameters of a command.

7.3. Control of the Tilt function

To control the Tilt function of your Yocto-3D-V2, you need the YTilt executable file.

For instance, you can launch:

C:\>YTilt any get_currentValue

This example uses the "any" target to indicate that we want to work on the first Tilt function found among all those available on the connected Yoctopuce modules when running. This prevents you from having to know the exact names of your function and of your module.

But you can use logical names as well, as long as you have configured them beforehand. Let us imagine a Yocto-3D-V2 module with the Y3DMK002-123456 serial number which you have called "MyModule", and its tilt1 function which you have renamed "MyFunction". The five following calls are strictly equivalent (as long as MyFunction is defined only once, to avoid any ambiguity).


C:\>YTilt Y3DMK002-123456.tilt1 describe

C:\>YTilt Y3DMK002-123456.MyFunction describe

C:\>YTilt MyModule.tilt1 describe

C:\>YTilt MyModule.MyFunction describe

C:\>YTilt MyFunction describe

To work on all the Tilt functions at the same time, use the "all" target.


C:\>YTilt all describe

For more details on the possibilities of the YTilt executable, use:


C:\>YTilt /help

7.4. Control of the module part

Each module can be controlled in a similar way with the help of the YModule executable. For example, to obtain the list of all the connected modules, use:


C:\>YModule inventory

You can also use the following command to obtain an even more detailed list of the connected modules:


C:\>YModule all describe

Each xxx property of the module can be obtained thanks to a command of the get_xxxx() type, and the properties which are not read only can be modified with the set_xxx() command. For example:


C:\>YModule Y3DMK002-12346 set_logicalName MonPremierModule

C:\>YModule Y3DMK002-12346 get_logicalName

Changing the settings of the module

When you want to change the settings of a module, simply use the corresponding set_xxx command. However, this change happens only in the module RAM: if the module restarts, the changes are lost. To store them permanently, you must tell the module to save its current configuration in its nonvolatile memory. To do so, use the saveToFlash command. Inversely, it is possible to force the module to forget its current settings by using the revertFromFlash method. For example:


C:\>YModule Y3DMK002-12346 set_logicalName MonPremierModule
C:\>YModule Y3DMK002-12346 saveToFlash

Note that you can do the same thing in a single command with the -s option.


C:\>YModule -s  Y3DMK002-12346 set_logicalName MonPremierModule

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

7.5. Limitations

The command line API has the same limitation than the other APIs: there can be only one application at a given time which can access the modules natively. By default, the command line API works in native mode.

You can easily work around this limitation by using a Virtual Hub: run the VirtualHub16 on the concerned machine, and use the executables of the command line API with the -r option. For example, if you use:


C:\>YModule  inventory

you obtain a list of the modules connected by USB, using a native access. If another command which accesses the modules natively is already running, this does not work. But if you run a Virtual Hub, and you give your command in the form:


C:\>YModule -r 127.0.0.1 inventory

it works because the command is not executed natively anymore, but through the Virtual Hub. Note that the Virtual Hub counts as a native application.

8. Using the Yocto-3D-V2 with Python

Python is an interpreted object oriented language developed by Guido van Rossum. Among its advantages is the fact that it is free, and the fact that it is available for most platforms, Windows as well as UNIX. It is an ideal language to write small scripts on a napkin. The Yoctopuce library is compatible with Python 2.6+ and 3+. It works under Windows, Mac OS X, and Linux, Intel as well as ARM. The library was tested with Python 2.6 and Python 3.2. Python interpreters are available on the Python web site17.

8.1. Source files

The Yoctopuce library classes18 for Python that you will use are provided as source files. Copy all the content of the Sources directory in the directory of your choice and add this directory to the PYTHONPATH environment variable. If you use an IDE to program in Python, refer to its documentation to configure it so that it automatically finds the API source files.

8.2. Dynamic library

A section of the low-level library is written in C, but you should not need to interact directly with it: it is provided as a DLL under Windows, as a .so files under UNIX, and as a .dylib file under Mac OS X. Everything was done to ensure the simplest possible interaction from Python: the distinct versions of the dynamic library corresponding to the distinct operating systems and architectures are stored in the cdll directory. The API automatically loads the correct file during its initialization. You should not have to worry about it.

If you ever need to recompile the dynamic library, its complete source code is located in the Yoctopuce C++ library.

In order to keep them simple, all the examples provided in this documentation are console applications. Naturally, the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface.

8.3. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a Python code snipplet to use the Tilt function.


[...]
# Enable detection of USB devices
errmsg=YRefParam()
YAPI.RegisterHub("usb",errmsg)
[...]

# Retrieve the object used to interact with the device
tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1")

# Hot-plug is easy: just check that the device is online
if tilt.isOnline():
    # Use tilt.get_currentValue()
    [...]
   
[...]    

Let's look at these lines in more details.

YAPI.RegisterHub

The yAPI.RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for. When used with the parameter "usb", it will use the modules locally connected to the computer running the library. If the initialization does not succeed, this function returns a value different from YAPI.SUCCESS and errmsg contains the error message.

YTilt.FindTilt

The YTilt.FindTilt function allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can use logical names as well, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1")
tilt = YTilt.FindTilt("Y3DMK002-123456.MyFunction")
tilt = YTilt.FindTilt("MyModule.tilt1")
tilt = YTilt.FindTilt("MyModule.MyFunction")
tilt = YTilt.FindTilt("MyFunction")

YTilt.FindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by YTilt.FindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by YTilt.FindTilt provides the value of orientation measured by the tilt sensor. The value returned is a floating number.

YCompass.FindCompass, YGyro.FindGyro...

Functions YCompass.FindCompass, YMagnetometer.FindMagnetometer, YGyro.FindGyro and YAccelerometer.FindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YTilt.FindTilt.

A real example

Launch Python and open the corresponding sample script provided in the directory Examples/Doc-GettingStarted-Yocto-3D-V2 of the Yoctopuce library.

In this example, you will recognize the functions explained above, but this time used with all side materials needed to make it work nicely as a small demo.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys

from yocto_api import *
from yocto_tilt import *
from yocto_compass import *
from yocto_gyro import *
from yocto_accelerometer import *


def usage():
    scriptname = os.path.basename(sys.argv[0])
    print("Usage:")
    print(scriptname + ' <serial_number>')
    print(scriptname + ' <logical_name>')
    print(scriptname + ' any  ')
    sys.exit()


def die(msg):
    sys.exit(msg + ' (check USB cable)')


errmsg = YRefParam()

if len(sys.argv) < 2:
    usage()

target = sys.argv[1]

# Setup the API to use local USB devices
if YAPI.RegisterHub("usb", errmsg) != YAPI.SUCCESS:
    sys.exit("init error" + errmsg.value)

if target == 'any':
    # retreive any tilt sensor
    anytilt = YTilt.FirstTilt()
    if anytilt is None:
        die('No module connected (check USB cable)')
    m = anytilt.get_module()
    target = m.get_serialNumber()
else:
    anytilt = YTilt.FindTilt(target + ".tilt1")
    if not (anytilt.isOnline()):
        die('Module not connected (check identification and USB cable)')

serial = anytilt.get_module().get_serialNumber()
tilt1 = YTilt.FindTilt(serial + ".tilt1")
tilt2 = YTilt.FindTilt(serial + ".tilt2")
compass = YCompass.FindCompass(serial + ".compass")
accelerometer = YAccelerometer.FindAccelerometer(serial + ".accelerometer")
gyro = YGyro.FindGyro(serial + ".gyro")

count = 0

if not (tilt1.isOnline()):
    die("Module not connected (check identification and USB cable)")

while tilt1.isOnline():

    if count % 10 == 0:
        print("tilt1   tilt2   compass acc     gyro")

    print("%-7.1f " % tilt1.get_currentValue() + \
          "%-7.1f " % tilt2.get_currentValue() + \
          "%-7.1f " % compass.get_currentValue() + \
          "%-7.1f " % accelerometer.get_currentValue() + \
          "%-7.1f" % gyro.get_currentValue())
    count += 1
    YAPI.Sleep(250, errmsg)
YAPI.FreeAPI()
 

8.4. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys

from yocto_api import *


def usage():
    sys.exit("usage: demo <serial or logical name> [ON/OFF]")


errmsg = YRefParam()
if YAPI.RegisterHub("usb", errmsg) != YAPI.SUCCESS:
    sys.exit("RegisterHub error: " + str(errmsg))

if len(sys.argv) < 2:
    usage()

m = YModule.FindModule(sys.argv[1])  # # use serial or logical name

if m.isOnline():
    if len(sys.argv) > 2:
        if sys.argv[2].upper() == "ON":
            m.set_beacon(YModule.BEACON_ON)
        if sys.argv[2].upper() == "OFF":
            m.set_beacon(YModule.BEACON_OFF)

    print("serial:       " + m.get_serialNumber())
    print("logical name: " + m.get_logicalName())
    print("luminosity:   " + str(m.get_luminosity()))
    if m.get_beacon() == YModule.BEACON_ON:
        print("beacon:       ON")
    else:
        print("beacon:       OFF")
    print("upTime:       " + str(m.get_upTime() / 1000) + " sec")
    print("USB current:  " + str(m.get_usbCurrent()) + " mA")
    print("logs:\n" + m.get_lastLogs())
else:
    print(sys.argv[1] + " not connected (check identification and USB cable)")
YAPI.FreeAPI()
 

Each property xxx of the module can be read thanks to a method of type YModule.get_xxxx(), and properties which are not read-only can be modified with the help of the YModule.set_xxx() method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding YModule.set_xxx() function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the YModule.saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the YModule.revertFromFlash() method. The short example below allows you to modify the logical name of a module.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys

from yocto_api import *


def usage():
    sys.exit("usage: demo <serial or logical name> <new logical name>")


if len(sys.argv) != 3:
    usage()

errmsg = YRefParam()
if YAPI.RegisterHub("usb", errmsg) != YAPI.SUCCESS:
    sys.exit("RegisterHub error: " + str(errmsg))

m = YModule.FindModule(sys.argv[1])  # use serial or logical name
if m.isOnline():
    newname = sys.argv[2]
    if not YAPI.CheckLogicalName(newname):
        sys.exit("Invalid name (" + newname + ")")
    m.set_logicalName(newname)
    m.saveToFlash()  # do not forget this
    print("Module: serial= " + m.get_serialNumber() + " / name= " + m.get_logicalName())
else:
    sys.exit("not connected (check identification and USB cable")
YAPI.FreeAPI()

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the YModule.saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the YModule.yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not null. Below a short example listing the connected modules.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys


from yocto_api import *

errmsg = YRefParam()

# Setup the API to use local USB devices
if YAPI.RegisterHub("usb", errmsg) != YAPI.SUCCESS:
    sys.exit("init error" + str(errmsg))

print('Device list')

module = YModule.FirstModule()
while module is not None:
    print(module.get_serialNumber() + ' (' + module.get_productName() + ')')
    module = module.nextModule()
YAPI.FreeAPI()

8.5. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software. The only way to prevent this is to implement one of the two error handling techniques described below.

The method recommended by most programming languages for unpredictable error handling is the use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while you try to access a module, the library throws an exception. In this case, there are three possibilities:

As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for error handling, allowing you to create a robust program without needing to catch exceptions at every line of code. You simply need to call the YAPI.DisableExceptions() function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values, which can be tested by the caller when necessary. For each function, the name of each return value in case of error is systematically documented in the library reference. The name always follows the same logic: a get_state() method returns a ClassName.STATE_INVALID value, a get_currentValue method returns a ClassName.CURRENTVALUE_INVALID value, and so on. In any case, the returned value is of the expected type and is not a null pointer which would risk crashing your program. At worst, if you display the value without testing it, it will be outside the expected bounds for the returned value. In the case of functions which do not normally return information, the return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.

When you work without exceptions, you can obtain an error code and an error message explaining the source of the error. You can request them from the object which returned the error, calling the errType() and errMessage() methods. Their returned values contain the same information as in the exceptions when they are active.

9. Using Yocto-3D-V2 with C++

C++ is not the simplest language to master. However, if you take care to limit yourself to its essential functionalities, this language can very well be used for short programs quickly coded, and it has the advantage of being easily ported from one operating system to another. Under Windows, all the examples and the project models are tested with Microsoft Visual Studio 2010 Express, freely available on the Microsoft web site19. Under Mac OS X, all the examples and project models are tested with XCode 4, available on the App Store. Moreover, under Max OS X and under Linux, you can compile the examples using a command line with GCC using the provided GNUmakefile. In the same manner under Windows, a Makefile allows you to compile examples using a command line, fully knowing the compilation and linking arguments.

Yoctopuce C++ libraries20 are integrally provided as source files. A section of the low-level library is written in pure C, but you should not need to interact directly with it: everything was done to ensure the simplest possible interaction from C++. The library is naturally also available as binary files, so that you can link it directly if you prefer.

You will soon notice that the C++ API defines many functions which return objects. You do not need to deallocate these objects yourself, the API does it automatically at the end of the application.

In order to keep them simple, all the examples provided in this documentation are console applications. Naturally, the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface. You will find in the last section of this chapter all the information needed to create a wholly new project linked with the Yoctopuce libraries.

9.1. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a C++ code snipplet to use the Tilt function.


#include "yocto_api.h"
#include "yocto_tilt.h"

[...]
// Enable detection of USB devices
String  errmsg;
YAPI::RegisterHub("usb", errmsg);
[...]

// Retrieve the object used to interact with the device
YTilt *tilt;
tilt = YTilt::FindTilt("Y3DMK002-123456.tilt1");

// Hot-plug is easy: just check that the device is online
if(tilt->isOnline())
{
    // Use tilt->get_currentValue()
    [...]
}

Let's look at these lines in more details.

yocto_api.h et yocto_tilt.h

These two include files provide access to the functions allowing you to manage Yoctopuce modules. yocto_api.h must always be used, yocto_tilt.h is necessary to manage modules containing a tilt sensor, such as Yocto-3D-V2.

YAPI::RegisterHub

The YAPI::RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for. When used with the parameter "usb", it will use the modules locally connected to the computer running the library. If the initialization does not succeed, this function returns a value different from YAPI_SUCCESS and errmsg contains the error message.

YTilt::FindTilt

The YTilt::FindTilt function allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can use logical names as well, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


YTilt *tilt = YTilt::FindTilt("Y3DMK002-123456.tilt1");
YTilt *tilt = YTilt::FindTilt("Y3DMK002-123456.MyFunction");
YTilt *tilt = YTilt::FindTilt("MyModule.tilt1");
YTilt *tilt = YTilt::FindTilt("MyModule.MyFunction");
YTilt *tilt = YTilt::FindTilt("MyFunction");

YTilt::FindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by YTilt::FindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by yFindTilt provides the angle currently measured by the inclinometer. The value returned is a floating number.

yFindCompass and yFindGyro

Functions yFindCompass, yFindGyro, yFindMagnetometer and yFindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YFindTilt.

A real example

Launch your C++ environment and open the corresponding sample project provided in the directory Examples/Doc-GettingStarted-Yocto-3D-V2 of the Yoctopuce library. If you prefer to work with your favorite text editor, open the file main.cpp, and type make to build the example when you are done.

In this example, you will recognize the functions explained above, but this time used with all side materials needed to make it work nicely as a small demo.

#include "yocto_api.h"
#include "yocto_tilt.h"
#include "yocto_compass.h"
#include "yocto_gyro.h"
#include "yocto_accelerometer.h"
#include <iostream>
#include <stdlib.h>
#include <iostream>
#include <iomanip>

using namespace std;

static void usage(void)
{
  cout << "usage: demo <serial_number> " << endl;
  cout << "       demo <logical_name>" << endl;
  cout << "       demo any" << endl;
  u64 now = YAPI::GetTickCount();
  while (YAPI::GetTickCount() - now < 3000) {
    // wait 3 sec to show the message
  }
  exit(1);
}

int main(int argc, const char * argv[])
{
  string errmsg, target;
  YTilt *anytilt, *tilt1, *tilt2;
  YCompass *compass;
  YAccelerometer *accelerometer;
  YGyro *gyro;

  if(argc < 2) {
    usage();
  }
  target = (string) argv[1];

  // Setup the API to use local USB devices
  if(YAPI::RegisterHub("usb", errmsg) != YAPI::SUCCESS) {
    cerr << "RegisterHub error: " << errmsg << endl;
    return 1;
  }

  // try to find a valid serial number
  if(target == "any") {
    anytilt = YTilt::FirstTilt();
    if (anytilt == NULL) {
      cout << "No module connected (check USB cable)" << endl;
      return 1;
    }
  } else {
    anytilt = YTilt::FindTilt(target + ".tilt1");
    if (!anytilt->isOnline()) {
      cout << "Module not connected (check identification and USB cable)" << endl;
      return 1;
    }
  }
  string serial = anytilt->get_module()->get_serialNumber();

  // retrieve all sensors on the device matching the serial
  tilt1 = YTilt::FindTilt(serial + ".tilt1");
  tilt2 = YTilt::FindTilt(serial + ".tilt2");
  compass = YCompass::FindCompass(serial + ".compass");
  accelerometer = YAccelerometer::FindAccelerometer(serial + ".accelerometer");
  gyro = YGyro::FindGyro(serial + ".gyro");
  int count = 0;

  while(1) {
    if(!tilt1->isOnline()) {
      cout << "device disconnected";
      break;
    }
    if ((count % 10) == 0) {
      cout << "tilt1\ntilt2\ncompass\tacc\tgyro" << endl;
    }
    cout <<  std::setprecision(2) << std::setw(8)
         << tilt1->get_currentValue() << "\t"
         << tilt2->get_currentValue() << "\t"
         << compass->get_currentValue() << "\t"
         << accelerometer->get_currentValue() << "\t"
         << gyro->get_currentValue() << endl;
    count++;
    YAPI::Sleep(250, errmsg);
  }
  YAPI::FreeAPI();
  return 0;
}
 

9.2. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.

#include <iostream>
#include <stdlib.h>

#include "yocto_api.h"

using namespace std;

static void usage(const char *exe)
{
  cout << "usage: " << exe << " <serial or logical name> [ON/OFF]" << endl;
  exit(1);
}


int main(int argc, const char * argv[])
{
  string      errmsg;

  // Setup the API to use local USB devices
  if(YAPI::RegisterHub("usb", errmsg) != YAPI::SUCCESS) {
    cerr << "RegisterHub error: " << errmsg << endl;
    return 1;
  }

  if(argc < 2)
    usage(argv[0]);

  YModule *module = YModule::FindModule(argv[1]);  // use serial or logical name

  if (module->isOnline()) {
    if (argc > 2) {
      if (string(argv[2]) == "ON")
        module->set_beacon(Y_BEACON_ON);
      else
        module->set_beacon(Y_BEACON_OFF);
    }
    cout << "serial:       " << module->get_serialNumber() << endl;
    cout << "logical name: " << module->get_logicalName() << endl;
    cout << "luminosity:   " << module->get_luminosity() << endl;
    cout << "beacon:       ";
    if (module->get_beacon() == Y_BEACON_ON)
      cout << "ON" << endl;
    else
      cout << "OFF" << endl;
    cout << "upTime:       " << module->get_upTime() / 1000 << " sec" << endl;
    cout << "USB current:  " << module->get_usbCurrent() << " mA" << endl;
    cout << "Logs:" << endl << module->get_lastLogs() << endl;
  } else {
    cout << argv[1] << " not connected (check identification and USB cable)"
         << endl;
  }
  YAPI::FreeAPI();
  return 0;
}
 

Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding set_xxx() function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the revertFromFlash() method. The short example below allows you to modify the logical name of a module.

#include <iostream>
#include <stdlib.h>

#include "yocto_api.h"

using namespace std;

static void usage(const char *exe)
{
  cerr << "usage: " << exe << " <serial> <newLogicalName>" << endl;
  exit(1);
}

int main(int argc, const char * argv[])
{
  string      errmsg;

  // Setup the API to use local USB devices
  if(YAPI::RegisterHub("usb", errmsg) != YAPI::SUCCESS) {
    cerr << "RegisterHub error: " << errmsg << endl;
    return 1;
  }

  if(argc < 2)
    usage(argv[0]);

  YModule *module = YModule::FindModule(argv[1]);  // use serial or logical name

  if (module->isOnline()) {
    if (argc >= 3) {
      string newname =  argv[2];
      if (!yCheckLogicalName(newname)) {
        cerr << "Invalid name (" << newname << ")" << endl;
        usage(argv[0]);
      }
      module->set_logicalName(newname);
      module->saveToFlash();
    }
    cout << "Current name: " << module->get_logicalName() << endl;
  } else {
    cout << argv[1] << " not connected (check identification and USB cable)"
         << endl;
  }
  YAPI::FreeAPI();
  return 0;
}
 

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not NULL. Below a short example listing the connected modules.

#include <iostream>

#include "yocto_api.h"

using namespace std;

int main(int argc, const char * argv[])
{
  string      errmsg;

  // Setup the API to use local USB devices
  if(YAPI::RegisterHub("usb", errmsg) != YAPI::SUCCESS) {
    cerr << "RegisterHub error: " << errmsg << endl;
    return 1;
  }

  cout << "Device list: " << endl;

  YModule *module = YModule::FirstModule();
  while (module != NULL) {
    cout << module->get_serialNumber() << " ";
    cout << module->get_productName()  << endl;
    module = module->nextModule();
  }
  YAPI::FreeAPI();
  return 0;
}
 

9.3. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software. The only way to prevent this is to implement one of the two error handling techniques described below.

The method recommended by most programming languages for unpredictable error handling is the use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while you try to access a module, the library throws an exception. In this case, there are three possibilities:

As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for error handling, allowing you to create a robust program without needing to catch exceptions at every line of code. You simply need to call the YAPI.DisableExceptions() function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values, which can be tested by the caller when necessary. For each function, the name of each return value in case of error is systematically documented in the library reference. The name always follows the same logic: a get_state() method returns a ClassName.STATE_INVALID value, a get_currentValue method returns a ClassName.CURRENTVALUE_INVALID value, and so on. In any case, the returned value is of the expected type and is not a null pointer which would risk crashing your program. At worst, if you display the value without testing it, it will be outside the expected bounds for the returned value. In the case of functions which do not normally return information, the return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.

When you work without exceptions, you can obtain an error code and an error message explaining the source of the error. You can request them from the object which returned the error, calling the errType() and errMessage() methods. Their returned values contain the same information as in the exceptions when they are active.

9.4. Integration variants for the C++ Yoctopuce library

Depending on your needs and on your preferences, you can integrate the library into your projects in several distinct manners. This section explains how to implement the different options.

Integration in source format (recommended)

Integrating all the sources of the library into your projects has several advantages:

To integrate the source code, the easiest way is to simply include the Sources directory of your Yoctopuce library into your IncludePath, and to add all the files of this directory (including the sub-directory yapi) to your project.

For your project to build correctly, you need to link with your project the prerequisite system libraries, that is:

Integration as a static library

With the integration of the Yoctopuce library as a static library, you do not need to install a dynamic library specific to Yoctopuce, everything is in the executable.

To use the static library, you must first compile it using the shell script build.sh on UNIX, or build.bat on Windows. This script, located in the root directory of the library, detects the OS and recompiles all the corresponding libraries as well as the examples.

Then, to integrate the static Yoctopuce library to your project, you must include the Sources directory of the Yoctopuce library into your IncludePath, and add the sub-directory Binaries/... corresponding to your operating system into your libPath.

Finally, for you project to build correctly, you need to link with your project the Yoctopuce library and the prerequisite system libraries:

Note, under Linux, if you wish to compile in command line with GCC, it is generally advisable to link system libraries as dynamic libraries, rather than as static ones. To mix static and dynamic libraries on the same command line, you must pass the following arguments:

gcc (...) -Wl,-Bstatic -lyocto-static -Wl,-Bdynamic -lm -lpthread -lusb-1.0 -lstdc++

Integration as a dynamic library

Integration of the Yoctopuce library as a dynamic library allows you to produce an executable smaller than with the two previous methods, and to possibly update this library, if a patch reveals itself necessary, without needing to recompile the source code of the application. On the other hand, it is an integration mode which systematically requires you to copy the dynamic library on the target machine where the application will run (yocto.dll for Windows, libyocto.so.1.0.1 for Mac OS X and Linux).

To use the dynamic library, you must first compile it using the shell script build.sh on UNIX, or build.bat on Windows. This script, located in the root directory of the library, detects the OS and recompiles all the corresponding libraries as well as the examples.

Then, To integrate the dynamic Yoctopuce library to your project, you must include the Sources directory of the Yoctopuce library into your IncludePath, and add the sub-directory Binaries/... corresponding to your operating system into your LibPath.

Finally, for you project to build correctly, you need to link with your project the dynamic Yoctopuce library and the prerequisite system libraries:

With GCC, the command line to compile is simply:

gcc (...) -lyocto -lm -lpthread -lusb-1.0 -lstdc++

10. Using Yocto-3D-V2 with C#

C# (pronounced C-Sharp) is an object-oriented programming language promoted by Microsoft, it is somewhat similar to Java. Like Visual-Basic and Delphi, it allows you to create Windows applications quite easily. All the examples and the project models are tested with Microsoft C# 2010 Express, freely available on the Microsoft web site21.

Our programming library is also compatible with Mono, the open source version of C# that also works on Linux and MacOS. You will find on our web site various articles that describe how to configure Mono to use our library.

10.1. Installation

Download the Visual C# Yoctopuce library from the Yoctopuce web site22. There is no setup program, simply copy the content of the zip file into the directory of your choice. You mostly need the content of the Sources directory. The other directories contain the documentation and a few sample programs. All sample projects are Visual C# 2010, projects, if you are using a previous version, you may have to recreate the projects structure from scratch.

10.2. Using the Yoctopuce API in a Visual C# project

The Visual C#.NET Yoctopuce library is composed of a DLL and of source files in Visual C#. The DLL is not a .NET DLL, but a classic DLL, written in C, which manages the low level communications with the modules23. The source files in Visual C# manage the high level part of the API. Therefore, your need both this DLL and the .cs files of the sources directory to create a project managing Yoctopuce modules.

Configuring a Visual C# project

The following indications are provided for Visual Studio Express 2010, but the process is similar for other versions. Start by creating your project. Then, on the Solution Explorer panel, right click on your project, and select "Add" and then "Add an existing item".

A file selection window opens. Select the yocto_api.cs file and the files corresponding to the functions of the Yoctopuce modules that your project is going to manage. If in doubt, select all the files.

You then have the choice between simply adding these files to your project, or to add them as links (the Add button is in fact a scroll-down menu). In the first case, Visual Studio copies the selected files into your project. In the second case, Visual Studio simply keeps a link on the original files. We recommend you to use links, which makes updates of the library much easier.

Then add in the same manner the yapi.dll DLL, located in the Sources/dll directory24. Then, from the Solution Explorer window, right click on the DLL, select Properties and in the Properties panel, set the Copy to output folder to always. You are now ready to use your Yoctopuce modules from Visual Studio.

In order to keep them simple, all the examples provided in this documentation are console applications. Naturally, the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface.

10.3. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a C# code snipplet to use the Tilt function.


[...]
// Enable detection of USB devices
string errmsg ="";
YAPI.RegisterHub("usb", errmsg);
[...]

// Retrieve the object used to interact with the device
YTilt tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1");

// Hot-plug is easy: just check that the device is online
if (tilt.isOnline())
{
    // Use tilt.get_currentValue()
    [...]
}

Let's look at these lines in more details.

YAPI.RegisterHub

The YAPI.RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for. When used with the parameter "usb", it will use the modules locally connected to the computer running the library. If the initialization does not succeed, this function returns a value different from YAPI.SUCCESS and errmsg contains the error message.

YTilt.FindTilt

The YTilt.FindTilt function allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can use logical names as well, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1");
tilt = YTilt.FindTilt("Y3DMK002-123456.MyFunction");
tilt = YTilt.FindTilt("MyModule.tilt1");
tilt = YTilt.FindTilt("MyModule.MyFunction");
tilt = YTilt.FindTilt("MyFunction");

YTilt.FindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by YTilt.FindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by YTilt.FindTilt provides the value of orientation measured by the tilt sensor. The value returned is a floating number.

YCompass.FindCompass, YGyro.FindGyro...

Functions YCompass.FindCompass, YMagnetometer.FindMagnetometer, YGyro.FindGyro and YAccelerometer.FindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YTilt.FindTilt.

A real example

Launch Microsoft Visual C# and open the corresponding sample project provided in the directory Examples/Doc-GettingStarted-Yocto-3D-V2 of the Yoctopuce library.

In this example, you will recognize the functions explained above, but this time used with all side materials needed to make it work nicely as a small demo.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
    static void usage()
    {
      string execname = System.AppDomain.CurrentDomain.FriendlyName;
      Console.WriteLine(execname + " <serial_number>");
      Console.WriteLine(execname + " <logical_name>");
      Console.WriteLine(execname + " any  ");
      System.Threading.Thread.Sleep(2500);
      Environment.Exit(0);
    }

    static void Main(string[] args)
    {
      string errmsg = "";
      string target;

      YTilt anytilt, tilt1, tilt2;
      YCompass compass;
      YAccelerometer accelerometer;
      YGyro gyro;

      if (args.Length < 1)
        usage();
      target = args[0].ToUpper();

      // Setup the API to use local USB devices
      if (YAPI.RegisterHub("usb", ref errmsg) != YAPI.SUCCESS) {
        Console.WriteLine("RegisterHub error: " + errmsg);
        Environment.Exit(0);
      }

      if (target == "ANY") {
        anytilt = YTilt.FirstTilt();
        if (anytilt == null) {
          Console.WriteLine("No module connected (check USB cable)");
          Environment.Exit(0);
        }
      } else {
        anytilt = YTilt.FindTilt(target + ".tilt1");
        if (!anytilt.isOnline()) {
          Console.WriteLine("Module not connected");
          Console.WriteLine("check identification and USB cable");
          Environment.Exit(0);
        }
      }

      string serial = anytilt.get_module().get_serialNumber();
      tilt1 = YTilt.FindTilt(serial + ".tilt1");
      tilt2 = YTilt.FindTilt(serial + ".tilt2");
      compass = YCompass.FindCompass(serial + ".compass");
      accelerometer = YAccelerometer.FindAccelerometer(serial + ".accelerometer");
      gyro = YGyro.FindGyro(serial + ".gyro");
      int count = 0;

      if (!tilt1.isOnline()) {
        Console.WriteLine("device disconnected");
        Environment.Exit(0);
      }

      while (tilt1.isOnline()) {

        if (count % 10 == 0) Console.WriteLine("tilt1   tilt2   compass   acc   gyro");

        Console.Write(tilt1.get_currentValue().ToString() + "\t");
        Console.Write(tilt2.get_currentValue().ToString() + "\t");
        Console.Write(compass.get_currentValue().ToString() + "\t");
        Console.Write(accelerometer.get_currentValue().ToString() + "\t");
        Console.WriteLine(gyro.get_currentValue().ToString());

        YAPI.Sleep(250, ref errmsg);
      }
      YAPI.FreeAPI();
    }
  }
}

10.4. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
  class Program
  {
    static void usage()
    {
      string execname = System.AppDomain.CurrentDomain.FriendlyName;
      Console.WriteLine("Usage:");
      Console.WriteLine(execname + " <serial or logical name> [ON/OFF]");
      System.Threading.Thread.Sleep(2500);
      Environment.Exit(0);
    }

    static void Main(string[] args)
    {
      YModule m;
      string errmsg = "";

      if (YAPI.RegisterHub("usb", ref errmsg) !=  YAPI.SUCCESS) {
        Console.WriteLine("RegisterHub error: " + errmsg);
        Environment.Exit(0);
      }


      if (args.Length < 1)  usage();

      m = YModule.FindModule(args[0]); // use serial or logical name

      if (m.isOnline()) {
        if (args.Length >= 2) {
          if (args[1].ToUpper() == "ON") {
            m.set_beacon(YModule.BEACON_ON);
          }
          if (args[1].ToUpper() == "OFF") {
            m.set_beacon(YModule.BEACON_OFF);
          }
        }

        Console.WriteLine("serial:       " + m.get_serialNumber());
        Console.WriteLine("logical name: " + m.get_logicalName());
        Console.WriteLine("luminosity:   " + m.get_luminosity().ToString());
        Console.Write("beacon:       ");
        if (m.get_beacon() == YModule.BEACON_ON)
          Console.WriteLine("ON");
        else
          Console.WriteLine("OFF");
        Console.WriteLine("upTime:       " + (m.get_upTime() / 1000 ).ToString() + " sec");
        Console.WriteLine("USB current:  " + m.get_usbCurrent().ToString() + " mA");
        Console.WriteLine("Logs:\r\n" + m.get_lastLogs());

      } else {
        Console.WriteLine(args[0] + " not connected (check identification and USB cable)");
      }
      YAPI.FreeAPI();
    }
  }
}
 

Each property xxx of the module can be read thanks to a method of type YModule.get_xxxx(), and properties which are not read-only can be modified with the help of the YModule.set_xxx() method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding YModule.set_xxx() function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the YModule.saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the YModule.revertFromFlash() method. The short example below allows you to modify the logical name of a module.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
    static void usage()
    {
      string execname = System.AppDomain.CurrentDomain.FriendlyName;
      Console.WriteLine("Usage:");
      Console.WriteLine("usage: demo <serial or logical name> <new logical name>");
      System.Threading.Thread.Sleep(2500);
      Environment.Exit(0);
    }

    static void Main(string[] args)
    {
      YModule m;
      string errmsg = "";
      string newname;

      if (args.Length != 2) usage();

      if (YAPI.RegisterHub("usb", ref errmsg) !=  YAPI.SUCCESS) {
        Console.WriteLine("RegisterHub error: " + errmsg);
        Environment.Exit(0);
      }

      m = YModule.FindModule(args[0]); // use serial or logical name

      if (m.isOnline()) {
        newname = args[1];
        if (!YAPI.CheckLogicalName(newname)) {
          Console.WriteLine("Invalid name (" + newname + ")");
          Environment.Exit(0);
        }

        m.set_logicalName(newname);
        m.saveToFlash(); // do not forget this

        Console.Write("Module: serial= " + m.get_serialNumber());
        Console.WriteLine(" / name= " + m.get_logicalName());
      } else {
        Console.Write("not connected (check identification and USB cable");
      }
      YAPI.FreeAPI();
    }
  }
}
 

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the YModule.saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the YModule.yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not null. Below a short example listing the connected modules.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      YModule m;
      string errmsg = "";

      if (YAPI.RegisterHub("usb", ref errmsg) !=  YAPI.SUCCESS) {
        Console.WriteLine("RegisterHub error: " + errmsg);
        Environment.Exit(0);
      }

      Console.WriteLine("Device list");
      m = YModule.FirstModule();
      while (m != null) {
        Console.WriteLine(m.get_serialNumber() + " (" + m.get_productName() + ")");
        m = m.nextModule();
      }
      YAPI.FreeAPI();
    }
  }
}
 

10.5. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software. The only way to prevent this is to implement one of the two error handling techniques described below.

The method recommended by most programming languages for unpredictable error handling is the use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while you try to access a module, the library throws an exception. In this case, there are three possibilities:

As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for error handling, allowing you to create a robust program without needing to catch exceptions at every line of code. You simply need to call the YAPI.DisableExceptions() function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values, which can be tested by the caller when necessary. For each function, the name of each return value in case of error is systematically documented in the library reference. The name always follows the same logic: a get_state() method returns a ClassName.STATE_INVALID value, a get_currentValue method returns a ClassName.CURRENTVALUE_INVALID value, and so on. In any case, the returned value is of the expected type and is not a null pointer which would risk crashing your program. At worst, if you display the value without testing it, it will be outside the expected bounds for the returned value. In the case of functions which do not normally return information, the return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.

When you work without exceptions, you can obtain an error code and an error message explaining the source of the error. You can request them from the object which returned the error, calling the errType() and errMessage() methods. Their returned values contain the same information as in the exceptions when they are active.

11. Using the Yocto-3D-V2 with LabVIEW

LabVIEW is edited by National Instruments since 1986. It is a graphic development environment: rather than writing lines of code, the users draw their programs, somewhat like a flow chart. LabVIEW was designed mostly to interface measuring tools, hence the Virtual Instruments name for LabVIEW programs. With visual programming, drawing complex algorithms becomes quickly fastidious. The LabVIEW Yoctopuce library was thus designed to make it as easy to use as possible. In other words, LabVIEW being an environment extremely different from other languages supported by Yoctopuce, there are major differences between the LabVIEW API and the other APIs.

11.1. Architecture

The LabVIEW library is based on the Yoctopuce DotNetProxy library contained in the DotNetProxyLibrary.dll DLL. In fact, it is this DotNetProxy library which takes care or most of the work by relying on the C# library which, in turn, uses the low level library coded in yapi.dll (32bits) and amd64\yapi.dll( 64bits).


LabVIEW Yoctopuce API architecture

You must therefore imperatively distribute the DotNetProxyLibrary.dll, yapi.dll, and amd64\yapi.dll with your LabVIEW applications using the Yoctopuce API.

If need be, you can find the low level API sources in the C# library and the DotNetProxyLibrary.dll sources in the DotNetProxy library.

11.2. Compatibility

Firmware

For the LabVIEW Yoctopuce library to work correctly with your Yoctopuce modules, these modules need to have firmware 37120, or higher.

LabVIEW for Linux and MacOS

At the time of writing, the LabVIEW Yoctopuce API has been tested under Windows only. It is therefore most likely that it simply does not work with the Linux and MacOS versions of LabVIEW.

LabVIEW NXG

The LabVIEW Yoctopuce library uses many techniques which are not yet available in the new generation of LabVIEW. The library is therefore absolutely not compatible with LabVIEW NXG.

About DotNewProxyLibrary.dll

In order to be compatible with as many versions of Windows as possible, including Windows XP, the DotNetProxyLibrary.dll library is compiled in .NET 3.5, which is available by default on all the Windows versions since XP.

11.3. Installation

Download the LabVIEW library from the Yoctopuce web site25. It is a ZIP file in which there is a distinct directory for each version of LabVIEW. Each of these directories contains two subdirectories: the first one contains programming examples for each Yoctopuce product; the second one, called VIs, contains all the VIs of the API and the required DLLs.

Depending on Windows configuration and the method used to copy the DotNetProxyLibrary.dll on your system, Windows may block it because it comes from an other computer. This may happen when the library zip file is uncompressed with Window's file explorer. If the DLL is blocked, LabVIEW will not be able to load it and an error 1386 will occur whenever any of the Yoctopuce VIs is executed.

There are two ways to fix this. The simplest is to unblock the file with the Windows file explorer: right click / properties on the DotNetProxyLibrary.dll file, and click on the unblock button. But this has to be done each time a new version of the DLL is copied on your system.


Unblock the DotNetProxyLibrary DLL.

Alternatively, one can modify the LabVIEW configuration by creating, in the same directory as the labview.exe executable, an XML file called labview.exe.config containing the following code:


<?xml version ="1.0"?>
<configuration>
 <runtime>
 <loadFromRemoteSources enabled="true" />
 </runtime>
</configuration>

Make sure to select the correct directory depending on the LabVIEW version you are using (32 bits vs. 64 bits). You can find more information about this file on the National Instruments web site.26

To install the LabVIEW Yoctopuce API, there are several methods.

Method 1 : "Take-out" installation

The simplest way to use the Yoctopuce library is to copy the content of the VIs directory wherever you want and to use the VIs in LabVIEW with a simple drag-n-drop operation.

To use the examples provided with the API, it is simpler if you add the directory of Yoctopuce VIs into the list of where LabVIEW must look for VIs that it has not found. You can access this list through the Tools > Options > Paths > VI Search Path menu.


Configuring the "VI Search Path"

Method 2 : Provided installer

In each LabVIEW folder of the Library, you will find a VI named "Install.vi", just open the one matching your LabVIEW version.


The provider installer

This installer provide 3 installation options:

Install: Keep VI and documentation files where they are.

With this option, VI files are keep in the place where the library has been unzipped. So you will have to make sure these files are not deleted as long as you need them. Here is what the installer will do if that option is chosen:

Install: Copy VI and documentation files into LabVIEW's vi.lib folder

In that case all required files are copied inside the LabVIEW's installation folder, so you will be able to delete the installation folder once the original installation is complete. Note that programming examples won't be copied. Here is the exact behaviour of the installer in that case:

Uninstall Yoctopuce Library

this option is meant to remove the LabVIEW library from your LabVIEW installation, here is how it is done:

In any case, if the labview.ini file needs to be modified, a backup copy will be made beforehand.

The installer identifies Yoctopuce VIs library folders by checking the presence of the YRegisterHub.vi file in said folders.

Once the installation is complete, a Yoctopuce palette will appear in Functions/Addons menu.

Method 3 : Installation in a LabVIEW palette (ancillary method)

The steps to manually install the VIs directly in the LabVIEW palette are somewhat more complex. You can find the detailed procedure on the National Instruments web site 27, but here is a summary:

  1. Create a Yoctopuce/API directory in the C:\Program Files\National Instruments\LabVIEW xxxx\vi.lib directory and copy all the VIs and DLLs of the VIs directory into it.
  2. Create a Yoctopuce directory in the C:\Program Files\National Instruments\LabVIEW xxxx\menus\Categories directory.
  3. Run LabVIEW and select the option Tools>Advanced>Edit Palette Set

    Three windows pop up:

    • "Edit Controls and Functions Palette Set"
    • "Functions"
    • "Controls"
    .

    In the Function window, there is a Yoctopuce icon. Double-click it to create an empty "Yoctopuce" window.

  4. In the Yoctopuce window, perform a Right click>Insert>Vi(s)..

    in order to open a file chooser. Put the file chooser in the vi.lib\Yoctopuce\API directory that you have created in step 1 and click on Current Folder

    All the Yoctopuce VIs now appear in the Yoctopuce window. By default, they are sorted by alphabetical order, but you can arrange them as you see fit by moving them around with the mouse. For the palette to be easy to use, we recommend to reorganize the icons over 8 columns.
  5. In the "Edit Controls and Functions Palette Set" window, click on the "Save Changes" button, the window indicates that it has created a dir.mnu file in your Documents directory.

    Copy this file in the "menus\Categories\Yoctopuce" directory that you have created in step 2.
  6. Restart LabVIEW, the LabVIEW palette now contains a Yoctopuce sub-palette with all the VIs of the API.

11.4. Presentation of Yoctopuce VIs

The LabVIEW Yoctopuce library contains one VI per class of the Yoctopuce API, as well as a few special VIs. All the VIs have the traditional connectors Error IN and Error Out.

YRegisterHub

The YRegisterHub VI is used to initialize the API. You must imperatively call this VI once before you do anything in relation with Yoctopuce modules.


The YRegisterHub VI

The YRegisterHub VI takes a url parameter which can be:

In the case of an IP address, the YRegisterHub VI tries to contact this address and generates and error if it does not succeed, unless the async parameter is set to TRUE. If async is set to TRUE, no error is generated and Yoctopuce modules corresponding to that IP address become automatically available as soon as the said machine can be reached.

If everything went well, the successful output contains the value TRUE. In the opposite case, it contains the value FALSE and the error msg output contains a string of characters with a description of the error.

You can use several YRegisterHub VIs with distinct URLs if you so wish. However, on the same machine, there can be only one process accessing local Yoctopuce modules directly by USB (url set to "usb"). You can easily work around this limitation by running the VirtualHub software on the local machine and using the "127.0.0.1" url.

YFreeAPI

The YFreeAPI VI enables you to free resources allocated by the Yoctopuce API.


The YFreeAPI VI

You must call the YFreeAPI VI when your code is done with the Yoctopuce API. Otherwise, direct USB access (url set to "usb") could stay locked after the execution of your VI, and stay so for as long as LabVIEW is not completely closed.

Structure of the VIs corresponding to a class

The other VIs correspond to each function/class of the Yoctopuce API, they all have the same structure:


Structure of most VIs of the API.

You can find the list of functions available on your Yocto-3D-V2 in chapter Programming, general concepts.

If the desired function (parameter name) is not available, this does not generate an error, but the is online output contains FALSE and all the other outputs contain the value "N/A" whenever possible. If the desired function becomes available later in the life of your program, is online switches to TRUE automatically.

If the name parameter contains an empty string, the VI targets the first available function of the same type. If no function is available, is online is set to FALSE.

The YModule VI

The YModule VI enables you to interface with the "module" section of each Yoctopuce module. It enables you to drive the module led and to know the serial number of the module.


The YModule VI

The name input works slightly differently from other VIs. If it is called with a name parameter corresponding to a function name, the YModule VI finds the Module function of the module hosting the function. You can therefore easily find the serial number of the module of any function. This enables you to build the name of other functions which are located on the same module. The following example finds the first available YHumidity function and builds the name of the YTemperature function located on the same module. The examples provided with the Yoctopuce API make extensive use of this technique.


Using the YModule VI to retrieve functions hosted on the same module

The sensor VIs

All the VIs corresponding to Yoctopuce sensors have exactly the same geometry. Both outputs enable you to retrieve the value measured by the corresponding sensor as well the unit used.


The sensor VIs have all exactly the same geometry

The update freq input parameter is a character string enabling you to configure the way in which the output value is updated:

The update frequency of the VI is a parameter managed by the physical Yoctopuce module. If several VIs try to change the frequency of the same sensor, the valid configuration is that of the latest call. It is however possible to set different update frequencies to different sensors on the same Yoctopuce module.


Changing the update frequency of the same module

The update frequency of the VI is completely independent from the sampling frequency of the sensor, which you usually cannot modify. It is useless and counterproductive to define an update frequency higher than the sensor sampling frequency.

11.5. Functioning and use of VIs

Here is one of the simplest example of VIs using the Yoctopuce API.


Minimal example of use of the LabVIEW Yoctopuce API

This example is based on the YSensor VI which is a generic VI enabling you to interface any sensor function of a Yoctopuce module. You can replace this VI by any other from the Yoctopuce API, they all have the same geometry and work in the same way. This example is limited to three actions:

  1. It initializes the API in native ("usb") mode with the YRegisterHub VI.
  2. It displays the value of the first Yoctopuce sensor it finds thanks to the YSensor VI.
  3. It frees the API thanks to the YFreeAPI VI.

This example automatically looks for an available sensor. If there is such a sensor, we can retrieve its name through the hardware name output and the isOnline output equals TRUE. If there is no available sensor, the VI does not generate an error but emulates a ghost sensor which is "offline". However, if later in the life of the application, a sensor becomes available because it has been connected, isOnline switches to TRUE and the hardware name contains the name of the sensor. We can therefore easily add a few indicators in the previous example to know how the executions goes.


Use of the hardware name and isOnline outputs

The VIs of the Yoctopuce API are actually an entry door into the library. Internally, this mechanism works independently of the Yoctopuce VIs. Indeed, most communications with electronic modules are managed automatically as background tasks. Therefore, you do not necessarily need to take any specific care to use Yoctopuce VIs, you can for example use them in a non-delayed loop without creating any specific problem for the API.


The Yoctopuce VIs can be used in a non-delayed loop

Note that the YRegisterHub VI is not inside the loop. The YRegisterHub VI is used to initialize the API. Unless you have several URLs that you need to register, it is better to call the YRegisterHub VI only once.

When the name parameter is initialized to an empty string, the Yoctopuce VIs automatically look for a function they can work with. This is very handy when you know that there is only one function of the same type available and when you do not want to manage its name. If the name parameter contains a hardware name or a logical name, the VI looks for the corresponding function. If it does not find it, it emulates an offline function while it waits for the true function to become available.


Using names to identify the functions to be used

Error handling

The LabVIEW Yoctopuce API is coded to handle errors as smoothly as possible: for example, if you use a VI to access a function which does not exist, the isOnline output is set to FALSE, the other outputs are set to NaN, and thus the inputs do not have any impact. Fatal errors are propagated through the traditional error in, error out channel.

However, the YRegisterHub VI manages connection errors slightly differently. In order to make them easier to manage, connection errors are signaled with Success and error msg outputs. If there is an issue during a call to the YRegisterHub VI, Success contains FALSE and error msg contains a description of the error.


Error handling

The most common error message is "Another process is already using yAPI". It means that another application, LabVIEW or other, already uses the API in native USB mode. For technical reasons, the native USB API can be used by only one application at the same time on the same machine. You can easily work around this limitation by using the network mode.

11.6. Using Proxy objects

The Yoctopuce API contains hundreds of methods, functions, and properties. It was not possible, or desirable, to create a VI for each of them. Therefore, there is a VI per class that shows the two properties that Yoctopuce deemed the most useful, but this does not mean that the rest is not available.

Each VI corresponding to a class has two connectors create ref and optional ref which enable you to obtain a reference on the Proxy object of the .NET Proxy API on which the LabVIEW library is built.


The connectors to obtain a reference on the Proxy object corresponding to the VI

To obtain this reference, you only need to set optional ref to TRUE. Note, it is essential to close all references created in this way, otherwise you risk to quickly saturate the computer memory.

Here is an example which uses this technique to change the luminosity of the leds of a Yoctopuce module.



Regulating the luminosity of the leds of a module

Note that each reference allows you to obtain properties (property nodes) as well as methods (invoke nodes). By convention, properties are optimized to generate a minimum of communication with the modules. Therefore, we recommend to use them rather than the corresponding get_xxx and set_xxx methods which might seem equivalent but which are not optimized. Properties also enable you to retrieve the various constants of the API, prefixed with the "_" character. For technical reasons, the get_xxx and set_xxx methods are not all available as properties.



Property and Invoke nodes: Using properties, methods and constants

You can find a description of all the available properties, functions, and methods in the documentation of the .NET Proxy API.

Network mode

On a given machine, there can be only one process accessing local Yoctopuce modules directly by USB (url set to "usb"). It is however possible that multiple process connect in parallel to YoctoHubs31 or tp a machine on which VirtualHub32 is running, including the local machine. Therefore, if you use the local address of your machine (127.0.0.1) and if a VirtualHub runs on it, you can work around the limitation which prevents using the native USB API in parallel.


Network mode

In the same way, there is no limitation on the number of network interfaces to which the API can connect itself in parallel. This means that it is quite possible to make multiple calls to the YRegisterHub VI. This is the only case where it is useful to call the YRegisterHub VI several times in the life of the application.


You can have multiple network connections

By default, the YRegisterHub VI tries to connect itself on the address given as parameter and generates an error (success=FALSE) when it cannot do so because nobody answers. But if the async parameter is initialized to TRUE, no error is generated when the connection does not succeed. If the connection becomes possible later in the life of the application, the corresponding modules are automatically made available.


Asynchronous connection

11.7. Managing the data logger

Almost all the Yoctopuce sensors have a data logger which enables you to store the measures of the sensors in the non-volatile memory of the module. You can configure the data logger with the VirtualHub, but also with a little bit of LabVIEW code.

Logging

To do so, you must configure the logging frequency by using the "LogFrequency" property which you can reach with a reference on the Proxy object of the sensor you are using. Then, you must turn the data logger on thanks to the YDataLogger VI. Note that, like with the YModule VI, you can obtain the YDataLogger VI corresponding to a module with its own name, but also with the name of any of the functions available on the same module.


Activating the data logger

Reading

You can retrieve the data in the data logger with the YDataLoggerContents VI.


The YDataLoggerContents VI

Retrieving the data from the logger of a Yoctopuce module is a slow process which can take up to several tens of seconds. Therefore, we designed the VI enabling this operation to work iteratively.

As a first step, you must call the VI with a sensor name, a start date, and an end date (UTC UNIX timestamp). The (0,0) pair enables you to obtain the complete content of the data logger. This first call enables you to obtain a summary of the data logger content and a context.

As a second step, you must call the YDataLoggerContents VI in a loop with the context parameter, until the progress output reaches the 100 value. At this time, the data output represents the content of the data logger.


Retrieving the content of the data logger

The results and the summary are returned as an array of structures containing the following fields:

Note that if the logging frequency is superior to 1Hz, the data logger stores only current values. In this case, averageValue, minValue, and maxValue share the same value.

11.8. Function list

Each VI corresponding to an object of the Proxy API enables you to list all the functions of the same class with the getSimilarfunctions() method of the corresponding Proxy object. Thus, you can easily perform an inventory of all the connected modules, of all the connected sensors, of all the connected relays, and so on.


Retrieving the list of all the modules which are connected

11.9. A word on performances

The LabVIEW Yoctopuce API is optimized so that all the VIs and .NET Proxy API object properties generate a minimum of communication with Yoctopuce modules. Thus, you can use them in loops without taking any specific precaution: you do not have to slow down the loops with a timer.


These two loops generate little USB communication and do not need to be slowed down

However, almost all the methods of the available Proxy objects initiate a communication with the Yoctopuce modules each time they are called. You should therefore avoid calling them too often without purpose.


This loop, using a method, must be slowed down

11.10. A full example of a LabVIEW program

Here is a short example of how to use the Yocto-3D-V2 in LabVIEW. After a call to the RegisterHub VI, the YAccelerometer VI finds the first accelerometer sensor available, then use the YModule VI to find out the device serial number. This number is used to build the name of all sensors present on the device. Theses names are used to initialize one VI per sensor. This technique avoids ambiguities when several Yocto-3D-V2 are connected at the same time. Once every VI is initialized, the sensor value can be displayed. When the application is about to exit, it frees the Yoctopuce API, thanks to the YFreeAPI VI.


Example of Yocto-3D-V2 usage in LabVIEW

If you read this documentation on screen, you can zoom on the image above. You can also find this example in the LabVIEW Yoctopuce library.

11.11. Differences from other Yoctopuce APIs

Yoctopuce does everything it can to maintain a strong coherence between its different programming libraries. However, LabVIEW being clearly apart as an environment, there are, as a consequence, important differences from the other libraries.

These differences were introduced to make the use of modules as easy as possible and requiring a minimum of LabVIEW code.

YFreeAPI

In the opposite to other languages, you must absolutely free the native API by calling the YFreeAPI VI when your code does not need to use the API anymore. If you forget this call, the native API risks to stay locked for the other applications until LabVIEW is completely closed.

Properties

In the opposite to classes of the other APIs, classes available in LabVIEW implement properties. By convention, these properties are optimized to generate a minimum of communication with the modules while automatically refreshing. By contrast, methods of type get_xxx and set_xxx systematically generate communications with the Yoctopuce modules and must be called sparingly.

Callback vs. Properties

There is no callback in the LabVIEW Yoctopuce API, the VIs automatically refresh: they are based on the properties of the .NET Proxy API objects.

12. Using the Yocto-3D-V2 with Java

Java is an object oriented language created by Sun Microsystem. Beside being free, its main strength is its portability. Unfortunately, this portability has an excruciating price. In Java, hardware abstraction is so high that it is almost impossible to work directly with the hardware. Therefore, the Yoctopuce API does not support native mode in regular Java. The Java API needs a Virtual Hub to communicate with Yoctopuce devices.

12.1. Getting ready

Go to the Yoctopuce web site and download the following items:

The library is available as source files as well as a jar file. Decompress the library files in a folder of your choice, connect your modules, run the VirtualHub software, and you are ready to start your first tests. You do not need to install any driver.

In order to keep them simple, all the examples provided in this documentation are console applications. Naturally, the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface.

12.2. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a Java code snippet to use the Tilt function.


[...]
// Get access to your device, through the VirtualHub running locally
YAPI.RegisterHub("127.0.0.1");
[...]

// Retrieve the object used to interact with the device
tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1");

// Hot-plug is easy: just check that the device is online
if (tilt.isOnline())
{    
    // Use tilt.get_currentValue()
    [...]
}

[...]

Let us look at these lines in more details.

YAPI.RegisterHub

The yAPI.RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for. The parameter is the address of the Virtual Hub able to see the devices. If the initialization does not succeed, an exception is thrown.

YTilt.FindTilt

The YTilt.FindTilt function allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can use logical names as well, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1")
tilt = YTilt.FindTilt("Y3DMK002-123456.MyFunction")
tilt = YTilt.FindTilt("MyModule.tilt1")
tilt = YTilt.FindTilt("MyModule.MyFunction")
tilt = YTilt.FindTilt("MyFunction")

YTilt.FindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by YTilt.FindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by YTilt.FindTilt provides the value of orientation measured by the tilt sensor. The value returned is a floating number.

YCompass.FindCompass, YGyro.FindGyro...

Functions YCompass.FindCompass, YMagnetometer.FindMagnetometer, YGyro.FindGyro and YAccelerometer.FindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YTilt.FindTilt.

A real example

Launch you Java environment and open the corresponding sample project provided in the directory Examples/Doc-GettingStarted-Yocto-3D-V2 of the Yoctopuce library.

In this example, you will recognize the functions explained above, but this time used with all the side materials needed to make it work nicely as a small demo.

import com.yoctopuce.YoctoAPI.*;

public class Demo {

    public static void main(String[] args)
    {
        try {
            // setup the API to use local VirtualHub
            YAPI.RegisterHub("127.0.0.1");
        } catch (YAPI_Exception ex) {
            System.out.println("Cannot contact VirtualHub on 127.0.0.1 (" + ex.getLocalizedMessage() + ")");
            System.out.println("Ensure that the VirtualHub application is running");
            System.exit(1);
        }

        YTilt anytilt,tilt1, tilt2;
        YCompass compass;
        YAccelerometer accelerometer;
        YGyro gyro;

        if (args.length == 0) {
            anytilt = YTilt.FirstTilt();            
            if (anytilt == null) {
                System.out.println("No module connected (check USB cable)");
                System.exit(1);
            }
        } else {
            anytilt = YTilt.FindTilt(args[0] + ".tilt1");
            if (!anytilt.isOnline()){
                System.out.println("Module not connected (check identification and USB cable)");
                System.exit(1);
            }
        }
        try {
            String serial = anytilt.get_module().get_serialNumber();
            tilt1 = YTilt.FindTilt(serial + ".tilt1");
            tilt2 = YTilt.FindTilt(serial + ".tilt2");
            compass = YCompass.FindCompass(serial + ".compass");
            accelerometer = YAccelerometer.FindAccelerometer(serial + ".accelerometer");
            gyro = YGyro.FindGyro(serial + ".gyro");
            int count = 0;
            while (true) {
                    if (!tilt1.isOnline()) {
                        System.out.println("device disconnected");
                        System.exit(0);
                    }

                    if (count % 10 == 0)
                        System.out.println("tilt1   tilt2   compass   acc   gyro");

                    System.out.println("" + tilt1.get_currentValue() + "\t" + tilt2.get_currentValue() +
                        "\t" + compass.get_currentValue() + "\t" + accelerometer.get_currentValue() + "\t" +
                        gyro.get_currentValue());
                    count++;
                    YAPI.Sleep(250);
            }
        } catch (YAPI_Exception ex) {
            System.out.println("Module not connected (check identification and USB cable)");
        }
        YAPI.FreeAPI();
    }
}
 

12.3. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.


import com.yoctopuce.YoctoAPI.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Demo {

    public static void main(String[] args)
    {
        try {
            // setup the API to use local VirtualHub
            YAPI.RegisterHub("127.0.0.1");
        } catch (YAPI_Exception ex) {
            System.out.println("Cannot contact VirtualHub on 127.0.0.1 (" + ex.getLocalizedMessage() + ")");
            System.out.println("Ensure that the VirtualHub application is running");
            System.exit(1);
        }
        System.out.println("usage: demo [serial or logical name] [ON/OFF]");

        YModule module;
        if (args.length == 0) {
            module = YModule.FirstModule();
            if (module == null) {
                System.out.println("No module connected (check USB cable)");
                System.exit(1);
            }
        } else {
            module = YModule.FindModule(args[0]);  // use serial or logical name
        }

        try {
            if (args.length > 1) {
                if (args[1].equalsIgnoreCase("ON")) {
                    module.setBeacon(YModule.BEACON_ON);
                } else {
                    module.setBeacon(YModule.BEACON_OFF);
                }
            }
            System.out.println("serial:       " + module.get_serialNumber());
            System.out.println("logical name: " + module.get_logicalName());
            System.out.println("luminosity:   " + module.get_luminosity());
            if (module.get_beacon() == YModule.BEACON_ON) {
                System.out.println("beacon:       ON");
            } else {
                System.out.println("beacon:       OFF");
            }
            System.out.println("upTime:       " + module.get_upTime() / 1000 + " sec");
            System.out.println("USB current:  " + module.get_usbCurrent() + " mA");
            System.out.println("logs:\n" + module.get_lastLogs());
        } catch (YAPI_Exception ex) {
            System.out.println(args[1] + " not connected (check identification and USB cable)");
        }
        YAPI.FreeAPI();
    }
}
 

Each property xxx of the module can be read thanks to a method of type YModule.get_xxxx(), and properties which are not read-only can be modified with the help of the YModule.set_xxx() method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding YModule.set_xxx() function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the YModule.saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the YModule.revertFromFlash() method. The short example below allows you to modify the logical name of a module.

import com.yoctopuce.YoctoAPI.*;

public class Demo {

    public static void main(String[] args)
    {
        try {
            // setup the API to use local VirtualHub
            YAPI.RegisterHub("127.0.0.1");
        } catch (YAPI_Exception ex) {
            System.out.println("Cannot contact VirtualHub on 127.0.0.1 (" + ex.getLocalizedMessage() + ")");
            System.out.println("Ensure that the VirtualHub application is running");
            System.exit(1);
        }

        if (args.length != 2) {
            System.out.println("usage: demo <serial or logical name> <new logical name>");
            System.exit(1);
        }

        YModule m;
        String newname;

        m = YModule.FindModule(args[0]); // use serial or logical name

        try {
            newname = args[1];
            if (!YAPI.CheckLogicalName(newname))
                {
                    System.out.println("Invalid name (" + newname + ")");
                    System.exit(1);
                }

            m.set_logicalName(newname);
            m.saveToFlash(); // do not forget this

            System.out.println("Module: serial= " + m.get_serialNumber());
            System.out.println(" / name= " + m.get_logicalName());
        } catch (YAPI_Exception ex) {
            System.out.println("Module " + args[0] + "not connected (check identification and USB cable)");
            System.out.println(ex.getMessage());
            System.exit(1);
        }

        YAPI.FreeAPI();
    }
}
 

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the YModule.saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the YModule.yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not null. Below a short example listing the connected modules.

import com.yoctopuce.YoctoAPI.*;

public class Demo {

    public static void main(String[] args)
    {
        try {
            // setup the API to use local VirtualHub
            YAPI.RegisterHub("127.0.0.1");
        } catch (YAPI_Exception ex) {
            System.out.println("Cannot contact VirtualHub on 127.0.0.1 (" + ex.getLocalizedMessage() + ")");
            System.out.println("Ensure that the VirtualHub application is running");
            System.exit(1);
        }

        System.out.println("Device list");
        YModule module = YModule.FirstModule();
        while (module != null) {
            try {
                System.out.println(module.get_serialNumber() + " (" + module.get_productName() + ")");
            } catch (YAPI_Exception ex) {
                break;
            }
            module = module.nextModule();
        }
        YAPI.FreeAPI();
    }
}
 

12.4. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software.

In the Java API, error handling is implemented with exceptions. Therefore you must catch and handle correctly all exceptions that might be thrown by the API if you do not want your software to crash as soon as you unplug a device.

13. Using the Yocto-3D-V2 with Android

To tell the truth, Android is not a programming language, it is an operating system developed by Google for mobile appliances such as smart phones and tablets. But it so happens that under Android everything is programmed with the same programming language: Java. Nevertheless, the programming paradigms and the possibilities to access the hardware are slightly different from classical Java, and this justifies a separate chapter on Android programming.

13.1. Native access and VirtualHub

In the opposite to the classical Java API, the Java for Android API can access USB modules natively. However, as there is no VirtualHub running under Android, it is not possible to remotely control Yoctopuce modules connected to a machine under Android. Naturally, the Java for Android API remains perfectly able to connect itself to a VirtualHub running on another OS.

13.2. Getting ready

Go to the Yoctopuce web site and download the Java for Android programming library35. The library is available as source files, and also as a jar file. Connect your modules, decompress the library files in the directory of your choice, and configure your Android programming environment so that it can find them.

To keep them simple, all the examples provided in this documentation are snippets of Android applications. You must integrate them in your own Android applications to make them work. However, your can find complete applications in the examples provided with the Java for Android library.

13.3. Compatibility

In an ideal world, you would only need to have a smart phone running under Android to be able to make Yoctopuce modules work. Unfortunately, it is not quite so in the real world. A machine running under Android must fulfil to a few requirements to be able to manage Yoctopuce USB modules natively.

Android 4.x

Android 4.0 (api 14) and following are officially supported. Theoretically, support of USB host functions since Android 3.1. But be aware that the Yoctopuce Java for Android API is regularly tested only from Android 4 onwards.

USB host support

Naturally, not only must your machine have a USB port, this port must also be able to run in host mode. In host mode, the machine literally takes control of the devices which are connected to it. The USB ports of a desktop computer, for example, work in host mode. The opposite of the host mode is the device mode. USB keys, for instance, work in device mode: they must be controlled by a host. Some USB ports are able to work in both modes, they are OTG (On The Go) ports. It so happens that many mobile devices can only work in device mode: they are designed to be connected to a charger or a desktop computer, and nothing else. It is therefore highly recommended to pay careful attention to the technical specifications of a product working under Android before hoping to make Yoctopuce modules work with it.

Unfortunately, having a correct version of Android and USB ports working in host mode is not enough to guaranty that Yoctopuce modules will work well under Android. Indeed, some manufacturers configure their Android image so that devices other than keyboard and mass storage are ignored, and this configuration is hard to detect. As things currently stand, the best way to know if a given Android machine works with Yoctopuce modules consists in trying.

Supported hardware

The library is tested and validated on the following machines:

If your Android machine is not able to control Yoctopuce modules natively, you still have the possibility to remotely control modules driven by a VirtualHub on another OS, or a YoctoHub 36.

13.4. Activating the USB port under Android

By default, Android does not allow an application to access the devices connected to the USB port. To enable your application to interact with a Yoctopuce module directly connected on your tablet on a USB port, a few additional steps are required. If you intend to interact only with modules connected on another machine through the network, you can ignore this section.

In your AndroidManifest.xml, you must declare using the "USB Host" functionality by adding the <uses-feature android:name="android.hardware.usb.host" /> tag in the manifest section.


<manifest ...>
    ...
    <uses-feature android:name="android.hardware.usb.host" />;
    ...
</manifest>

When first accessing a Yoctopuce module, Android opens a window to inform the user that the application is going to access the connected module. The user can deny or authorize access to the device. If the user authorizes the access, the application can access the connected device as long as it stays connected. To enable the Yoctopuce library to correctly manage these authorizations, your must provide a pointer on the application context by calling the EnableUSBHost method of the YAPI class before the first USB access. This function takes as arguments an object of the android.content.Context class (or of a subclass). As the Activity class is a subclass of Context, it is simpler to call YAPI.EnableUSBHost(this); in the method onCreate of your application. If the object passed as parameter is not of the correct type, a YAPI_Exception exception is generated.


...
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
                // Pass the application Context to the Yoctopuce Library
        YAPI.EnableUSBHost(this);
        } catch (YAPI_Exception e) {
                Log.e("Yocto",e.getLocalizedMessage());
        }
}
...

Autorun

It is possible to register your application as a default application for a USB module. In this case, as soon as a module is connected to the system, the application is automatically launched. You must add <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/> in the section <intent-filter> of the main activity. The section <activity> must have a pointer to an XML file containing the list of USB modules which can run the application.


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <uses-feature android:name="android.hardware.usb.host" />
    ...
    <application ... >
        <activity
            android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/device_filter" />
        </activity>
    </application>

</manifest>

The XML file containing the list of modules allowed to run the application must be saved in the res/xml directory. This file contains a list of USB vendorId and deviceID in decimal. The following example runs the application as soon as a Yocto-Relay or a YoctoPowerRelay is connected. You can find the vendorID and the deviceID of Yoctopuce modules in the characteristics section of the documentation.


<?xml version="1.0" encoding="utf-8"?>

<resources>
    <usb-device vendor-id="9440" product-id="12" />
    <usb-device vendor-id="9440" product-id="13" />
</resources>

13.5. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a Java code snippet to use the Tilt function.


[...]
// Enable detection of USB devices
YAPI.EnableUSBHost(this);
YAPI.RegisterHub("usb");
[...]
// Retrieve the object used to interact with the device
tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1");

// Hot-plug is easy: just check that the device is online
if (tilt.isOnline()) {
    // Use tilt.get_currentValue()
    [...]
}

[...]

Let us look at these lines in more details.

YAPI.EnableUSBHost

The YAPI.EnableUSBHost function initializes the API with the Context of the current application. This function takes as argument an object of the android.content.Context class (or of a subclass). If you intend to connect your application only to other machines through the network, this function is facultative.

YAPI.RegisterHub

The yAPI.RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for. The parameter is the address of the virtual hub able to see the devices. If the string "usb" is passed as parameter, the API works with modules locally connected to the machine. If the initialization does not succeed, an exception is thrown.

YTilt.FindTilt

The YTilt.FindTilt function allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can use logical names as well, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1")
tilt = YTilt.FindTilt("Y3DMK002-123456.MyFunction")
tilt = YTilt.FindTilt("MyModule.tilt1")
tilt = YTilt.FindTilt("MyModule.MyFunction")
tilt = YTilt.FindTilt("MyFunction")

YTilt.FindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by YTilt.FindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by YTilt.FindTilt provides the value of orientation measured by the tilt sensor. The value returned is a floating number.

YCompass.FindCompass, YGyro.FindGyro...

Functions YCompass.FindCompass, YMagnetometer.FindMagnetometer, YGyro.FindGyro and YAccelerometer.FindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YTilt.FindTilt.

A real example

Launch you Java environment and open the corresponding sample project provided in the directory Examples//Doc-Examples of the Yoctopuce library.

In this example, you can recognize the functions explained above, but this time used with all the side materials needed to make it work nicely as a small demo.

package com.yoctopuce.doc_examples;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.yoctopuce.YoctoAPI.YAPI;
import com.yoctopuce.YoctoAPI.YAPI_Exception;
import com.yoctopuce.YoctoAPI.YAccelerometer;
import com.yoctopuce.YoctoAPI.YCompass;
import com.yoctopuce.YoctoAPI.YGyro;
import com.yoctopuce.YoctoAPI.YModule;
import com.yoctopuce.YoctoAPI.YSensor;
import com.yoctopuce.YoctoAPI.YTilt;

public class GettingStarted_Yocto_3D extends Activity implements OnItemSelectedListener
{

    private ArrayAdapter<String> aa;
    private String serial = "";
    private Handler handler = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gettingstarted_yocto_3d);
        Spinner my_spin = (Spinner) findViewById(R.id.spinner1);
        my_spin.setOnItemSelectedListener(this);
        aa = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        my_spin.setAdapter(aa);
        handler = new Handler();
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        try {
            aa.clear();
            YAPI.EnableUSBHost(this);
            YAPI.RegisterHub("usb");
            YModule module = YModule.FirstModule();
            while (module != null) {
                if (module.get_productName().equals("Yocto-3D")) {
                    String serial = module.get_serialNumber();
                    aa.add(serial);
                }
                module = module.nextModule();
            }
        } catch (YAPI_Exception e) {
            e.printStackTrace();
        }
        aa.notifyDataSetChanged();
        handler.postDelayed(r, 500);
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        handler.removeCallbacks(r);
        YAPI.FreeAPI();
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
    {
        serial = parent.getItemAtPosition(pos).toString();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0)
    {
    }

    final Runnable r = new Runnable()
    {
        public void run()
        {
            if (serial != null) {
                YSensor tilt1 = YTilt.FindTilt(serial + ".tilt1");
                try {
                    TextView view = (TextView) findViewById(R.id.tilt1field);
                    view.setText(String.format("%.1f %s", tilt1.getCurrentValue(), tilt1.getUnit()));
                } catch (YAPI_Exception e) {
                    e.printStackTrace();
                }
                YTilt tilt2 = YTilt.FindTilt(serial + ".tilt2");
                try {
                    TextView view = (TextView) findViewById(R.id.tilt2field);
                    view.setText(String.format("%.1f %s", tilt2.getCurrentValue(), tilt2.getUnit()));
                } catch (YAPI_Exception e) {
                    e.printStackTrace();
                }
                YCompass compass = YCompass.FindCompass(serial + ".compass");
                try {
                    TextView view = (TextView) findViewById(R.id.compassfield);
                    view.setText(String.format("%.1f %s", compass.getCurrentValue(), compass.getUnit()));
                } catch (YAPI_Exception e) {
                    e.printStackTrace();
                }
                YAccelerometer accelerometer = YAccelerometer.FindAccelerometer(serial + ".accelerometer");
                try {
                    TextView view = (TextView) findViewById(R.id.accelfield);
                    view.setText(String.format("%.1f %s", accelerometer.getCurrentValue(), accelerometer.getUnit()));
                } catch (YAPI_Exception e) {
                    e.printStackTrace();
                }
                YGyro gyro = YGyro.FindGyro(serial + ".gyro");
                try {
                    TextView view = (TextView) findViewById(R.id.gyrofield);
                    view.setText(String.format("%.1f %s", gyro.getCurrentValue(), gyro.getUnit()));
                } catch (YAPI_Exception e) {
                    e.printStackTrace();
                }
            }
            handler.postDelayed(this, 200);
        }
    };

}
 

13.6. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.

package com.yoctopuce.doc_examples;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.yoctopuce.YoctoAPI.YAPI;
import com.yoctopuce.YoctoAPI.YAPI_Exception;
import com.yoctopuce.YoctoAPI.YModule;

public class ModuleControl extends Activity implements OnItemSelectedListener
{

    private ArrayAdapter<String> aa;
    private YModule module = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.modulecontrol);
        Spinner my_spin = (Spinner) findViewById(R.id.spinner1);
        my_spin.setOnItemSelectedListener(this);
        aa = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        my_spin.setAdapter(aa);
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        try {
            aa.clear();
            YAPI.EnableUSBHost(this);
            YAPI.RegisterHub("usb");
            YModule r = YModule.FirstModule();
            while (r != null) {
                String hwid = r.get_hardwareId();
                aa.add(hwid);
                r = r.nextModule();
            }
        } catch (YAPI_Exception e) {
            e.printStackTrace();
        }
        // refresh Spinner with detected relay
        aa.notifyDataSetChanged();
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        YAPI.FreeAPI();
    }

    private void DisplayModuleInfo()
    {
        TextView field;
        if (module == null)
            return;
        try {
            field = (TextView) findViewById(R.id.serialfield);
            field.setText(module.getSerialNumber());
            field = (TextView) findViewById(R.id.logicalnamefield);
            field.setText(module.getLogicalName());
            field = (TextView) findViewById(R.id.luminosityfield);
            field.setText(String.format("%d%%", module.getLuminosity()));
            field = (TextView) findViewById(R.id.uptimefield);
            field.setText(module.getUpTime() / 1000 + " sec");
            field = (TextView) findViewById(R.id.usbcurrentfield);
            field.setText(module.getUsbCurrent() + " mA");
            Switch sw = (Switch) findViewById(R.id.beaconswitch);
            sw.setChecked(module.getBeacon() == YModule.BEACON_ON);
            field = (TextView) findViewById(R.id.logs);
            field.setText(module.get_lastLogs());

        } catch (YAPI_Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
    {
        String hwid = parent.getItemAtPosition(pos).toString();
        module = YModule.FindModule(hwid);
        DisplayModuleInfo();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0)
    {
    }

    public void refreshInfo(View view)
    {
        DisplayModuleInfo();
    }

    public void toggleBeacon(View view)
    {
        if (module == null)
            return;
        boolean on = ((Switch) view).isChecked();

        try {
            if (on) {
                module.setBeacon(YModule.BEACON_ON);
            } else {
                module.setBeacon(YModule.BEACON_OFF);
            }
        } catch (YAPI_Exception e) {
            e.printStackTrace();
        }
    }
}
 

Each property xxx of the module can be read thanks to a method of type YModule.get_xxxx(), and properties which are not read-only can be modified with the help of the YModule.set_xxx() method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding YModule.set_xxx() function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the YModule.saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the YModule.revertFromFlash() method. The short example below allows you to modify the logical name of a module.

package com.yoctopuce.doc_examples;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.yoctopuce.YoctoAPI.YAPI;
import com.yoctopuce.YoctoAPI.YAPI_Exception;
import com.yoctopuce.YoctoAPI.YModule;

public class SaveSettings extends Activity implements OnItemSelectedListener
{

    private ArrayAdapter<String> aa;
    private YModule module = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.savesettings);
        Spinner my_spin = (Spinner) findViewById(R.id.spinner1);
        my_spin.setOnItemSelectedListener(this);
        aa = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        my_spin.setAdapter(aa);
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        try {
            aa.clear();
            YAPI.EnableUSBHost(this);
            YAPI.RegisterHub("usb");
            YModule r = YModule.FirstModule();
            while (r != null) {
                String hwid = r.get_hardwareId();
                aa.add(hwid);
                r = r.nextModule();
            }
        } catch (YAPI_Exception e) {
            e.printStackTrace();
        }
        // refresh Spinner with detected relay
        aa.notifyDataSetChanged();
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        YAPI.FreeAPI();
    }

    private void DisplayModuleInfo()
    {
        TextView field;
        if (module == null)
            return;
        try {
            YAPI.UpdateDeviceList();// fixme
            field = (TextView) findViewById(R.id.logicalnamefield);
            field.setText(module.getLogicalName());
        } catch (YAPI_Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
    {
        String hwid = parent.getItemAtPosition(pos).toString();
        module = YModule.FindModule(hwid);
        DisplayModuleInfo();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0)
    {
    }

    public void saveName(View view)
    {
        if (module == null)
            return;

        EditText edit = (EditText) findViewById(R.id.newname);
        String newname = edit.getText().toString();
        try {
            if (!YAPI.CheckLogicalName(newname)) {
                Toast.makeText(getApplicationContext(), "Invalid name (" + newname + ")", Toast.LENGTH_LONG).show();
                return;
            }
            module.set_logicalName(newname);
            module.saveToFlash(); // do not forget this
            edit.setText("");
        } catch (YAPI_Exception ex) {
            ex.printStackTrace();
        }
        DisplayModuleInfo();
    }

}
 

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the YModule.saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the YModule.yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not null. Below a short example listing the connected modules.

package com.yoctopuce.doc_examples;

import android.app.Activity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yoctopuce.YoctoAPI.YAPI;
import com.yoctopuce.YoctoAPI.YAPI_Exception;
import com.yoctopuce.YoctoAPI.YModule;

public class Inventory extends Activity
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inventory);
    }

    public void refreshInventory(View view)
    {
        LinearLayout layout = (LinearLayout) findViewById(R.id.inventoryList);
        layout.removeAllViews();

        try {
            YAPI.UpdateDeviceList();
            YModule module = YModule.FirstModule();
            while (module != null) {
                String line = module.get_serialNumber() + " (" + module.get_productName() + ")";
                TextView tx = new TextView(this);
                tx.setText(line);
                tx.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
                layout.addView(tx);
                module = module.nextModule();
            }
        } catch (YAPI_Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        try {
            YAPI.EnableUSBHost(this);
            YAPI.RegisterHub("usb");
        } catch (YAPI_Exception e) {
            e.printStackTrace();
        }
        refreshInventory(null);
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        YAPI.FreeAPI();
    }

}
 

13.7. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software.

In the Java API for Android, error handling is implemented with exceptions. Therefore you must catch and handle correctly all exceptions that might be thrown by the API if you do not want your software to crash soon as you unplug a device.

14. Using Yocto-3D-V2 with TypeScript

TypeScript is an enhanced version of the JavaScript programming language. It is a syntaxic superset with strong typing, therefore increasing the code reliability, but transpiled - aka compiled - into JavaScript for execution in any standard Web browser or Node.js environment.

This Yoctopuce library therefore makes it possible to implement JavaScript applications using strong typing. Similarly to our EcmaScript library, it uses the new asynchronous features introduced in ECMAScript 2017, which are now available in all modern JavaScript environments. Note however that at the time of writting, Web browsers and Node.JS cannot use TypeScript code directly, so you must first compile your TypeScript into JavaScript before running it.

The library works both in a Web browser and in Node.js. In order to allow for a static resolution of dependencies, and to avoid ambiguities that can arise when using hybrid environments such as Electron, the choice of the runtime environment must be done explicitly upon import of the library, by referencing in the project either yocto_api_nodejs.js or yocto_api_html.js.

The library can be integrated in your projects in multiple ways, depending on what best fits your requirements:

14.1. Using the Yoctopuce library for TypeScript

1. Start by installing TypeScript on your machine if this is not yet done. In order to do so:

2. Go to the Yoctopuce web site and download the following items:

3. Extract the library files in a folder of your choice, and open a command window in the directory where you have installed it. In order to install the few dependencies which are necessary to start the examples, run this command:


npm install

When the command has run without error, you are ready to explore the examples. They are available in two different trees, depending on the environment that you need to use: example_html for running the Yoctopuce library within a Web browser, or example_nodejs if you plan to use the library in a Node.js environment.

The method to use for launching the examples depends on the environment. You will find more about it below.

14.2. Refresher on asynchronous I/O in JavaScript

JavaScript is single-threaded by design. In order to handle time-consuming I/O operations, JavaScript relies on asynchronous operations: the I/O call is only triggered but then the code execution flow is suspended. The JavaScript engine is therefore free to handle other pending tasks, such as user interface. Whenever the pending I/O call is completed, the system invokes a callback function with the result of the I/O call to resume execution of the original execution flow.

When used with plain callback functions, as pervasive in Node.js libraries, asynchronous I/O tend to produce code with poor readability, as the execution flow is broken into many disconnected callback functions. Fortunately, the ECMAScript 2015 standard came in with Promise objects and a new async / await syntax to abstract calls to asynchronous calls:

To make a long story short, async and await make it possible to write TypeScript code with all the benefits of asynchronous I/O, but without breaking the code flow. It is almost like multi-threaded execution, except that control switch between pending tasks only happens at places where the await keyword appears.

This TypeScript library uses the Promise objects and async methods, to allow you to use the await syntax. To keep it easy to remember, all public methods of the TypeScript library are async, i.e. return a Promise object, except:

In most cases, TypeScript strong typing will remind you to use await when calling an asynchronous method.

14.3. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a TypeScript code snipplet to use the Tilt function.


// For Node.js, the library is referenced through the NPM package
// For HTML, we would use instead a relative path (depending on the build environment)
import { YAPI, YErrorMsg, YModule } from 'yoctolib-cjs/yocto_api_nodejs.js';
import { YTilt } from 'yoctolib-cjs/yocto_tilt.js';

[...]
// Get access to your device, through the VirtualHub running locally
await YAPI.RegisterHub('127.0.0.1');
[...]

// Retrieve the object used to interact with the device
var tilt: YTilt = YTilt.FindTilt("Y3DMK002-123456.tilt1");

// Check that the module is online to handle hot-plug
if(await tilt.isOnline())
{
    // Use tilt.get_currentValue()
    [...]
}

Let us look at these lines in more details.

yocto_api and yocto_tilt import

These two imports provide access to functions allowing you to manage Yoctopuce modules. yocto_api is always needed, yocto_tilt is necessary to manage modules containing a tilt sensor, such as Yocto-3D-V2. Other imports can be useful in other cases, such as YModule which can let you enumerate any type of Yoctopuce device.

In order to properly bind yocto_api to the proper network libraries (provided either by Node.js or by the web browser for an HTML application), you must import at least once in your project one of the two variants yocto_api_nodejs.js or yocto_api_html.js.

Note that this example imports the Yoctopuce library as a CommonJS module, which is the most frequently used with Node.JS, but if your project is designed around EcmaScript native modules, you can also replace in the import directive the prefix yoctolib-cjs by yoctolib-esm.

YAPI.RegisterHub

The RegisterHub method allows you to indicate on which machine the Yoctopuce modules are located, more precisely on which machine the VirtualHub software is running. In our case, the 127.0.0.1:4444 address indicates the local machine, port 4444 (the standard port used by Yoctopuce). You can very well modify this address, and enter the address of another machine on which the VirtualHub software is running, or of a YoctoHub. If the host cannot be reached, this function will trigger an exception.

As explained above, using RegisterHub("usb") is not supported in TypeScript, because the JavaScript engine has no direct access to USB devices. It needs to go through the VirtualHub via a localhost connection.

YTilt.FindTilt

The FindTilt method allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can also use logical names, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1")
tilt = YTilt.FindTilt("Y3DMK002-123456.MaFonction")
tilt = YTilt.FindTilt("MonModule.tilt1")
tilt = YTilt.FindTilt("MonModule.MaFonction")
tilt = YTilt.FindTilt("MaFonction")

YTilt.FindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by FindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by YTilt.FindTilt provides the value of orientation measured by the tilt sensor. The value returned is a floating number.

YCompass.FindCompass, YGyro.FindGyro...

Functions YCompass.FindCompass, YMagnetometer.FindMagnetometer, YGyro.FindGyro and YAccelerometer.FindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YTilt.FindTilt.

A real example, for Node.js

Open a command window (a terminal, a shell...) and go into the directory example_nodejs/Doc-GettingStarted-Yocto-3D-V2 within Yoctopuce library for TypeScript. In there, you will find a file named demo.ts with the sample code below, which uses the functions explained above, but this time used with all side materials needed to make it work nicely as a small demo.

If your Yocto-3D-V2 is not connected on the host running the browser, replace in the example the address 127.0.0.1 by the IP address of the host on which the Yocto-3D-V2 is connected and where you run the VirtualHub.

import { YAPI, YErrorMsg, YModule } from 'yoctolib-cjs/yocto_api_nodejs.js';
import { YTilt } from 'yoctolib-cjs/yocto_tilt.js'
import { YCompass } from 'yoctolib-cjs/yocto_compass.js'
import { YGyro } from 'yoctolib-cjs/yocto_gyro.js'
import { YAccelerometer } from 'yoctolib-cjs/yocto_accelerometer.js'

let tilt1: YTilt;
let tilt2: YTilt;
let compass: YCompass;
let gyro: YGyro;
let accelerometer: YAccelerometer;
let count: number;

async function startDemo(): Promise<void>
{
    await YAPI.LogUnhandledPromiseRejections();

    // Setup the API to use the VirtualHub on local machine
    let errmsg: YErrorMsg = new YErrorMsg();
    if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS) {
        console.log('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);
        return;
    }

    // Select specified device, or use first available one
    let serial: string = process.argv[process.argv.length-1];
    if(serial[8] != '-') {
        // by default use any connected module suitable for the demo
        let anysensor = YTilt.FirstTilt();
        if(anysensor) {
            let module = await anysensor.get_module();
            serial = await module.get_serialNumber();
        } else {
            console.log('No matching sensor connected, check cable !');
            await YAPI.FreeAPI();
            return;
        }
    }
    console.log('Using device '+serial);
    tilt1   = YTilt.FindTilt(serial + ".tilt1");
    tilt2   = YTilt.FindTilt(serial + ".tilt2");
    compass = YCompass.FindCompass(serial + ".compass");
    gyro    = YGyro.FindGyro(serial + ".gyro");
    accelerometer = YAccelerometer.FindAccelerometer(serial+".accelerometer");
    count = 0;

    refresh();
}

async function refresh(): Promise<void>
{
    if (await tilt1.isOnline()) {
        if (count % 10 == 0) {
            console.log("tilt1\ttilt2\tcompass\tacc\tgyro");
        }
        console.log(
            await tilt1.get_currentValue()+"\t"+
            await tilt2.get_currentValue()+"\t"+
            await compass.get_currentValue()+"\t"+
            await accelerometer.get_currentValue()+"\t"+
            await gyro.get_currentValue()
        );
        count++;
    } else {
        console.log('Module not connected');
        count = 0;
    }
    setTimeout(refresh, 500);
}

startDemo();
 

As explained at the beginning of this chapter, you need to have installed the TypeScript compiler on your machine to test these examples, and to install the typescript library dependencies. If you have done that, you can now type the following two commands in the example directory, to finalize the resolution of the example-specific dependencies:


npm install

You ar now ready to start the sample code with Node.js. The easiest way to do it is to use the following command, replacing the [...] by the arguments that you want to pass to the demo code:


npm run demo [...]

This command, defined in package.json, will first start the TypeScript compiler using the simple tsc command, then run the transpiled code in Node.js.

The compilation uses the parameters specified in the file tsconfig.json, and produces

Note that the package.json file in our examples uses a relative reference to the local copy of the library, to avoid duplicating the library in each example. But of course, for your application, you can refer to the package directly in npm repository, by adding it to your project using the command:


npm install yoctolib-cjs

Same example, but this time running in a browser

If you want to see how to use the library within a browser rather than with Node.js, switch to the directory example_html/Doc-GettingStarted-Yocto-3D-V2. You will find there an HTML file named app.html, and a TypeScript file app.ts similar to the code above, but with a few changes since it has to interact through an HTML page rather than through the JavaScript console.

No installation is needed to run this example, as the TypeScript library is referenced using a relative path. However, in order to allow the browser to run the code, the HTML page must be served by a Web server. We therefore provide a simple test server for this purpose, that you can start with the command:


npm run app-server

This command will compile the TypeScript sample code, make it available via an HTTP server on port 3000 and open a Web browser on this example. If you change the example source code, the TypeScript compiler will automatically be triggered to update the transpiled code and a simple page reload on the browser will make it possible to test the change.

As for the Node.js example, the compilation process will create a source map file which makes it possible to debug the example code in TypeScript source form within the browser debugger. Note that as of the writing of this document, this works on Chromium-based browsers but not yet in Firefox.

14.4. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.

import { YAPI, YErrorMsg, YModule } from 'yoctolib-cjs/yocto_api_nodejs.js';

async function startDemo(args: string[]): Promise<void>
{
    await YAPI.LogUnhandledPromiseRejections();

    // Setup the API to use the VirtualHub on local machine
    let errmsg: YErrorMsg = new YErrorMsg();
    if (await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS) {
        console.log('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);
        return;
    }

    // Select the device to use
    let module: YModule = YModule.FindModule(args[0]);
    if(await module.isOnline()) {
        if(args.length > 1) {
            if(args[1] == 'ON') {
                await module.set_beacon(YModule.BEACON_ON);
            } else {
                await module.set_beacon(YModule.BEACON_OFF);
            }
        }
        console.log('serial:       '+await module.get_serialNumber());
        console.log('logical name: '+await module.get_logicalName());
        console.log('luminosity:   '+await module.get_luminosity()+'%');
        console.log('beacon:       '+
            (await module.get_beacon() == YModule.BEACON_ON ? 'ON' : 'OFF'));
        console.log('upTime:       '+
            ((await module.get_upTime()/1000)>>0) +' sec');
        console.log('USB current:  '+await module.get_usbCurrent()+' mA');
        console.log('logs:');
        console.log(await module.get_lastLogs());
    } else {
        console.log("Module not connected (check identification and USB cable)\n");
    }
    await YAPI.FreeAPI();
}

if(process.argv.length < 3) {
    console.log("usage: npm run demo <serial or logicalname> [ ON | OFF ]");
} else {
    startDemo(process.argv.slice(2));
}
 

Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used methods, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding set_xxx() method. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the revertFromFlash() method. The short example below allows you to modify the logical name of a module.

import { YAPI, YErrorMsg, YModule } from 'yoctolib-cjs/yocto_api_nodejs.js';

async function startDemo(args: string[]): Promise<void>
{
    await YAPI.LogUnhandledPromiseRejections();

    // Setup the API to use the VirtualHub on local machine
    let errmsg: YErrorMsg = new YErrorMsg();
    if (await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS) {
        console.log('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);
        return;
    }

    // Select the device to use
    let module: YModule = YModule.FindModule(args[0]);
    if(await module.isOnline()) {
        if(args.length > 1) {
            let newname: string = args[1];
            if (!await YAPI.CheckLogicalName(newname)) {
                console.log("Invalid name (" + newname + ")");
                process.exit(1);
            }
            await module.set_logicalName(newname);
            await module.saveToFlash();
        }
        console.log('Current name: '+await module.get_logicalName());
    } else {
        console.log("Module not connected (check identification and USB cable)\n");
    }
    await YAPI.FreeAPI();
}

if(process.argv.length < 3) {
    console.log("usage: npm run demo <serial> [newLogicalName]");
} else {
    startDemo(process.argv.slice(2));
}
 

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the saveToFlash() method only 100000 times in the life of the module. Make sure you do not call this method within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the YModule.FirstModule() method which returns the first module found. Then, you only need to call the nextModule() method of this object to find the following modules, and this as long as the returned value is not null. Below a short example listing the connected modules.

import { YAPI, YErrorMsg, YModule } from 'yoctolib-cjs/yocto_api_nodejs.js';

async function startDemo(): Promise<void>
{
    await YAPI.LogUnhandledPromiseRejections();

    // Setup the API to use the VirtualHub on local machine
    let errmsg = new YErrorMsg();
    if (await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS) {
        console.log('Cannot contact VirtualHub on 127.0.0.1');
        return;
    }
    refresh();
}

async function refresh(): Promise<void>
{
    try {
        let errmsg: YErrorMsg = new YErrorMsg();
        await YAPI.UpdateDeviceList(errmsg);

        let module = YModule.FirstModule();
        while(module) {
            let line: string = await module.get_serialNumber();
            line += '(' + (await module.get_productName()) + ')';
            console.log(line);
            module = module.nextModule();
        }
        setTimeout(refresh, 500);
    } catch(e) {
        console.log(e);
    }
}

startDemo();
 

14.5. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software. The only way to prevent this is to implement one of the two error handling techniques described below.

The method recommended by most programming languages for unpredictable error handling is the use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while you try to access a module, the library throws an exception. In this case, there are three possibilities:

As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for error handling, allowing you to create a robust program without needing to catch exceptions at every line of code. You simply need to call the YAPI.DisableExceptions() function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values, which can be tested by the caller when necessary. For each function, the name of each return value in case of error is systematically documented in the library reference. The name always follows the same logic: a get_state() method returns a ClassName.STATE_INVALID value, a get_currentValue method returns a ClassName.CURRENTVALUE_INVALID value, and so on. In any case, the returned value is of the expected type and is not a null pointer which would risk crashing your program. At worst, if you display the value without testing it, it will be outside the expected bounds for the returned value. In the case of functions which do not normally return information, the return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.

When you work without exceptions, you can obtain an error code and an error message explaining the source of the error. You can request them from the object which returned the error, calling the errType() and errMessage() methods. Their returned values contain the same information as in the exceptions when they are active.

15. Using Yocto-3D-V2 with JavaScript / EcmaScript

EcmaScript is the official name of the standardized version of the web-oriented programming language commonly referred to as JavaScript. This Yoctopuce library take advantages of advanced features introduced in EcmaScript 2017. It has therefore been named Library for JavaScript / EcmaScript 2017 to differentiate it from the previous Library for JavaScript, now deprecated in favor of this new version.

This library provides access to Yoctopuce devices for modern JavaScript engines. It can be used within a browser as well as with Node.js. The library will automatically detect upon initialization whether the runtime environment is a browser or a Node.js virtual machine, and use the most appropriate system libraries accordingly.

Asynchronous communication with the devices is handled across the whole library using Promise objects, leveraging the new EcmaScript 2017 async / await non-blocking syntax for asynchronous I/O (see below). This syntax is now available out-of-the-box in most Javascript engines. No transpilation is needed: no Babel, no jspm, just plain Javascript. Here is your favorite engines minimum version needed to run this code. All of them are officially released at the time we write this document.

If you need backward-compatibility with older releases, you can always run Babel to transpile your code and the library to older standards, as described a few paragraphs below.

We don't suggest using jspm anymore now that async / await are part of the standard.

15.1. Blocking I/O versus Asynchronous I/O in JavaScript

JavaScript is single-threaded by design. That means, if a program is actively waiting for the result of a network-based operation such as reading from a sensor, the whole program is blocked. In browser environments, this can even completely freeze the user interface. For this reason, the use of blocking I/O in JavaScript is strongly discouraged nowadays, and blocking network APIs are getting deprecated everywhere.

Instead of using parallel threads, JavaScript relies on asynchronous I/O to handle operations with a possible long timeout: whenever a long I/O call needs to be performed, it is only triggered and but then the code execution flow is terminated. The JavaScript engine is therefore free to handle other pending tasks, such as UI. Whenever the pending I/O call is completed, the system invokes a callback function with the result of the I/O call to resume execution of the original execution flow.

When used with plain callback functions, as pervasive in Node.js libraries, asynchronous I/O tend to produce code with poor readability, as the execution flow is broken into many disconnected callback functions. Fortunately, new methods have emerged recently to improve that situation. In particular, the use of Promise objects to abstract and work with asynchronous tasks helps a lot. Any function that makes a long I/O operation can return a Promise, which can be used by the caller to chain subsequent operations in the same flow. Promises are part of EcmaScript 2015 standard.

Promise objects are good, but what makes them even better is the new async / await keywords to handle asynchronous I/O:

Long story made short, async and await make it possible to write EcmaScript code with all benefits of asynchronous I/O, but without breaking the code flow. It is almost like multi-threaded execution, except that control switch between pending tasks only happens at places where the await keyword appears.

We have therefore chosen to write our new EcmaScript library using Promises and async functions, so that you can use the friendly await syntax. To keep it easy to remember, all public methods of the EcmaScript library are async, i.e. return a Promise object, except:

15.2. Using Yoctopuce library for JavaScript / EcmaScript 2017

JavaScript is one of those languages which do not generally allow you to directly access the hardware layers of your computer. Therefore the library can only be used to access network-enabled devices (connected through a YoctoHub), or USB devices accessible through Yoctopuce TCP/IP to USB gateway, named VirtualHub.

Go to the Yoctopuce web site and download the following items:

Extract the library files in a folder of your choice, you will find many of examples in it. Connect your modules and start the VirtualHub software. You do not need to install any driver.

Using the official Yoctopuce library for node.js

Start by installing the latest Node.js version (v7.6 or later) on your system. It is very easy. You can download it from the official web site: http://nodejs.org. Make sure to install it fully, including npm, and add it to the system path.

To give it a try, go into one of the example directory (for instance example_nodejs/Doc-Inventory). You will see that it include an application description file (package.json) and a source file (demo.js). To download and setup the libraries needed by this example, just run:


npm install

Once done, you can start the example file using:


node demo.js

Using a local copy of the Yoctopuce library with node.js

If for some reason you need to make changes to the Yoctopuce library, you can easily configure your project to use the local copy in the lib/ subdirectory rather than the official npm package. In order to do so, simply type the following command in your project directory:


npm link ../../lib

Using the Yoctopuce library within a browser (HTML)

For HTML examples, it is even simpler: there is nothing to install. Each example is a single HTML file that you can open in a browser to try it. In this context, loading the Yoctopuce library is no different from any standard HTML script include tag.

Using the Yoctoluce library on older JavaScript engines

If you need to run this library on older JavaScript engines, you can use Babel41 to transpile your code and the library into older JavaScript standards. To install Babel with typical settings, simply use:


npm instal -g babel-cli
npm instal babel-preset-env

You would typically ask Babel to put the transpiled files in another directory, named compat for instance. Your files and all files of the Yoctopuce library should be transpiled, as follow:


babel --presets env demo.js --out-dir compat/
babel --presets env ../../lib --out-dir compat/

Although this approach is based on node.js toolchain, it actually works as well for transpiling JavaScript files for use in a browser. The only thing that you cannot do so easily is transpiling JavaScript code embedded directly in an HTML page. You have to use an external script file for using EcmaScript 2017 syntax with Babel.

Babel has many smart features, such as a watch mode that will automatically refresh transpiled files whenever the source file is changed, but this is beyond the scope of this note. You will find more in Babel documentation.

Backward-compatibility with the old JavaScript library

This new library is not fully backward-compatible with the old JavaScript library, because there is no way to transparently map the old blocking API to the new asynchronous API. The method names however are the same, and old synchronous code can easily be made asynchronous just by adding the proper await keywords before the method calls. For instance, simply replace:


beaconState = module.get_beacon();

by


beaconState = await module.get_beacon();

Apart from a few exceptions, most XXX_async redundant methods have been removed as well, as they would have introduced confusion on the proper way of handling asynchronous behaviors. It is however very simple to get an async method to invoke a callback upon completion, using the returned Promise object. For instance, you can replace:


module.get_beacon_async(callback, myContext);

by


module.get_beacon().then(function(res) { callback(myContext, module, res); });

In some cases, it might be desirable to get a sensor value using a method identical to the old synchronous methods (without using Promises), even if it returns a slightly outdated cached value since I/O is not possible. For this purpose, the EcmaScript library introduce new classes called synchronous proxies. A synchronous proxy is an object that mirrors the most recent state of the connected class, but can be read using regular synchronous function calls. For instance, instead of writing:


async function logInfo(module)
{
    console.log('Name: '+await module.get_logicalName());
    console.log('Beacon: '+await module.get_beacon());
}

...
logInfo(myModule);
...

you can use:


function logInfoProxy(moduleSyncProxy)
{
    console.log('Name: '+moduleProxy.get_logicalName());
    console.log('Beacon: '+moduleProxy.get_beacon());
}

logInfoSync(await myModule.get_syncProxy());

You can also rewrite this last asynchronous call as:


myModule.get_syncProxy().then(logInfoProxy);

15.3. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a JavaScript code snippet to use the Tilt function.


// For Node.js, we use function require()
// For HTML, we would use &lt;script src="..."&gt;
require('yoctolib-es2017/yocto_api.js');
require('yoctolib-es2017/yocto_tilt.js');

[...]
// Get access to your device, through the VirtualHub running locally
await YAPI.RegisterHub('127.0.0.1');
[...]

// Retrieve the object used to interact with the device
var tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1");

// Check that the module is online to handle hot-plug
if(await tilt.isOnline())
{
    // Use tilt.get_currentValue()
    [...]
}

Let us look at these lines in more details.

yocto_api and yocto_tilt import

These two import provide access to functions allowing you to manage Yoctopuce modules. yocto_api is always needed, yocto_tilt is necessary to manage modules containing a tilt sensor, such as Yocto-3D-V2. Other imports can be useful in other cases, such as YModule which can let you enumerate any type of Yoctopuce device.

YAPI.RegisterHub

The RegisterHub method allows you to indicate on which machine the Yoctopuce modules are located, more precisely on which machine the VirtualHub software is running. In our case, the 127.0.0.1:4444 address indicates the local machine, port 4444 (the standard port used by Yoctopuce). You can very well modify this address, and enter the address of another machine on which the VirtualHub software is running, or of a YoctoHub. If the host cannot be reached, this function will trigger an exception.

YTilt.FindTilt

The FindTilt method allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can also use logical names, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1")
tilt = YTilt.FindTilt("Y3DMK002-123456.MaFonction")
tilt = YTilt.FindTilt("MonModule.tilt1")
tilt = YTilt.FindTilt("MonModule.MaFonction")
tilt = YTilt.FindTilt("MaFonction")

YTilt.FindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by FindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by YTilt.FindTilt provides the value of orientation measured by the tilt sensor. The value returned is a floating number.

YCompass.FindCompass, YGyro.FindGyro...

Functions YCompass.FindCompass, YMagnetometer.FindMagnetometer, YGyro.FindGyro and YAccelerometer.FindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YTilt.FindTilt.

A real example, for Node.js

Open a command window (a terminal, a shell...) and go into the directory example_nodejs/Doc-GettingStarted-Yocto-3D-V2 within Yoctopuce library for JavaScript / EcmaScript 2017. In there, you will find a file named demo.js with the sample code below, which uses the functions explained above, but this time used with all side materials needed to make it work nicely as a small demo.

If your Yocto-3D-V2 is not connected on the host running the browser, replace in the example the address 127.0.0.1 with the IP address of the host on which the Yocto-3D-V2 is connected and where you run the VirtualHub.

"use strict";

require('yoctolib-es2017/yocto_api.js');
require('yoctolib-es2017/yocto_tilt.js');
require('yoctolib-es2017/yocto_compass.js');
require('yoctolib-es2017/yocto_gyro.js');
require('yoctolib-es2017/yocto_accelerometer.js');

let tilt1, tilt2, compass, gyro, accelerometer, count;

async function startDemo()
{
    await YAPI.LogUnhandledPromiseRejections();
    await YAPI.DisableExceptions();

    // Setup the API to use the VirtualHub on local machine
    let errmsg = new YErrorMsg();
    if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS) {
        console.log('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);
        return;
    }

    // Select specified device, or use first available one
    let serial = process.argv[process.argv.length-1];
    if(serial[8] != '-') {
        // by default use any connected module suitable for the demo
        let anysensor = YTilt.FirstTilt();
        if(anysensor) {
            let module = await anysensor.module();
            serial = await module.get_serialNumber();
        } else {
            console.log('No matching sensor connected, check cable !');
            return;
        }
    }
    console.log('Using device '+serial);
    tilt1   = YTilt.FindTilt(serial + ".tilt1");
    tilt2   = YTilt.FindTilt(serial + ".tilt2");
    compass = YCompass.FindCompass(serial + ".compass");
    gyro    = YGyro.FindGyro(serial + ".gyro");
    accelerometer = YAccelerometer.FindAccelerometer(serial+".accelerometer");
    count = 0;

    refresh();
}

async function refresh()
{
    if (await tilt1.isOnline()) {
        if (count % 10 == 0) {
            console.log("tilt1\ttilt2\tcompass\tacc\tgyro");
        }
        console.log(
            await tilt1.get_currentValue()+"\t"+
            await tilt2.get_currentValue()+"\t"+
            await compass.get_currentValue()+"\t"+
            await accelerometer.get_currentValue()+"\t"+
            await gyro.get_currentValue()
        );
        count++;
    } else {
        console.log('Module not connected');
        count = 0;
    }
    setTimeout(refresh, 500);
}

startDemo();
 

As explained at the beginning of this chapter, you need to have Node.js v7.6 or later installed to try this example. When done, you can type the following two commands to automatically download and install the dependencies for building this example:


npm install
You can the start the sample code within Node.js using the following command, replacing the [...] by the arguments that you want to pass to the demo code:

node demo.js [...]

Same example, but this time running in a browser

If you want to see how to use the library within a browser rather than with Node.js, switch to the directory example_html/Doc-GettingStarted-Yocto-3D-V2. You will find there a single HTML file, with a JavaScript section similar to the code above, but with a few changes since it has to interact through an HTML page rather than through the JavaScript console.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Hello World</title>
  <script src="../../lib/yocto_api.js"></script>
  <script src="../../lib/yocto_tilt.js"></script>
  <script src="../../lib/yocto_compass.js"></script>
  <script src="../../lib/yocto_accelerometer.js"></script>
  <script src="../../lib/yocto_gyro.js"></script>
  <script>
    async function startDemo()
    {
      await YAPI.LogUnhandledPromiseRejections();
      await YAPI.DisableExceptions();

      // Setup the API to use the VirtualHub on local machine
      let errmsg = new YErrorMsg();
      if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS) {
      alert('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);
    }
      refresh();
    }

    async function refresh()
    {
      let serial = document.getElementById('serial').value;
      if(serial == '') {
        // by default use any connected module suitable for the demo
        let anysensor = YTilt.FirstTilt();
        if(anysensor) {
          let module = await anysensor.module();
          serial = await module.get_serialNumber();
          document.getElementById('serial').value = serial;
        }
      }
      let tilt1         = YTilt.FindTilt(serial+".tilt1");
      let tilt2         = YTilt.FindTilt(serial+".tilt2");
      let compass       = YCompass.FindCompass(serial+".compass");
      let gyro          = YGyro.FindGyro(serial+".gyro");
      let accelerometer = YAccelerometer.FindAccelerometer(serial+".accelerometer");
      if (await tilt1.isOnline()) {
      document.getElementById('msg').value = '';
      document.getElementById("tilt1-val").value    = await tilt1.get_currentValue();
      document.getElementById("tilt2-val").value    = await tilt2.get_currentValue();
      document.getElementById("compass-val").value  = await compass.get_currentValue();
      document.getElementById("gyro-val").value     = await gyro.get_currentValue();
      document.getElementById("accelerometer-val").value = await accelerometer.get_currentValue();
    } else {
      document.getElementById('msg').value = 'Module not connected';
    }
      setTimeout(refresh, 500);
    }

    startDemo();
  </script>
</head>
<body>
Module to use: <input id='serial'>
<input id='msg' style='color:red;border:none;' readonly><br>
tilt1:   <input id='tilt1-val' readonly> &deg;<br>
tilt2:   <input id='tilt2-val' readonly></span> &deg;<br>
compass: <input id='compass-val' readonly></span> &deg;<br>
gyro:    <input id='gyro-val' readonly></span> &deg;/s<br>
accelerometer:    <input id='accelerometer-val' readonly></span> g<br>
</body>
</html>
 

No installation is needed to run this example, all you have to do is open the HTML file using a web browser,

15.4. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.

"use strict";

require('yoctolib-es2017/yocto_api.js');

async function startDemo(args)
{
    await YAPI.LogUnhandledPromiseRejections();

    // Setup the API to use the VirtualHub on local machine
    let errmsg = new YErrorMsg();
    if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS) {
        console.log('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);
        return;
    }

    // Select the relay to use
    let module = YModule.FindModule(args[0]);
    if(await module.isOnline()) {
        if(args.length > 1) {
            if(args[1] == 'ON') {
                await module.set_beacon(YModule.BEACON_ON);
            } else {
                await module.set_beacon(YModule.BEACON_OFF);
            }
        }
        console.log('serial:       '+await module.get_serialNumber());
        console.log('logical name: '+await module.get_logicalName());
        console.log('luminosity:   '+await module.get_luminosity()+'%');
        console.log('beacon:       '+(await module.get_beacon()==YModule.BEACON_ON?'ON':'OFF'));
        console.log('upTime:       '+parseInt(await module.get_upTime()/1000)+' sec');
        console.log('USB current:  '+await module.get_usbCurrent()+' mA');
        console.log('logs:');
        console.log(await module.get_lastLogs());
    } else {
        console.log("Module not connected (check identification and USB cable)\n");
    }
    await YAPI.FreeAPI();
}

if(process.argv.length < 2) {
    console.log("usage: node demo.js <serial or logicalname> [ ON | OFF ]");
} else {
    startDemo(process.argv.slice(2));
}
 

Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding set_xxx() function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the revertFromFlash() method. The short example below allows you to modify the logical name of a module.

"use strict";

require('yoctolib-es2017/yocto_api.js');

async function startDemo(args)
{
    await YAPI.LogUnhandledPromiseRejections();

    // Setup the API to use the VirtualHub on local machine
    let errmsg = new YErrorMsg();
    if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS) {
        console.log('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);
        return;
    }
   
    // Select the relay to use
    let module = YModule.FindModule(args[0]);
    if(await module.isOnline()) {
        if(args.length > 1) {
            let newname = args[1];
            if (!await YAPI.CheckLogicalName(newname)) {
                console.log("Invalid name (" + newname + ")");
                process.exit(1);
            }
            await module.set_logicalName(newname);
            await module.saveToFlash();
        }
        console.log('Current name: '+await module.get_logicalName());
    } else {
        console.log("Module not connected (check identification and USB cable)\n");
    }
    await YAPI.FreeAPI();
}

if(process.argv.length < 2) {
    console.log("usage: node demo.js <serial> [newLogicalName]");
} else {
    startDemo(process.argv.slice(2));
}
 

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the YModule.FirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not null. Below a short example listing the connected modules.

"use strict";

require('yoctolib-es2017/yocto_api.js');

async function startDemo()
{
    await YAPI.LogUnhandledPromiseRejections();
    await YAPI.DisableExceptions();

    // Setup the API to use the VirtualHub on local machine
    let errmsg = new YErrorMsg();
    if (await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS) {
        console.log('Cannot contact VirtualHub on 127.0.0.1');
        return;
    }
    refresh();
}

async function refresh()
{
    try {
        let errmsg = new YErrorMsg();
        await YAPI.UpdateDeviceList(errmsg);

        let module = YModule.FirstModule();
        while(module) {
            let line = await module.get_serialNumber();
            line += '(' + (await module.get_productName()) + ')';
            console.log(line);
            module = module.nextModule();
        }
        setTimeout(refresh, 500);
    } catch(e) {
        console.log(e);
    }
}

try {
    startDemo();
} catch(e) {
    console.log(e);
}
 

15.5. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software. The only way to prevent this is to implement one of the two error handling techniques described below.

The method recommended by most programming languages for unpredictable error handling is the use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while you try to access a module, the library throws an exception. In this case, there are three possibilities:

As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for error handling, allowing you to create a robust program without needing to catch exceptions at every line of code. You simply need to call the YAPI.DisableExceptions() function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values, which can be tested by the caller when necessary. For each function, the name of each return value in case of error is systematically documented in the library reference. The name always follows the same logic: a get_state() method returns a ClassName.STATE_INVALID value, a get_currentValue method returns a ClassName.CURRENTVALUE_INVALID value, and so on. In any case, the returned value is of the expected type and is not a null pointer which would risk crashing your program. At worst, if you display the value without testing it, it will be outside the expected bounds for the returned value. In the case of functions which do not normally return information, the return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.

When you work without exceptions, you can obtain an error code and an error message explaining the source of the error. You can request them from the object which returned the error, calling the errType() and errMessage() methods. Their returned values contain the same information as in the exceptions when they are active.

16. Using Yocto-3D-V2 with PHP

PHP is, like Javascript, an atypical language when interfacing with hardware is at stakes. Nevertheless, using PHP with Yoctopuce modules provides you with the opportunity to very easily create web sites which are able to interact with their physical environment, and this is not available to every web server. This technique has a direct application in home automation: a few Yoctopuce modules, a PHP server, and you can interact with your home from anywhere on the planet, as long as you have an internet connection.

PHP is one of those languages which do not allow you to directly access the hardware layers of your computer. Therefore you need to run a virtual hub on the machine on which your modules are connected.

To start your tests with PHP, you need a PHP 5.3 (or more) server42, preferably locally on you machine. If you wish to use the PHP server of your internet provider, it is possible, but you will probably need to configure your ADSL router for it to accept and forward TCP request on the 4444 port.

16.1. Getting ready

Go to the Yoctopuce web site and download the following items:

Decompress the library files in a folder of your choice accessible to your web server, connect your modules, run the VirtualHub software, and you are ready to start your first tests. You do not need to install any driver.

16.2. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a PHP code snipplet to use the Tilt function.


include('yocto_api.php');
include('yocto_tilt.php');

[...]
// Get access to your device, through the VirtualHub running locally
YAPI::RegisterHub('http://127.0.0.1:4444/',$errmsg);
[...]

// Retrieve the object used to interact with the device
$tilt = YTilt::FindTilt("Y3DMK002-123456.tilt1");

// Check that the module is online to handle hot-plug
if($tilt->isOnline())
{
    // Use $tilt->get_currentValue()
    [...]
}

Let's look at these lines in more details.

yocto_api.php and yocto_tilt.php

These two PHP includes provides access to the functions allowing you to manage Yoctopuce modules. yocto_api.php must always be included, yocto_tilt.php is necessary to manage modules containing a tilt sensor, such as Yocto-3D-V2.

YAPI::RegisterHub

The YAPI::RegisterHub function allows you to indicate on which machine the Yoctopuce modules are located, more precisely on which machine the VirtualHub software is running. In our case, the 127.0.0.1:4444 address indicates the local machine, port 4444 (the standard port used by Yoctopuce). You can very well modify this address, and enter the address of another machine on which the VirtualHub software is running.

YTilt::FindTilt

The YTilt::FindTilt function allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can use logical names as well, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


$tilt = YTilt::FindTilt("Y3DMK002-123456.tilt1");
$tilt = YTilt::FindTilt("Y3DMK002-123456.MyFunction");
$tilt = YTilt::FindTilt("MyModule.tilt1");
$tilt = YTilt::FindTilt("MyModule.MyFunction");
$tilt = YTilt::FindTilt("MyFunction");

YTilt::FindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by YTilt::FindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by yFindTilt provides the angle currently measured by the inclinometer. The value returned is a floating number.

yFindCompass and yFindGyro

Functions yFindCompass, yFindGyro, yFindMagnetometer and yFindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YFindTilt.

A real example

Open your preferred text editor45, copy the code sample below, save it with the Yoctopuce library files in a location which is accessible to you web server, then use your preferred web browser to access this page. The code is also provided in the directory Examples/Doc-GettingStarted-Yocto-3D-V2 of the Yoctopuce library.

In this example, you will recognize the functions explained above, but this time used with all side materials needed to make it work nicely as a small demo.

<HTML>
<HEAD>
 <TITLE> Hello World</TITLE>
</HEAD>
<BODY>
<?php
  include('yocto_api.php');
  include('yocto_tilt.php');
  include('yocto_compass.php');
  include('yocto_gyro.php');
  include('yocto_accelerometer.php');

  // Use explicit error handling rather than exceptions
  YAPI::DisableExceptions();

  // Setup the API to use the VirtualHub on local machine
  if(YAPI::RegisterHub('http://127.0.0.1:4444/',$errmsg) != YAPI::SUCCESS) {
      die("Cannot contact VirtualHub on 127.0.0.1");
  }

  @$serial = $_GET['serial'];
  if ($serial != '') {
      // Check if a specified module is available online
      $anytilt = YTilt::FindTilt("$serial.tilt1");
      if (!$anytilt->isOnline()) {
          die("Module not connected (check serial and USB cable)");
      }
  } else {
      // or use any connected module suitable for the demo
      $anytilt = YTilt::FirstTilt();
      if(is_null($anytilt)) {
          die("No module connected (check USB cable)");
      } else {
          $serial = $anytilt->module()->get_serialnumber();
      }
  }
  Print("Module to use: <input name='serial' value='$serial'><br>");

  // Get all sensor on the device matching the serial
  $tilt1         = YTilt::FindTilt("$serial.tilt1");
  $tilt2         = YTilt::FindTilt("$serial.tilt2");
  $compass       = YCompass::FindCompass("$serial.compass");
  $gyro          = YGyro::FindGyro("$serial.gyro");
  $accelerometer = yFindAccelerometer ("$serial.accelerometer");

  $tilt1value         =  $tilt1->get_currentValue();
  $tilt2value         =  $tilt2 ->get_currentValue();
  $compassvalue       = $compass->get_currentValue();
  $gyrovalue          = $gyro->get_currentValue();
  $accelerometervalue =  $accelerometer->get_currentValue();

  Print("tilt1: $tilt1value &deg;<br>");
  Print("tilt2: $tilt2value &deg;<br>");
  Print("compass: $compassvalue &deg;<br>");
  Print("gyro: $gyrovalue &deg;/s<br>");
  Print("Accelerometer: $accelerometervalue  g<br>");
  YAPI::FreeAPI();

  // trigger auto-refresh after one second
  Print("<script language='javascript1.5' type='text/JavaScript'>\n");
  Print("setTimeout('window.location.reload()',500);");
  Print("</script>\n");
?>
</BODY>
</HTML>
 

16.3. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.

<HTML>
<HEAD>
 <TITLE>Module Control</TITLE>
</HEAD>
<BODY>
<FORM method='get'>
<?php
  include('yocto_api.php');

  // Use explicit error handling rather than exceptions
  YAPI::DisableExceptions();

  // Setup the API to use the VirtualHub on local machine
  if(YAPI::RegisterHub('http://127.0.0.1:4444/',$errmsg) != YAPI::SUCCESS) {
      die("Cannot contact VirtualHub on 127.0.0.1 : ".$errmsg);
  }

  @$serial = $_GET['serial'];
  if ($serial != '') {
      // Check if a specified module is available online
      $module = YModule::FindModule("$serial");
      if (!$module->isOnline()) {
          die("Module not connected (check serial and USB cable)");
      }
  } else {
      // or use any connected module suitable for the demo
      $module = YModule::FirstModule();
      if($module) { // skip VirtualHub
          $module = $module->nextModule();
      }
      if(is_null($module)) {
          die("No module connected (check USB cable)");
      } else {
          $serial = $module->get_serialnumber();
      }
  }
  Print("Module to use: <input name='serial' value='$serial'><br>");

  if (isset($_GET['beacon'])) {
      if ($_GET['beacon']=='ON')
          $module->set_beacon(Y_BEACON_ON);
      else
          $module->set_beacon(Y_BEACON_OFF);
  }
  printf('serial: %s<br>',$module->get_serialNumber());
  printf('logical name: %s<br>',$module->get_logicalName());
  printf('luminosity: %s<br>',$module->get_luminosity());
  print('beacon: ');
  if($module->get_beacon() == Y_BEACON_ON) {
      printf("<input type='radio' name='beacon' value='ON' checked>ON ");
      printf("<input type='radio' name='beacon' value='OFF'>OFF<br>");
  } else {
      printf("<input type='radio' name='beacon' value='ON'>ON ");
      printf("<input type='radio' name='beacon' value='OFF' checked>OFF<br>");
  }
  printf('upTime: %s sec<br>',intVal($module->get_upTime()/1000));
  printf('USB current: %smA<br>',$module->get_usbCurrent());
  printf('logs:<br><pre>%s</pre>',$module->get_lastLogs());
  YAPI::FreeAPI();
?>
<input type='submit' value='refresh'>
</FORM>
</BODY>
</HTML>
 

Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding set_xxx() function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the revertFromFlash() method. The short example below allows you to modify the logical name of a module.

<HTML>
<HEAD>
 <TITLE>save settings</TITLE>
<BODY>
<FORM method='get'>
<?php
  include('yocto_api.php');

  // Use explicit error handling rather than exceptions
  YAPI::DisableExceptions();

  // Setup the API to use the VirtualHub on local machine
  if(YAPI::RegisterHub('http://127.0.0.1:4444/',$errmsg) != YAPI::SUCCESS) {
      die("Cannot contact VirtualHub on 127.0.0.1");
  }

  @$serial = $_GET['serial'];
  if ($serial != '') {
      // Check if a specified module is available online
      $module = YModule::FindModule("$serial");
      if (!$module->isOnline()) {
          die("Module not connected (check serial and USB cable)");
      }
  } else {
      // or use any connected module suitable for the demo
      $module = YModule::FirstModule();
      if($module) { // skip VirtualHub
          $module = $module->nextModule();
      }
      if(is_null($module)) {
          die("No module connected (check USB cable)");
      } else {
          $serial = $module->get_serialnumber();
      }
  }
  Print("Module to use: <input name='serial' value='$serial'><br>");

  if (isset($_GET['newname'])){
      $newname = $_GET['newname'];
      if (!yCheckLogicalName($newname))
          die('Invalid name');
      $module->set_logicalName($newname);
      $module->saveToFlash();
  }
  printf("Current name: %s<br>", $module->get_logicalName());
  print("New name: <input name='newname' value='' maxlength=19><br>");
  YAPI::FreeAPI();
?>
<input type='submit'>
</FORM>
</BODY>
</HTML>
 

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not NULL. Below a short example listing the connected modules.

<HTML>
<HEAD>
 <TITLE>inventory</TITLE>
</HEAD>
<BODY>
<H1>Device list</H1>
<TT>
<?php
    include('yocto_api.php');
    YAPI::RegisterHub("http://127.0.0.1:4444/");
    $module   = YModule::FirstModule();
    while (!is_null($module)) {
        printf("%s (%s)<br>", $module->get_serialNumber(),
               $module->get_productName());
        $module=$module->nextModule();
    }
    YAPI::FreeAPI();
?>
</TT>
</BODY>
</HTML>
 

16.4. HTTP callback API and NAT filters

The PHP library is able to work in a specific mode called HTTP callback Yocto-API. With this mode, you can control Yoctopuce devices installed behind a NAT filter, such as a DSL router for example, and this without needing to open a port. The typical application is to control Yoctopuce devices, located on a private network, from a public web site.

The NAT filter: advantages and disadvantages

A DSL router which translates network addresses (NAT) works somewhat like a private phone switchboard (a PBX): internal extensions can call each other and call the outside; but seen from the outside, there is only one official phone number, that of the switchboard itself. You cannot reach the internal extensions from the outside.


Typical DSL configuration: LAN machines are isolated from the outside by the DSL router

Transposed to the network, we have the following: appliances connected to your home automation network can communicate with one another using a local IP address (of the 192.168.xxx.yyy type), and contact Internet servers through their public address. However, seen from the outside, you have only one official IP address, assigned to the DSL router only, and you cannot reach your network appliances directly from the outside. It is rather restrictive, but it is a relatively efficient protection against intrusions.


Responses from request from LAN machines are routed.


But requests from the outside are blocked.

Seeing Internet without being seen provides an enormous security advantage. However, this signifies that you cannot, a priori, set up your own web server at home to control a home automation installation from the outside. A solution to this problem, advised by numerous home automation system dealers, consists in providing outside visibility to your home automation server itself, by adding a routing rule in the NAT configuration of the DSL router. The issue of this solution is that it exposes the home automation server to external attacks.

The HTTP callback API solves this issue without having to modify the DSL router configuration. The module control script is located on an external site, and it is the VirtualHub which is in charge of calling it a regular intervals.


The HTTP callback API uses the VirtualHub which initiates the requests.

Configuration

The callback API thus uses the VirtualHub as a gateway. All the communications are initiated by the VirtualHub. They are thus outgoing communications and therefore perfectly authorized by the DSL router.

You must configure the VirtualHub so that it calls the PHP script on a regular basis. To do so:

  1. Launch a VirtualHub
  2. Access its interface, usually 127.0.0.1:4444
  3. Click on the configure button of the line corresponding to the VirtualHub itself
  4. Click on the edit button of the Outgoing callbacks section


Click on the "configure" button on the first line


Click on the "edit" button of the "Outgoing callbacks" section


And select "Yocto-API callback".

You then only need to define the URL of the PHP script and, if need be, the user name and password to access this URL. Supported authentication methods are basic and digest. The second method is safer than the first one because it does not allow transfer of the password on the network.

Usage

From the programmer standpoint, the only difference is at the level of the yRegisterHub function call. Instead of using an IP address, you must use the callback string (or http://callback which is equivalent).


include("yocto_api.php");
yRegisterHub("callback");

The remainder of the code stays strictly identical. On the VirtualHub interface, at the bottom of the configuration window for the HTTP callback API , there is a button allowing you to test the call to the PHP script.

Be aware that the PHP script controlling the modules remotely through the HTTP callback API can be called only by the VirtualHub. Indeed, it requires the information posted by the VirtualHub to function. To code a web site which controls Yoctopuce modules interactively, you must create a user interface which stores in a file or in a database the actions to be performed on the Yoctopuce modules. These actions are then read and run by the control script.

Common issues

For the HTTP callback API to work, the PHP option allow_url_fopen must be set. Some web site hosts do not set it by default. The problem then manifests itself with the following error:

error: URL file-access is disabled in the server configuration

To set this option, you must create, in the repertory where the control PHP script is located, an .htaccess file containing the following line:
php_flag "allow_url_fopen" "On"
Depending on the security policies of the host, it is sometimes impossible to authorize this option at the root of the web site, or even to install PHP scripts receiving data from a POST HTTP. In this case, place the PHP script in a subdirectory.

Limitations

This method that allows you to go through NAT filters cheaply has nevertheless a price. Communications being initiated by the VirtualHub at a more or less regular interval, reaction time to an event is clearly longer than if the Yoctopuce modules were driven directly. You can configure the reaction time in the specific window of the VirtualHub, but it is at least of a few seconds in the best case.

The HTTP callback Yocto-API mode is currently available in PHP, EcmaScript (Node.JS) and Java only.

16.5. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software. The only way to prevent this is to implement one of the two error handling techniques described below.

The method recommended by most programming languages for unpredictable error handling is the use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while you try to access a module, the library throws an exception. In this case, there are three possibilities:

As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for error handling, allowing you to create a robust program without needing to catch exceptions at every line of code. You simply need to call the YAPI.DisableExceptions() function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values, which can be tested by the caller when necessary. For each function, the name of each return value in case of error is systematically documented in the library reference. The name always follows the same logic: a get_state() method returns a ClassName.STATE_INVALID value, a get_currentValue method returns a ClassName.CURRENTVALUE_INVALID value, and so on. In any case, the returned value is of the expected type and is not a null pointer which would risk crashing your program. At worst, if you display the value without testing it, it will be outside the expected bounds for the returned value. In the case of functions which do not normally return information, the return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.

When you work without exceptions, you can obtain an error code and an error message explaining the source of the error. You can request them from the object which returned the error, calling the errType() and errMessage() methods. Their returned values contain the same information as in the exceptions when they are active.

17. Using Yocto-3D-V2 with Visual Basic .NET

VisualBasic has long been the most favored entrance path to the Microsoft world. Therefore, we had to provide our library for this language, even if the new trend is shifting to C#. All the examples and the project models are tested with Microsoft VisualBasic 2010 Express, freely available on the Microsoft web site46.

17.1. Installation

Download the Visual Basic Yoctopuce library from the Yoctopuce web site47. There is no setup program, simply copy the content of the zip file into the directory of your choice. You mostly need the content of the Sources directory. The other directories contain the documentation and a few sample programs. All sample projects are Visual Basic 2010, projects, if you are using a previous version, you may have to recreate the projects structure from scratch.

17.2. Using the Yoctopuce API in a Visual Basic project

The Visual Basic.NET Yoctopuce library is composed of a DLL and of source files in Visual Basic. The DLL is not a .NET DLL, but a classic DLL, written in C, which manages the low level communications with the modules48. The source files in Visual Basic manage the high level part of the API. Therefore, your need both this DLL and the .vb files of the sources directory to create a project managing Yoctopuce modules.

Configuring a Visual Basic project

The following indications are provided for Visual Studio Express 2010, but the process is similar for other versions. Start by creating your project. Then, on the Solution Explorer panel, right click on your project, and select "Add" and then "Add an existing item".

A file selection window opens. Select the yocto_api.vb file and the files corresponding to the functions of the Yoctopuce modules that your project is going to manage. If in doubt, select all the files.

You then have the choice between simply adding these files to your project, or to add them as links (the Add button is in fact a scroll-down menu). In the first case, Visual Studio copies the selected files into your project. In the second case, Visual Studio simply keeps a link on the original files. We recommend you to use links, which makes updates of the library much easier.

Then add in the same manner the yapi.dll DLL, located in the Sources/dll directory49. Then, from the Solution Explorer window, right click on the DLL, select Properties and in the Properties panel, set the Copy to output folder to always. You are now ready to use your Yoctopuce modules from Visual Studio.

In order to keep them simple, all the examples provided in this documentation are console applications. Naturally, the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface.

17.3. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a Visual Basic code snipplet to use the Tilt function.


[...]
' Enable detection of USB devices
Dim errmsg As String errmsg
YAPI.RegisterHub("usb", errmsg)
[...]

' Retrieve the object used to interact with the device
Dim tilt As YTilt
tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1")

' Hot-plug is easy: just check that the device is online
If (tilt.isOnline()) Then
   ' Use tilt.get_currentValue()
   [...]
End If

[...]

Let's look at these lines in more details.

YAPI.RegisterHub

The YAPI.RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for. When used with the parameter "usb", it will use the modules locally connected to the computer running the library. If the initialization does not succeed, this function returns a value different from YAPI_SUCCESS and errmsg contains the error message.

YTilt.FindTilt

The YTilt.FindTilt function allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can use logical names as well, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1")
tilt = YTilt.FindTilt("Y3DMK002-123456.MyFunction")
tilt = YTilt.FindTilt("MyModule.tilt1")
tilt = YTilt.FindTilt("MyModule.MyFunction")
tilt = YTilt.FindTilt("MyFunction")

YTilt.FindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by YTilt.FindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by yFindTilt provides the angle currently measured by the inclinometer. The value returned is a floating number.

yFindCompass and yFindGyro

Functions yFindCompass, yFindGyro, yFindMagnetometer and yFindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YFindTilt.

A real example

Launch Microsoft VisualBasic and open the corresponding sample project provided in the directory Examples/Doc-GettingStarted-Yocto-3D-V2 of the Yoctopuce library.

In this example, you will recognize the functions explained above, but this time used with all side materials needed to make it work nicely as a small demo.

Module Module1

  Private Sub Usage()
    Dim execname = System.AppDomain.CurrentDomain.FriendlyName
    Console.WriteLine("Usage:")
    Console.WriteLine(execname + " <serial_number>")
    Console.WriteLine(execname + " <logical_name>")
    Console.WriteLine(execname + " any  ")
    System.Threading.Thread.Sleep(2500)

    End
  End Sub

  Sub Main()
    Dim argv() As String = System.Environment.GetCommandLineArgs()
    Dim errmsg As String = ""
    Dim target As String
    Dim serial As String
    Dim count As Integer
    Dim anytilt, tilt1, tilt2 As YTilt
    Dim compass As YCompass
    Dim accelerometer As YAccelerometer
    Dim gyro As YGyro

    If argv.Length < 2 Then Usage()

    target = argv(1)

    REM Setup the API to use local USB devices
    If (YAPI.RegisterHub("usb", errmsg) <> YAPI_SUCCESS) Then
      Console.WriteLine("RegisterHub error: " + errmsg)
      End
    End If

    If target = "any" Then
      anytilt = YTilt.FirstTilt()
      If anytilt Is Nothing Then
        Console.WriteLine("No module connected (check USB cable)")
        End
      End If
    Else
      anytilt = YTilt.FindTilt(target + ".tilt1")
      If Not (anytilt.isOnline()) Then
        Console.WriteLine("Module not connected (check identification and USB cable)")
        End
      End If
    End If

    serial = anytilt.get_module().get_serialNumber()
    tilt1 = YTilt.FindTilt(serial + ".tilt1")
    tilt2 = YTilt.FindTilt(serial + ".tilt2")
    compass = YCompass.FindCompass(serial + ".compass")
    accelerometer = YAccelerometer.FindAccelerometer(serial + ".accelerometer")
    gyro = YGyro.FindGyro(serial + ".gyro")
    count = 0

    While (True)
      If (Not tilt1.isOnline()) Then
        Console.WriteLine("Module disconnected")
        End
      End If

      If (count Mod 10 = 0) Then
        Console.WriteLine("tilt1" + Chr(9) + "tilt2" + Chr(9) + "compass" _
                          + Chr(9) + "acc" + Chr(9) + "gyro")
      End If
      Console.Write(tilt1.get_currentValue().ToString() + Chr(9))
      Console.Write(tilt2.get_currentValue().ToString() + Chr(9))
      Console.Write(compass.get_currentValue().ToString() + Chr(9))
      Console.Write(accelerometer.get_currentValue().ToString() + Chr(9))
      Console.WriteLine(gyro.get_currentValue().ToString())
      count = count + 1
      YAPI.Sleep(250, errmsg)
    End While
    YAPI.FreeAPI()
  End Sub

End Module
 

17.4. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.


Imports System.IO
Imports System.Environment

Module Module1

  Sub usage()
    Console.WriteLine("usage: demo <serial or logical name> [ON/OFF]")
    End
  End Sub

  Sub Main()
    Dim argv() As String = System.Environment.GetCommandLineArgs()
    Dim errmsg As String = ""
    Dim m As ymodule

    If (YAPI.RegisterHub("usb", errmsg) <> YAPI_SUCCESS) Then
      Console.WriteLine("RegisterHub error:" + errmsg)
      End
    End If

    If argv.Length < 2 Then usage()

    m = YModule.FindModule(argv(1)) REM use serial or logical name
    If (m.isOnline()) Then
      If argv.Length > 2 Then
        If argv(2) = "ON" Then m.set_beacon(Y_BEACON_ON)
        If argv(2) = "OFF" Then m.set_beacon(Y_BEACON_OFF)
      End If
      Console.WriteLine("serial:       " + m.get_serialNumber())
      Console.WriteLine("logical name: " + m.get_logicalName())
      Console.WriteLine("luminosity:   " + Str(m.get_luminosity()))
      Console.Write("beacon:       ")
      If (m.get_beacon() = Y_BEACON_ON) Then
        Console.WriteLine("ON")
      Else
        Console.WriteLine("OFF")
      End If
      Console.WriteLine("upTime:       " + Str(m.get_upTime() / 1000) + " sec")
      Console.WriteLine("USB current:  " + Str(m.get_usbCurrent()) + " mA")
      Console.WriteLine("Logs:")
      Console.WriteLine(m.get_lastLogs())
    Else
      Console.WriteLine(argv(1) + " not connected (check identification and USB cable)")
    End If
    YAPI.FreeAPI()
  End Sub

End Module
 

Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding set_xxx() function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the revertFromFlash() method. The short example below allows you to modify the logical name of a module.

Module Module1


  Sub usage()

    Console.WriteLine("usage: demo <serial or logical name> <new logical name>")
    End
  End Sub

  Sub Main()
    Dim argv() As String = System.Environment.GetCommandLineArgs()
    Dim errmsg As String = ""
    Dim newname As String
    Dim m As YModule

    If (argv.Length <> 3) Then usage()

    REM Setup the API to use local USB devices
    If YAPI.RegisterHub("usb", errmsg) <> YAPI_SUCCESS Then
      Console.WriteLine("RegisterHub error: " + errmsg)
      End
    End If

    m = YModule.FindModule(argv(1)) REM use serial or logical name
    If m.isOnline() Then
      newname = argv(2)
      If (Not YAPI.CheckLogicalName(newname)) Then
        Console.WriteLine("Invalid name (" + newname + ")")
        End
      End If
      m.set_logicalName(newname)
      m.saveToFlash() REM do not forget this
      Console.Write("Module: serial= " + m.get_serialNumber)
      Console.Write(" / name= " + m.get_logicalName())
    Else
      Console.Write("not connected (check identification and USB cable")
    End If
    YAPI.FreeAPI()

  End Sub

End Module
 

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not Nothing. Below a short example listing the connected modules.

Module Module1

  Sub Main()
    Dim M As ymodule
    Dim errmsg As String = ""

    REM Setup the API to use local USB devices
    If YAPI.RegisterHub("usb", errmsg) <> YAPI_SUCCESS Then
      Console.WriteLine("RegisterHub error: " + errmsg)
      End
    End If

    Console.WriteLine("Device list")
    M = YModule.FirstModule()
    While M IsNot Nothing
      Console.WriteLine(M.get_serialNumber() + " (" + M.get_productName() + ")")
      M = M.nextModule()
    End While
    YAPI.FreeAPI()
  End Sub

End Module
 

17.5. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software. The only way to prevent this is to implement one of the two error handling techniques described below.

The method recommended by most programming languages for unpredictable error handling is the use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while you try to access a module, the library throws an exception. In this case, there are three possibilities:

As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for error handling, allowing you to create a robust program without needing to catch exceptions at every line of code. You simply need to call the YAPI.DisableExceptions() function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values, which can be tested by the caller when necessary. For each function, the name of each return value in case of error is systematically documented in the library reference. The name always follows the same logic: a get_state() method returns a ClassName.STATE_INVALID value, a get_currentValue method returns a ClassName.CURRENTVALUE_INVALID value, and so on. In any case, the returned value is of the expected type and is not a null pointer which would risk crashing your program. At worst, if you display the value without testing it, it will be outside the expected bounds for the returned value. In the case of functions which do not normally return information, the return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.

When you work without exceptions, you can obtain an error code and an error message explaining the source of the error. You can request them from the object which returned the error, calling the errType() and errMessage() methods. Their returned values contain the same information as in the exceptions when they are active.

18. Using Yocto-3D-V2 with Delphi

Delphi is a descendent of Turbo-Pascal. Originally, Delphi was produced by Borland, Embarcadero now edits it. The strength of this language resides in its ease of use, as anyone with some notions of the Pascal language can develop a Windows application in next to no time. Its only disadvantage is to cost something50.

Delphi libraries are provided not as VCL components, but directly as source files. These files are compatible with most Delphi versions. 51

To keep them simple, all the examples provided in this documentation are console applications. Obviously, the libraries work in a strictly identical way with VCL applications.

You will soon notice that the Delphi API defines many functions which return objects. You do not need to deallocate these objects yourself, the API does it automatically at the end of the application.

18.1. Preparation

Go to the Yoctopuce web site and download the Yoctopuce Delphi libraries52. Uncompress everything in a directory of your choice, add the subdirectory sources in the list of directories of Delphi libraries.53

By default, the Yoctopuce Delphi library uses the yapi.dll DLL, all the applications you will create with Delphi must have access to this DLL. The simplest way to ensure this is to make sure yapi.dll is located in the same directory as the executable file of your application.

18.2. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a Delphi code snipplet to use the Tilt function.


uses yocto_api, yocto_tilt;

var errmsg: string;
    tilt: TYTilt;

[...]
// Enable detection of USB devices
yRegisterHub('usb',errmsg)
[...]

// Retrieve the object used to interact with the device
tilt = yFindTilt("Y3DMK002-123456.tilt1")

// Hot-plug is easy: just check that the device is online
if tilt.isOnline() then
    begin
        // Use tilt.get_currentValue()
        [...]
    end;
[...]

Let's look at these lines in more details.

yocto_api and yocto_tilt

These two units provide access to the functions allowing you to manage Yoctopuce modules. yocto_api must always be used, yocto_tilt is necessary to manage modules containing a tilt sensor, such as Yocto-3D-V2.

yRegisterHub

The yRegisterHub function initializes the Yoctopuce API and specifies where the modules should be looked for. When used with the parameter 'usb', it will use the modules locally connected to the computer running the library. If the initialization does not succeed, this function returns a value different from YAPI_SUCCESS and errmsg contains the error message.

yFindTilt

The yFindTilt function allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can also use logical names, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


tilt := yFindTilt("Y3DMK002-123456.tilt1");
tilt := yFindTilt("Y3DMK002-123456.MyFunction");
tilt := yFindTilt("MyModule.tilt1");
tilt := yFindTilt("MyModule.MyFunction");
tilt := yFindTilt("MyFunction");

yFindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by yFindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by yFindTilt provides the angle currently measured by the inclinometer. The value returned is a floating number.

yFindCompass and yFindGyro

Functions yFindCompass, yFindGyro, yFindMagnetometer and yFindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YFindTilt.

A real example

Launch your Delphi environment, copy the yapi.dll DLL in a directory, create a new console application in the same directory, and copy-paste the piece of code below:

In this example, you will recognize the functions explained above, but this time used with all side materials needed to make it work nicely as a small demo.

program helloworld;
{$APPTYPE CONSOLE}
uses
  SysUtils,
  Windows,
  yocto_api,
  yocto_tilt,
  yocto_compass,
  yocto_accelerometer,
  yocto_gyro;

Procedure  Usage();
  var
   exe : string;

  begin
    exe:= ExtractFileName(paramstr(0));
    WriteLn(exe+' <serial_number>');
    WriteLn(exe+' <logical_name>');
    WriteLn(exe+' any');
    halt;
  End;

var
  m             : TYmodule;
  anytilt,tilt1,tilt2   : TYTilt;
  Compass       : TYcompass;
  accelerometer : TYAccelerometer;
  gyro          : TYGyro;
  errmsg,serial : string;
  done          : boolean;
  count         : integer;

begin
   if (paramcount<1) then usage();

  // Setup the API to use local USB devices
  if yRegisterHub('usb', errmsg)<>YAPI_SUCCESS then
  begin
    Write('RegisterHub error: '+errmsg);
    exit;
  end;

  if paramstr(1)='any' then
    begin
      // lets try to find the first available tilt sensor
      anytilt := yFirstTilt();
      if anytilt=nil then
         begin
           writeln('No module connected (check USB cable)');
           halt;
         end
       end
   else
  // or the one specified on command line
  anytilt:= YFindTilt(paramstr(1)+'.tilt1');

  // make sure it is online
  if  not anytilt.isOnline() then
    begin
      writeln('No module connected (check USB cable)');
      halt;
    end;

  // lets find the parent module so we can get the other sensors
  m      :=  anytilt.get_module();
  serial :=  m.get_serialNumber();

  // retreive some sensors present on the yocto-3D
  tilt1         := yFindTilt(serial+'.tilt1');
  tilt2         := yFindTilt(serial+'.tilt2');
  compass       := yFindCompass(serial+'.compass');
  accelerometer :=  yFindaccelerometer(serial+'.accelerometer');
  gyro          :=yFindGyro(serial+'.gyro');

  // let's poll
  done := false;
  count :=0;

  repeat
    if (tilt1.isOnline()) then
     begin
       if (count mod 10=0) then   Writeln('tilt1'#9'tilt2'#9'compass'#9'acc'#9'gyro');
       Write(FloatToStr(tilt1.get_currentValue())+#9);
       Write(FloatToStr(tilt2.get_currentValue())+#9);
       Write(FloatToStr(compass.get_currentValue())+#9);
       Write(FloatToStr(accelerometer.get_currentValue())+#9);
       Writeln(FloatToStr(gyro.get_currentValue()));
       inc(count);
       Sleep(100);
     end
    else
     begin
       Writeln('Module not connected (check identification and USB cable)');
       done := true;
     end;
  until done;
  yFreeAPI();
end.

18.3. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.

program modulecontrol;
{$APPTYPE CONSOLE}
uses
  SysUtils,
  yocto_api;

const
  serial = 'Y3DMK002-123456'; // use serial number or logical name

procedure refresh(module:Tymodule) ;
  begin
    if (module.isOnline())  then
     begin
       Writeln('');
       Writeln('Serial       : ' + module.get_serialNumber());
       Writeln('Logical name : ' + module.get_logicalName());
       Writeln('Luminosity   : ' + intToStr(module.get_luminosity()));
       Write('Beacon    :');
       if  (module.get_beacon()=Y_BEACON_ON) then Writeln('on')
                                             else Writeln('off');
       Writeln('uptime       : ' + intToStr(module.get_upTime() div 1000)+'s');
       Writeln('USB current  : ' + intToStr(module.get_usbCurrent())+'mA');
       Writeln('Logs         : ');
       Writeln(module.get_lastlogs());
       Writeln('');
       Writeln('r : refresh / b:beacon ON / space : beacon off');
     end
    else Writeln('Module not connected (check identification and USB cable)');
  end;


procedure beacon(module:Tymodule;state:integer);
  begin
    module.set_beacon(state);
    refresh(module);
  end;

var
  module : TYModule;
  c      : char;
  errmsg : string;

begin
  // Setup the API to use local USB devices
  if yRegisterHub('usb', errmsg)<>YAPI_SUCCESS then
  begin
    Write('RegisterHub error: '+errmsg);
    exit;
  end;

  module := yFindModule(serial);
  refresh(module);

  repeat
    read(c);
    case c of
     'r': refresh(module);
     'b': beacon(module,Y_BEACON_ON);
     ' ': beacon(module,Y_BEACON_OFF);
    end;
  until  c = 'x';
  yFreeAPI();
end.

Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding set_xxx() function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the revertFromFlash() method. The short example below allows you to modify the logical name of a module.

program savesettings;
{$APPTYPE CONSOLE}
uses
  SysUtils,
  yocto_api;

const
  serial = 'Y3DMK002-123456'; // use serial number or logical name

var
  module  : TYModule;
  errmsg  : string;
  newname : string;

begin
  // Setup the API to use local USB devices
  if yRegisterHub('usb', errmsg)<>YAPI_SUCCESS then
  begin
    Write('RegisterHub error: '+errmsg);
    exit;
  end;

  module := yFindModule(serial);
  if (not(module.isOnline)) then
   begin
     writeln('Module not connected (check identification and USB cable)');
     exit;
   end;

  Writeln('Current logical name : '+module.get_logicalName());
  Write('Enter new name : ');
  Readln(newname);
  if (not(yCheckLogicalName(newname))) then
   begin
     Writeln('invalid logical name');
     exit;
   end;
  module.set_logicalName(newname);
  module.saveToFlash();
  yFreeAPI();
  Writeln('logical name is now : '+module.get_logicalName());
end.
 

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not nil. Below a short example listing the connected modules.

program inventory;
{$APPTYPE CONSOLE}
uses
  SysUtils,
  yocto_api;

var
  module : TYModule;
  errmsg : string;

begin
  // Setup the API to use local USB devices
  if yRegisterHub('usb', errmsg)<>YAPI_SUCCESS then
  begin
    Write('RegisterHub error: '+errmsg);
    exit;
  end;

  Writeln('Device list');

  module := yFirstModule();
  while module<>nil  do
   begin
     Writeln( module.get_serialNumber()+' ('+module.get_productName()+')');
     module := module.nextModule();
   end;
  yFreeAPI();

end.

18.4. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software. The only way to prevent this is to implement one of the two error handling techniques described below.

The method recommended by most programming languages for unpredictable error handling is the use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while you try to access a module, the library throws an exception. In this case, there are three possibilities:

As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for error handling, allowing you to create a robust program without needing to catch exceptions at every line of code. You simply need to call the YAPI.DisableExceptions() function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values, which can be tested by the caller when necessary. For each function, the name of each return value in case of error is systematically documented in the library reference. The name always follows the same logic: a get_state() method returns a ClassName.STATE_INVALID value, a get_currentValue method returns a ClassName.CURRENTVALUE_INVALID value, and so on. In any case, the returned value is of the expected type and is not a null pointer which would risk crashing your program. At worst, if you display the value without testing it, it will be outside the expected bounds for the returned value. In the case of functions which do not normally return information, the return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.

When you work without exceptions, you can obtain an error code and an error message explaining the source of the error. You can request them from the object which returned the error, calling the errType() and errMessage() methods. Their returned values contain the same information as in the exceptions when they are active.

19. Using the Yocto-3D-V2 with Universal Windows Platform

Universal Windows Platform (UWP) is not a language per say, but a software platform created by Microsoft. This platform allows you to run a new type of applications: the universal Windows applications. These applications can work on all machines running under Windows 10. This includes computers, tablets, smart phones, XBox One, and also Windows IoT Core.

The Yoctopuce UWP library allows you to use Yoctopuce modules in a universal Windows application and is written in C# in its entirety. You can add it to a Visual Studio 201754 project.

19.1. Blocking and asynchronous functions

The Universal Windows Platform does not use the Win32 API but only the Windows Runtime API which is available on all the versions of Windows 10 and for any architecture. Thanks to this library, you can use UWP on all the Windows 10 versions, including Windows 10 IoT Core.

However, using the new UWP API has some consequences: the Windows Runtime API to access the USB ports is asynchronous, and therefore the Yoctopuce library must be asynchronous as well. Concretely, the asynchronous methods do not return a result directly but a Task or Task<> object and the result can be obtained later. Fortunately, the C# language, version 6, supports the async and await keywords, which simplifies using these functions enormously. You can thus use asynchronous functions in the same way as traditional functions as long as you respect the following two rules:

Example:

async Task<int> MyFunction(int  val)
{
    // do some long computation
    ...

    return result;
}

int res = await MyFunction(1234);
Our library follows these two rules and can therefore use the await notation.

For you not to have to wonder wether a function is asynchronous or not, there is the following convention: all the public methods of the UWP library are asynchronous, that is that you must call them with the await keyword, except:

19.2. Installation

Download the Yoctopuce library for Universal Windows Platform from the Yoctopuce web site55. There is no installation software, simply copy the content of the zip file in a directory of your choice. You essentially need the content of the Sources directory. The other directories contain documentation and a few sample programs. Sample projects are Visual Studio 2017 projects. Visual Studio 2017 is available on the Microsoft web site56.

19.3. Using the Yoctopuce API in a Visual Studio project

Start by creating your project. Then, from the Solution Explorer panel right click on your project and select Add then Existing element .

A file chooser opens: select all the files in the library Sources directory.

You then have the choice between simply adding the files to your project or adding them as a link (the Add button is actually a drop-down menu). In the first case, Visual Studio copies the selected files into your project. In the second case, Visual Studio simply creates a link to the original files. We recommend to use links, as a potential library update is thus much easier.

The Package.appxmanifest file

By default a Universal Windows application doesn't have access rights to the USB ports. If you want to access USB devices, you must imperatively declare it in the Package.appxmanifest file.

Unfortunately, the edition window of this file doesn't allow this operation and you must modify the Package.appxmanifest file by hand. In the "Solution Explorer" panel, right click on the Package.appxmanifest and select "View Code".

In this XML file, we must add a DeviceCapability node in the Capabilities node. This node must have a "Name" attribute with a "humaninterfacedevice" value.

Inside this node, you must declare all the modules that can be used. Concretely, for each module, you must add a "Device" node with an "Id" attribute, which has for value a character string "vidpid:USB_VENDORID USB_DEVICE_ID". The Yoctopuce USB_VENDORID is 24e0 and you can find the USB_DEVICE_ID of each Yoctopuce device in the documentation in the "Characteristics" section. Finally, the "Device" node must contain a "Function" node with the "Type" attribute with a value of "usage:ff00 0001".

For the Yocto-3D-V2, here is what you must add in the "Capabilities" node:


  <DeviceCapability Name="humaninterfacedevice">
      <!-- Yocto-3D-V2 -->
      <Device Id="vidpid:24e0 006A">
        <Function Type="usage:ff00 0001" />
      </Device>
    </DeviceCapability>

Unfortunately, it's not possible to write a rule authorizing all Yoctopuce modules. Therefore, you must imperatively add each module that you want to use.

19.4. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a C# code snippet to use the Tilt function.


[...]
// Enable detection of USB devices
await YAPI.RegisterHub("usb");
[...]

// Retrieve the object used to interact with the device
YTilt tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1");

// Hot-plug is easy: just check that the device is online
if (await tilt.isOnline())
{
        // Use tilt.get_currentValue()
    [...]
}

[...]

Let us look at these lines in more details.

YAPI.RegisterHub

The YAPI.RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for. The parameter is the address of the virtual hub able to see the devices. If the string "usb" is passed as parameter, the API works with modules locally connected to the machine. If the initialization does not succeed, an exception is thrown.

YTilt.FindTilt

The YTilt.FindTilt function allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can use logical names as well, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


tilt = YTilt.FindTilt("Y3DMK002-123456.tilt1");
tilt = YTilt.FindTilt("Y3DMK002-123456.MaFonction");
tilt = YTilt.FindTilt("MonModule.tilt1");
tilt = YTilt.FindTilt("MonModule.MaFonction");
tilt = YTilt.FindTilt("MaFonction");

YTilt.FindTilt returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline() method of the object returned by YTilt.FindTilt allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by YTilt.FindTilt provides the value of orientation measured by the tilt sensor. The value returned is a floating number.

YCompass.FindCompass, YGyro.FindGyro...

Functions YCompass.FindCompass, YMagnetometer.FindMagnetometer, YGyro.FindGyro and YAccelerometer.FindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YTilt.FindTilt.

19.5. A real example

Launch Visual Studio and open the corresponding project provided in the directory Examples/Doc-GettingStarted-Yocto-3D-V2 of the Yoctopuce library.

Visual Studio projects contain numerous files, and most of them are not linked to the use of the Yoctopuce library. To simplify reading the code, we regrouped all the code that uses the library in the Demo class, located in the demo.cs file. Properties of this class correspond to the different fields displayed on the screen, and the Run() method contains the code which is run when the "Start" button is pushed.

In this example, you can recognize the functions explained above, but this time used with all the side materials needed to make it work nicely as a small demo.

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using com.yoctopuce.YoctoAPI;

namespace Demo
{
  public class Demo : DemoBase
  {
    public string HubURL { get; set; }
    public string Target { get; set; }

    public override async Task<int> Run()
    {
      try {
        await YAPI.RegisterHub(HubURL);

        YTilt anytilt, tilt1, tilt2;
        YCompass compass;
        YAccelerometer accel;
        YGyro gyro;

        if (Target.ToLower() == "any") {
          anytilt = YTilt.FirstTilt();
          if (anytilt == null) {
            WriteLine("No module connected (check USB cable)");
            return -1;
          }
        } else {
          anytilt = YTilt.FindTilt(Target + ".tilt1");
        }

        string serial = await (await anytilt.get_module()).get_serialNumber();
        tilt1 = YTilt.FindTilt(serial + ".tilt1");
        tilt2 = YTilt.FindTilt(serial + ".tilt2");
        compass = YCompass.FindCompass(serial + ".compass");
        accel = YAccelerometer.FindAccelerometer(serial + ".accelerometer");
        gyro = YGyro.FindGyro(serial + ".gyro");
        int count = 0;

        while (await tilt1.isOnline()) {
          if (count++ % 10 == 0) {
            WriteLine("tilt1   tilt2   compass   acc   gyro");
          }
          Write(await tilt1.get_currentValue() + "\t");
          Write(await tilt2.get_currentValue() + "\t");
          Write(await compass.get_currentValue() + "\t");
          Write(await accel.get_currentValue() + "\t");
          WriteLine("" + await gyro.get_currentValue());
          await YAPI.Sleep(250);
        }

        WriteLine("Module not connected (check identification and USB cable)");
      } catch (YAPI_Exception ex) {
        WriteLine("error: " + ex.Message);
      }

      YAPI.FreeAPI();
      return 0;
    }
  }
}

19.6. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using com.yoctopuce.YoctoAPI;

namespace Demo
{
  public class Demo : DemoBase
  {

    public string HubURL { get; set; }
    public string Target { get; set; }
    public bool Beacon { get; set; }

    public override async Task<int> Run()
    {
      YModule m;
      string errmsg = "";

      if (await YAPI.RegisterHub(HubURL) != YAPI.SUCCESS) {
        WriteLine("RegisterHub error: " + errmsg);
        return -1;
      }
      m = YModule.FindModule(Target + ".module"); // use serial or logical name
      if (await m.isOnline()) {
        if (Beacon) {
          await m.set_beacon(YModule.BEACON_ON);
        } else {
          await m.set_beacon(YModule.BEACON_OFF);
        }

        WriteLine("serial: " + await m.get_serialNumber());
        WriteLine("logical name: " + await m.get_logicalName());
        WriteLine("luminosity: " + await m.get_luminosity());
        Write("beacon: ");
        if (await m.get_beacon() == YModule.BEACON_ON)
          WriteLine("ON");
        else
          WriteLine("OFF");
        WriteLine("upTime: " + (await m.get_upTime() / 1000) + " sec");
        WriteLine("USB current: " + await m.get_usbCurrent() + " mA");
        WriteLine("Logs:\r\n" + await m.get_lastLogs());
      } else {
        WriteLine(Target + " not connected  on" + HubURL +
                  "(check identification and USB cable)");
      }
      YAPI.FreeAPI();
      return 0;
    }
  }
}

Each property xxx of the module can be read thanks to a method of type YModule.get_xxxx(), and properties which are not read-only can be modified with the help of the YModule.set_xxx() method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding YModule.set_xxx() function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the YModule.saveToFlash() method. Inversely, it is possible to force the module to forget its current settings by using the YModule.revertFromFlash() method. The short example below allows you to modify the logical name of a module.

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using com.yoctopuce.YoctoAPI;

namespace Demo
{
  public class Demo : DemoBase
  {

    public string HubURL { get; set; }
    public string Target { get; set; }
    public string LogicalName { get; set; }

    public override async Task<int> Run()
    {
      try {
        YModule m;

        await YAPI.RegisterHub(HubURL);

        m = YModule.FindModule(Target); // use serial or logical name
        if (await m.isOnline()) {
          if (!YAPI.CheckLogicalName(LogicalName)) {
            WriteLine("Invalid name (" + LogicalName + ")");
            return -1;
          }

          await m.set_logicalName(LogicalName);
          await m.saveToFlash(); // do not forget this
          Write("Module: serial= " + await m.get_serialNumber());
          WriteLine(" / name= " + await m.get_logicalName());
        } else {
          Write("not connected (check identification and USB cable");
        }
      } catch (YAPI_Exception ex) {
        WriteLine("RegisterHub error: " + ex.Message);
      }
      YAPI.FreeAPI();
      return 0;
    }
  }
}

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the YModule.saveToFlash() function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the YModule.yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not null. Below a short example listing the connected modules.

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using com.yoctopuce.YoctoAPI;

namespace Demo
{
  public class Demo : DemoBase
  {
    public string HubURL { get; set; }

    public override async Task<int> Run()
    {
      YModule m;
      try {
        await YAPI.RegisterHub(HubURL);

        WriteLine("Device list");
        m = YModule.FirstModule();
        while (m != null) {
          WriteLine(await m.get_serialNumber()
                    + " (" + await m.get_productName() + ")");
          m = m.nextModule();
        }
      } catch (YAPI_Exception ex) {
        WriteLine("Error:" + ex.Message);
      }
      YAPI.FreeAPI();
      return 0;
    }
  }
}

19.7. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software.

In the Universal Windows Platform library, error handling is implemented with exceptions. You must therefore intercept and correctly handle these exceptions if you want to have a reliable project which does not crash as soon as you disconnect a module.

Library thrown exceptions are always of the YAPI_Exception type, so you can easily separate them from other exceptions in a try{...} catch{...} block.

Example:


try {
        ....
} catch (YAPI_Exception ex) {
        Debug.WriteLine("Exception from Yoctopuce lib:" + ex.Message);
} catch (Exception ex) {
        Debug.WriteLine("Other exceptions :" + ex.Message);
}

20. Using Yocto-3D-V2 with Objective-C

Objective-C is language of choice for programming on Mac OS X, due to its integration with the Cocoa framework. In order to use the Objective-C library, you need XCode version 4.2 (earlier versions will not work), available freely when you run Lion. If you are still under Snow Leopard, you need to be registered as Apple developer to be able to download XCode 4.2. The Yoctopuce library is ARC compatible. You can therefore implement your projects either using the traditional retain / release method, or using the Automatic Reference Counting.

Yoctopuce Objective-C libraries57 are integrally provided as source files. A section of the low-level library is written in pure C, but you should not need to interact directly with it: everything was done to ensure the simplest possible interaction from Objective-C.

You will soon notice that the Objective-C API defines many functions which return objects. You do not need to deallocate these objects yourself, the API does it automatically at the end of the application.

In order to keep them simple, all the examples provided in this documentation are console applications. Naturally, the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface. You can find on Yoctopuce blog a detailed example58 with video shots showing how to integrate the library into your projects.

20.1. Control of the Tilt function

A few lines of code are enough to use a Yocto-3D-V2. Here is the skeleton of a Objective-C code snipplet to use the Tilt function.


#import "yocto_api.h"
#import "yocto_tilt.h"

...
NSError *error;
[YAPI RegisterHub:@"usb": &error]
...
// On récupère l'objet représentant le module (ici connecté en local sur USB)
tilt = [YTilt FindTilt:@"Y3DMK002-123456.tilt1"];

// Pour gérer le hot-plug, on vérifie que le module est là
if([tilt isOnline])
{
    // Utiliser [tilt get_currentValue]
    ...
}

Let's look at these lines in more details.

yocto_api.h and yocto_tilt.h

These two import files provide access to the functions allowing you to manage Yoctopuce modules. yocto_api.h must always be used, yocto_tilt.h is necessary to manage modules containing a tilt sensor, such as Yocto-3D-V2.

[YAPI RegisterHub]

The [YAPI RegisterHub] function initializes the Yoctopuce API and indicates where the modules should be looked for. When used with the parameter @"usb", it will use the modules locally connected to the computer running the library. If the initialization does not succeed, this function returns a value different from YAPI_SUCCESS and errmsg contains the error message.

[Tilt FindTilt]

The [Tilt FindTilt] function allows you to find a tilt sensor from the serial number of the module on which it resides and from its function name. You can use logical names as well, as long as you have initialized them. Let us imagine a Yocto-3D-V2 module with serial number Y3DMK002-123456 which you have named "MyModule", and for which you have given the tilt1 function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.


YTilt *tilt = [Tilt FindTilt:@"Y3DMK002-123456.tilt1"];
YTilt *tilt = [Tilt FindTilt:@"Y3DMK002-123456.MyFunction"];
YTilt *tilt = [Tilt FindTilt:@"MyModule.tilt1"];
YTilt *tilt = [Tilt FindTilt:@"MyModule.MyFunction"];
YTilt *tilt = [Tilt FindTilt:@"MyFunction"];

[Tilt FindTilt] returns an object which you can then use at will to control the tilt sensor.

isOnline

The isOnline method of the object returned by [Tilt FindTilt] allows you to know if the corresponding module is present and in working order.

get_currentValue

The get_currentValue() method of the object returned by YTilt.FindTilt provides the value of orientation measured by the tilt sensor. The value returned is a floating number.

YCompass.FindCompass, YGyro.FindGyro...

Functions YCompass.FindCompass, YMagnetometer.FindMagnetometer, YGyro.FindGyro and YAccelerometer.FindAccelerometer allow you to work with compass, magnetometer, gyroscope, acceleration measures. You can handle them just as YTilt.FindTilt.

A real example

Launch Xcode 4.2 and open the corresponding sample project provided in the directory Examples/Doc-GettingStarted-Yocto-3D-V2 of the Yoctopuce library.

In this example, you will recognize the functions explained above, but this time used with all side materials needed to make it work nicely as a small demo.

#import <Foundation/Foundation.h>
#import "yocto_api.h"
#import "yocto_tilt.h"
#import "yocto_compass.h"
#import "yocto_gyro.h"
#import "yocto_accelerometer.h"

static void usage(void)
{
  NSLog(@"usage: demo <serial_number> ");
  NSLog(@"       demo <logical_name>");
  NSLog(@"       demo any                 (use any discovered device)");
  exit(1);
}

int main(int argc, const char * argv[])
{
  NSError *error;

  if (argc < 2) {
    usage();
  }

  @autoreleasepool {
    // Setup the API to use local USB devices
    if([YAPI RegisterHub:@"usb": &error] != YAPI_SUCCESS) {
      NSLog(@"RegisterHub error: %@", [error localizedDescription]);
      return 1;
    }

    NSString *target = [NSString stringWithUTF8String:argv[1]];
    YTilt *anytilt, *tilt1, *tilt2;
    YCompass *compass;
    YAccelerometer *accelerometer;
    YGyro *gyro;

    if([target isEqualToString:@"any"]) {
      anytilt = [YTilt FirstTilt];
      if (anytilt == NULL) {
        NSLog(@"No module connected (check USB cable)");
        return 1;
      }
    } else {
      anytilt = [YTilt FindTilt:[target stringByAppendingString:@".tilt1"]];
      if(![anytilt isOnline]) {
        NSLog(@"Module not connected (check identification and USB cable)");
        return 1;
      }
    }
    NSString *serial = [[anytilt get_module] get_serialNumber];
    // retrieve all sensors on the device matching the serial
    tilt1 = [YTilt FindTilt:[serial stringByAppendingString:@".tilt1"]];
    tilt2 = [YTilt FindTilt:[serial stringByAppendingString:@".tilt2"]];
    compass = [YCompass FindCompass:[serial stringByAppendingString:@".compass"]];
    accelerometer = [YAccelerometer FindAccelerometer:[serial stringByAppendingString:
                     @".accelerometer"]];
    gyro = [YGyro FindGyro:[serial stringByAppendingString:@".gyro"]];
    int count = 0;

    while(1) {
      if(![tilt1 isOnline]) {
        NSLog(@"device disconnected");
        break;
      }
      if ((count % 10) == 0)
        NSLog(@"tilt1\ntilt2\ncompass\tacc\tgyro");
      NSLog(@"%f\n%f\n%f\t%f\t%f",
            [tilt1 get_currentValue],
            [tilt2 get_currentValue],
            [compass get_currentValue],
            [accelerometer get_currentValue],
            [gyro get_currentValue]);
      count++;

      [YAPI Sleep:250:NULL];
    }
    [YAPI FreeAPI];
  }

  return 0;
}
 

20.2. Control of the module part

Each module can be controlled in a similar manner, you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon.

#import <Foundation/Foundation.h>
#import "yocto_api.h"

static void usage(const char *exe)
{
  NSLog(@"usage: %s <serial or logical name> [ON/OFF]\n", exe);
  exit(1);
}


int main (int argc, const char * argv[])
{
  NSError *error;

  @autoreleasepool {
    // Setup the API to use local USB devices
    if([YAPI RegisterHub:@"usb": &error] != YAPI_SUCCESS) {
      NSLog(@"RegisterHub error: %@", [error localizedDescription]);
      return 1;
    }
    if(argc < 2)
      usage(argv[0]);
    NSString *serial_or_name = [NSString stringWithUTF8String:argv[1]];
    // use serial or logical name
    YModule *module = [YModule FindModule:serial_or_name];
    if ([module isOnline]) {
      if (argc > 2) {
        if (strcmp(argv[2], "ON") == 0)
          [module setBeacon:Y_BEACON_ON];
        else
          [module setBeacon:Y_BEACON_OFF];
      }
      NSLog(@"serial:       %@\n", [module serialNumber]);
      NSLog(@"logical name: %@\n", [module logicalName]);
      NSLog(@"luminosity:   %d\n", [module luminosity]);
      NSLog(@"beacon:       ");
      if ([module beacon] == Y_BEACON_ON)
        NSLog(@"ON\n");
      else
        NSLog(@"OFF\n");
      NSLog(@"upTime:       %ld sec\n", [module upTime] / 1000);
      NSLog(@"USB current:  %d mA\n",  [module usbCurrent]);
      NSLog(@"logs:  %@\n",  [module get_lastLogs]);
    } else {
      NSLog(@"%@ not connected (check identification and USB cable)\n",
            serial_or_name);
    }
    [YAPI FreeAPI];
  }
  return 0;
}
 

Each property xxx of the module can be read thanks to a method of type get_xxxx, and properties which are not read-only can be modified with the help of the set_xxx: method. For more details regarding the used functions, refer to the API chapters.

Changing the module settings

When you want to modify the settings of a module, you only need to call the corresponding set_xxx: function. However, this modification is performed only in the random access memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize them persistently, it is necessary to ask the module to save its current configuration in its permanent memory. To do so, use the saveToFlash method. Inversely, it is possible to force the module to forget its current settings by using the revertFromFlash method. The short example below allows you to modify the logical name of a module.

#import <Foundation/Foundation.h>
#import "yocto_api.h"

static void usage(const char *exe)
{
  NSLog(@"usage: %s <serial> <newLogicalName>\n", exe);
  exit(1);
}


int main (int argc, const char * argv[])
{
  NSError *error;

  @autoreleasepool {
    // Setup the API to use local USB devices
    if([YAPI RegisterHub:@"usb" :&error] != YAPI_SUCCESS) {
      NSLog(@"RegisterHub error: %@", [error localizedDescription]);
      return 1;
    }

    if(argc < 2)
      usage(argv[0]);

    NSString *serial_or_name = [NSString stringWithUTF8String:argv[1]];
    // use serial or logical name
    YModule *module = [YModule FindModule:serial_or_name];

    if (module.isOnline) {
      if (argc >= 3) {
        NSString *newname =  [NSString stringWithUTF8String:argv[2]];
        if (![YAPI CheckLogicalName:newname]) {
          NSLog(@"Invalid name (%@)\n", newname);
          usage(argv[0]);
        }
        module.logicalName = newname;
        [module saveToFlash];
      }
      NSLog(@"Current name: %@\n", module.logicalName);
    } else {
      NSLog(@"%@ not connected (check identification and USB cable)\n",
            serial_or_name);
    }
    [YAPI FreeAPI];
  }
  return 0;
}
 

Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to the technology employed by the module micro-processor, is located at about 100000 cycles. In short, you can use the saveToFlash function only 100000 times in the life of the module. Make sure you do not call this function within a loop.

Listing the modules

Obtaining the list of the connected modules is performed with the yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not NULL. Below a short example listing the connected modules.

#import <Foundation/Foundation.h>
#import "yocto_api.h"

int main (int argc, const char * argv[])
{
  NSError *error;

  @autoreleasepool {
    // Setup the API to use local USB devices
    if([YAPI RegisterHub:@"usb" :&error] != YAPI_SUCCESS) {
      NSLog(@"RegisterHub error: %@\n", [error localizedDescription]);
      return 1;
    }

    NSLog(@"Device list:\n");

    YModule *module = [YModule FirstModule];
    while (module != nil) {
      NSLog(@"%@ %@", module.serialNumber, module.productName);
      module = [module nextModule];
    }
    [YAPI FreeAPI];
  }
  return 0;
}
 

20.3. Error handling

When you implement a program which must interact with USB modules, you cannot disregard error handling. Inevitably, there will be a time when a user will have unplugged the device, either before running the software, or even while the software is running. The Yoctopuce library is designed to help you support this kind of behavior, but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library.

The simplest way to work around the problem is the one used in the short examples provided in this chapter: before accessing a module, check that it is online with the isOnline function, and then hope that it will stay so during the fraction of a second necessary for the following code lines to run. This method is not perfect, but it can be sufficient in some cases. You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software. The only way to prevent this is to implement one of the two error handling techniques described below.

The method recommended by most programming languages for unpredictable error handling is the use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while you try to access a module, the library throws an exception. In this case, there are three possibilities:

As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for error handling, allowing you to create a robust program without needing to catch exceptions at every line of code. You simply need to call the YAPI.DisableExceptions() function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values, which can be tested by the caller when necessary. For each function, the name of each return value in case of error is systematically documented in the library reference. The name always follows the same logic: a get_state() method returns a ClassName.STATE_INVALID value, a get_currentValue method returns a ClassName.CURRENTVALUE_INVALID value, and so on. In any case, the returned value is of the expected type and is not a null pointer which would risk crashing your program. At worst, if you display the value without testing it, it will be outside the expected bounds for the returned value. In the case of functions which do not normally return information, the return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.

When you work without exceptions, you can obtain an error code and an error message explaining the source of the error. You can request them from the object which returned the error, calling the errType() and errMessage() methods. Their returned values contain the same information as in the exceptions when they are active.

21. Using with unsupported languages

Yoctopuce modules can be driven from most common programming languages. New languages are regularly added, depending on the interest expressed by Yoctopuce product users. Nevertheless, some languages are not, and will never be, supported by Yoctopuce. There can be several reasons for this: compilers which are not available anymore, unadapted environments, etc.

However, there are alternative methods to access Yoctopuce modules from an unsupported programming language.

21.1. Command line

The easiest method to drive Yoctopuce modules from an unsupported programming language is to use the command line API through system calls. The command line API is in fact made of a group of small executables which are easy to call. Their output is also easy to analyze. As most programming languages allow you to make system calls, the issue is solved with a few lines of code.

However, if the command line API is the easiest solution, it is neither the fastest nor the most efficient. For each call, the executable must initialize its own API and make an inventory of USB connected modules. This requires about one second per call.

21.2. .NET Assembly

A .NET Assembly enables you to share a set of pre-compiled classes to offer a service, by stating entry points which can be used by third-party applications. In our case, it's the whole Yoctopuce library which is available in the .NET Assembly, so that it can be used in any environment which supports .NET Assembly dynamic loading.

The Yoctopuce library as a .NET Assembly does not contain only the standard C# Yoctopuce library, as this wouldn't have allowed an optimal use in all environments. Indeed, we cannot expect host applications to necessarily offer a thread system or a callback system, although they are very useful to manage plug-and-play events and sensors with a high refresh rate. Likewise, we can't expect from external applications a transparent behavior in cases where a function call in Assembly creates a delay because of network communications.

Therefore, we added to it an additional layer, called .NET Proxy library. This additional layer offers an interface very similar to the standard library but somewhat simplified, as it internally manages all the callback mechanisms. Instead, this library offers mirror objects, called Proxys, which publish through Properties the main attributes of the Yoctopuce functions such as the current measure, configuration parameters, the state, and so on.


.NET Assembly Architecture

The callback mechanism automatically updates the properties of the Proxys objects, without the host application needing to care for it. The later can thus, at any time and without any risk of latency, display the value of all properties of Yoctopuce Proxy objects.

Pay attention to the fact that the yapi.dll low-level communication library is not included in the .NET Assembly. You must therefore keep it together with DotNetProxyLibrary.dll. The 32 bit version must be located in the same directory as DotNetProxyLibrary.dll, while the 64 bit version must be in a subdirectory amd64.

Example of use with MATLAB

Here is how to load our Proxy .NET Assembly in MATLAB and how to read the value of the first sensor connected by USB found on the machine:


NET.addAssembly("C:/Yoctopuce/DotNetProxyLibrary.dll");
import YoctoProxyAPI.*

errmsg = YAPIProxy.RegisterHub("usb");
sensor = YSensorProxy.FindSensor("");
measure = sprintf('%.3f %s', sensor.CurrentValue, sensor.Unit);

Example of use in PowerShell

PowerShell commands are a little stranger, but we can recognize the same structure:


Add-Type -Path "C:/Yoctopuce/DotNetProxyLibrary.dll"

$errmsg = [YoctoProxyAPI.YAPIProxy]::RegisterHub("usb")
$sensor = [YoctoProxyAPI.YSensorProxy]::FindSensor("")
$measure = "{0:n3} {1}" -f $sensor.CurrentValue, $sensor.Unit

Specificities of the .NET Proxy library

With regards to classic Yoctopuce libraries, the following differences in particular should be noted:

No FirstModule/nextModule method

To obtain an object referring to the first found module, we call YModuleProxy.FindModule(""). If there is no connected module, this method returns an object with its module.IsOnline property set to False. As soon as a module is connected, the property changes to True and the module hardware identifier is updated.

To list modules, you can call the module.GetSimilarFunctions() method which returns an array of character strings containing the identifiers of all the modules which were found.

No callback function

Callback functions are implemented internally and they update the object properties. You can therefore simply poll the properties, without significant performance penalties. Be aware that if you use one of the function that disables callbacks, the automatic refresh of object properties may not work anymore.

A new method YAPIProxy.GetLog makes it possible to retrieve low-level debug logs without using callbacks.

Enumerated types

In order to maximize compatibility with host applications, the .NET Proxy library does not use true .NET enumerated types, but simple integers. For each enumerated type, the library includes public constants named according to the possible values. Contrarily to standard Yoctopuce libraries, numeric values always start from 1, as the value 0 is reserved to return an invalid value, for instance when the device is disconnected.

Invalid numeric results

For all numeric results, rather than using an arbitrary constant, the invalid value returned in case of error is NaN. You should therefore use function isNaN() to detect this value.

Using .NET Assembly without the Proxy library

If for a reason or another you don't want to use the Proxy library, and if your environment allows it, you can use the standard C# API as it is located in the Assembly, under the YoctoLib namespace. Beware however not to mix both types of use: either you go through the Proxy library, or you use he YoctoLib version directly, but not both!

Compatibilité

For the LabVIEW Yoctopuce library to work correctly with your Yoctopuce modules, these modules need to have firmware 37120, or higher.

In order to be compatible with as many versions of Windows as possible, including Windows XP, the DotNetProxyLibrary.dll library is compiled in .NET 3.5, which is available by default on all the Windows versions since XP. As of today, we have never met any non-Windows environment able to load a .NET Assembly, so we only ship the low-level communication dll for Windows together with the assembly.

21.3. VirtualHub and HTTP GET

The VirtualHub is available on almost all current platforms. It is generally used as a gateway to provide access to Yoctopuce modules from languages which prevent direct access to hardware layers of a computer (JavaScript, PHP, Java, ...).

In fact, the VirtualHub is a small web server able to route HTTP requests to Yoctopuce modules. This means that if you can make an HTTP request from your programming language, you can drive Yoctopuce modules, even if this language is not officially supported.

REST interface

At a low level, the modules are driven through a REST API. Thus, to control a module, you only need to perform appropriate requests on the VirtualHub. By default, the VirtualHub HTTP port is 4444.

An important advantage of this technique is that preliminary tests are very easy to implement. You only need a VirtualHub and a simple web browser. If you copy the following URL in your preferred browser, while the VirtualHub is running, you obtain the list of the connected modules.


http://127.0.0.1:4444/api/services/whitePages.txt

Note that the result is displayed as text, but if you request whitePages.xml, you obtain an XML result. Likewise, whitePages.json allows you to obtain a JSON result. The html extension even allows you to display a rough interface where you can modify values in real time. The whole REST API is available in these different formats.

Driving a module through the REST interface

Each Yoctopuce module has its own REST interface, available in several variants. Let us imagine a Yocto-3D-V2 with the Y3DMK002-12345 serial number and the myModule logical name. The following URL allows you to know the state of the module.


http://127.0.0.1:4444/bySerial/Y3DMK002-12345/api/module.txt

You can naturally also use the module logical name rather than its serial number.


http://127.0.0.1:4444/byName/myModule/api/module.txt

To retrieve the value of a module property, simply add the name of the property below module. For example, if you want to know the signposting led luminosity, send the following request:


http://127.0.0.1:4444/bySerial/Y3DMK002-12345/api/module/luminosity

To change the value of a property, modify the corresponding attribute. Thus, to modify the luminosity, send the following request:


http://127.0.0.1:4444/bySerial/Y3DMK002-12345/api/module?luminosity=100

Driving the module functions through the REST interface

The module functions can be manipulated in the same way. To know the state of the tilt1 function, build the following URL:


http://127.0.0.1:4444/bySerial/Y3DMK002-12345/api/tilt1.txt

Note that if you can use logical names for the modules instead of their serial number, you cannot use logical names for functions. Only hardware names are authorized to access functions.

You can retrieve a module function attribute in a way rather similar to that used with the modules. For example:


http://127.0.0.1:4444/bySerial/Y3DMK002-12345/api/tilt1/logicalName

Rather logically, attributes can be modified in the same manner.


http://127.0.0.1:4444/bySerial/Y3DMK002-12345/api/tilt1?logicalName=myFunction

You can find the list of available attributes for your Yocto-3D-V2 at the beginning of the Programming chapter.

Accessing Yoctopuce data logger through the REST interface

This section only applies to devices with a built-in data logger.

The preview of all recorded data streams can be retrieved in JSON format using the following URL:


http://127.0.0.1:4444/bySerial/Y3DMK002-12345/dataLogger.json

Individual measures for any given stream can be obtained by appending the desired function identifier as well as start time of the stream:


http://127.0.0.1:4444/bySerial/Y3DMK002-12345/dataLogger.json?id=tilt1&utc=1389801080

21.4. Using dynamic libraries

The low level Yoctopuce API is available under several formats of dynamic libraries written in C. The sources are available with the C++ API. If you use one of these low level libraries, you do not need the VirtualHub anymore.

FilenamePlatform
libyapi.dylibMax OS X
libyapi-amd64.soLinux Intel (64 bits)
libyapi-armel.soLinux ARM EL (32 bits)
libyapi-armhf.soLinux ARM HL (32 bits)
libyapi-aarch64.soLinux ARM (64 bits)
libyapi-i386.soLinux Intel (32 bits)
yapi64.dllWindows (64 bits)
yapi.dllWindows (32 bits)

These dynamic libraries contain all the functions necessary to completely rebuild the whole high level API in any language able to integrate these libraries. This chapter nevertheless restrains itself to describing basic use of the modules.

Driving a module

The three essential functions of the low level API are the following:


int yapiInitAPI(int connection_type, char *errmsg);
int yapiUpdateDeviceList(int forceupdate, char *errmsg);
int yapiHTTPRequest(char *device, char *request, char* buffer,int buffsize,int *fullsize, char *errmsg);

The yapiInitAPI function initializes the API and must be called once at the beginning of the program. For a USB type connection, the connection_type parameter takes value 1. The errmsg parameter must point to a 255 character buffer to retrieve a potential error message. This pointer can also point to null. The function returns a negative integer in case of error, zero otherwise.

The yapiUpdateDeviceList manages the inventory of connected Yoctopuce modules. It must be called at least once. To manage hot plug and detect potential newly connected modules, this function must be called at regular intervals. The forceupdate parameter must take value 1 to force a hardware scan. The errmsg parameter must point to a 255 character buffer to retrieve a potential error message. This pointer can also point to null. The function returns a negative integer in case of error, zero otherwise.

Finally, the yapiHTTPRequest function sends HTTP requests to the module REST API. The device parameter contains the serial number or the logical name of the module which you want to reach. The request parameter contains the full HTTP request (including terminal line breaks). buffer points to a character buffer long enough to contain the answer. buffsize is the size of the buffer. fullsize is a pointer to an integer to which will be assigned the actual size of the answer. The errmsg parameter must point to a 255 character buffer to retrieve a potential error message. This pointer can also point to null. The function returns a negative integer in case of error, zero otherwise.

The format of the requests is the same as the one described in the VirtualHub et HTTP GET section. All the character strings used by the API are strings made of 8-bit characters: Unicode and UTF8 are not supported.

The resutlt returned in the buffer variable respects the HTTP protocol. It therefore includes an HTTP header. This header ends with two empty lines, that is a sequence of four ASCII characters 13, 10, 13, 10.

Here is a sample program written in pascal using the yapi.dll DLL to read and then update the luminosity of a module.


// Dll functions import
function  yapiInitAPI(mode:integer;
                      errmsg : pansichar):integer;cdecl;
                      external 'yapi.dll' name 'yapiInitAPI';
function  yapiUpdateDeviceList(force:integer;errmsg : pansichar):integer;cdecl;
                      external 'yapi.dll' name 'yapiUpdateDeviceList';
function  yapiHTTPRequest(device:pansichar;url:pansichar; buffer:pansichar;
                      buffsize:integer;var fullsize:integer;
                      errmsg : pansichar):integer;cdecl;
                      external 'yapi.dll' name 'yapiHTTPRequest';

var
 errmsgBuffer  : array [0..256] of ansichar;
 dataBuffer    : array [0..1024] of ansichar;
 errmsg,data   : pansichar;
 fullsize,p    : integer;

const
  serial      = 'Y3DMK002-12345';
  getValue = 'GET /api/module/luminosity HTTP/1.1'#13#10#13#10;
  setValue = 'GET /api/module?luminosity=100 HTTP/1.1'#13#10#13#10;

begin
  errmsg  :=  @errmsgBuffer;
  data    :=  @dataBuffer;
  // API  initialization
  if(yapiInitAPI(1,errmsg)<0) then
   begin
    writeln(errmsg);
    halt;
  end;

  // forces a device inventory
  if( yapiUpdateDeviceList(1,errmsg)<0) then
    begin
     writeln(errmsg);
     halt;
   end;

  // requests the  module luminosity
  if (yapiHTTPRequest(serial,getValue,data,sizeof(dataBuffer),fullsize,errmsg)<0) then
   begin
     writeln(errmsg);
     halt;
   end;

  // searches for the HTTP header end
  p := pos(#13#10#13#10,data);

  // displays the response minus the HTTP header
  writeln(copy(data,p+4,length(data)-p-3));

  // changes the luminosity
  if (yapiHTTPRequest(serial,setValue,data,sizeof(dataBuffer),fullsize,errmsg)<0) then
   begin
     writeln(errmsg);
     halt;
   end;

end.

Module inventory

To perform an inventory of Yoctopuce modules, you need two functions from the dynamic library:


 int yapiGetAllDevices(int *buffer,int maxsize,int *neededsize,char *errmsg);
 int yapiGetDeviceInfo(int devdesc,yDeviceSt *infos, char *errmsg);

The yapiGetAllDevices function retrieves the list of all connected modules as a list of handles. buffer points to a 32-bit integer array which contains the returned handles. maxsize is the size in bytes of the buffer. To neededsize is assigned the necessary size to store all the handles. From this, you can deduce either the number of connected modules or that the input buffer is too small. The errmsg parameter must point to a 255 character buffer to retrieve a potential error message. This pointer can also point to null. The function returns a negative integer in case of error, zero otherwise.

The yapiGetDeviceInfo function retrieves the information related to a module from its handle. devdesc is a 32-bit integer representing the module and which was obtained through yapiGetAllDevices. infos points to a data structure in which the result is stored. This data structure has the following format:

Name TypeSize (bytes)Description
vendorid int4Yoctopuce USB ID
deviceid int4Module USB ID
devrelease int4Module version
nbinbterfaces int4Number of USB interfaces used by the module
manufacturer char[]20Yoctopuce (null terminated)
productname char[]28Model (null terminated)
serial char[]20Serial number (null terminated)
logicalname char[]20Logical name (null terminated)
firmware char[]22Firmware version (null terminated)
beacon byte1Beacon state (0/1)

The errmsg parameter must point to a 255 character buffer to retrieve a potential error message.

Here is a sample program written in pascal using the yapi.dll DLL to list the connected modules.


// device description structure
type yDeviceSt = packed record
   vendorid        : word;
   deviceid        : word;
   devrelease      : word;
   nbinbterfaces   : word;
   manufacturer    : array [0..19] of ansichar;
   productname     : array [0..27] of ansichar;
   serial          : array [0..19] of ansichar;
   logicalname     : array [0..19] of ansichar;
   firmware        : array [0..21] of ansichar;
   beacon          : byte;
 end;

// Dll function import
function  yapiInitAPI(mode:integer;
                      errmsg : pansichar):integer;cdecl;
                      external 'yapi.dll' name 'yapiInitAPI';

function  yapiUpdateDeviceList(force:integer;errmsg : pansichar):integer;cdecl;
                      external 'yapi.dll' name 'yapiUpdateDeviceList';

function  yapiGetAllDevices( buffer:pointer;
                             maxsize:integer;
                             var neededsize:integer;
                             errmsg : pansichar):integer; cdecl;
                             external 'yapi.dll' name 'yapiGetAllDevices';

function  apiGetDeviceInfo(d:integer; var infos:yDeviceSt;
                             errmsg : pansichar):integer;  cdecl;
                             external 'yapi.dll' name 'yapiGetDeviceInfo';


var
 errmsgBuffer  : array [0..256] of ansichar;
 dataBuffer    : array [0..127] of integer;   // max of 128 USB devices
 errmsg,data   : pansichar;
 neededsize,i  : integer;
 devinfos      : yDeviceSt;

begin
  errmsg  :=  @errmsgBuffer;

  // API  initialization
  if(yapiInitAPI(1,errmsg)<0) then
   begin
    writeln(errmsg);
    halt;
  end;

   // forces a device inventory
  if( yapiUpdateDeviceList(1,errmsg)<0) then
    begin
     writeln(errmsg);
     halt;
   end;

  // loads all device handles into dataBuffer
  if yapiGetAllDevices(@dataBuffer,sizeof(dataBuffer),neededsize,errmsg)<0 then
    begin
     writeln(errmsg);
     halt;
    end;

  // gets device info from each handle
  for i:=0 to  neededsize div sizeof(integer)-1 do
   begin
     if (apiGetDeviceInfo(dataBuffer[i], devinfos, errmsg)<0) then
       begin
         writeln(errmsg);
         halt;
       end;
     writeln(pansichar(@devinfos.serial)+' ('+pansichar(@devinfos.productname)+')');
   end;

end.

VB6 and yapi.dll

Each entry point from the yapi.dll is duplicated. You will find one regular C-decl version and one Visual Basic 6 compatible version, prefixed with vb6_.

21.5. Porting the high level library

As all the sources of the Yoctopuce API are fully provided, you can very well port the whole API in the language of your choice. Note, however, that a large portion of the API source code is automatically generated.

Therefore, it is not necessary for you to port the complete API. You only need to port the yocto_api file and one file corresponding to a function, for example yocto_relay. After a little additional work, Yoctopuce is then able to generate all other files. Therefore, we highly recommend that you contact Yoctopuce support before undertaking to port the Yoctopuce library in another language. Collaborative work is advantageous to both parties.

22. Firmware Update

There are multiples way to update the firmware of a Yoctopuce module..

22.1. The VirtualHub or the YoctoHub

It is possible to update the firmware directly from the web interface of the VirtualHub or the YoctoHub. The configuration panel of the module has an "upgrade" button to start a wizard that will guide you through the firmware update procedure.

In case the firmware update fails for any reason, and the module does no start anymore, simply unplug the module then plug it back while maintaining the Yocto-button down. The module will boot in "firmware update" mode and will appear in the VirtualHub interface below the module list.

22.2. The command line library

All the command line tools can update Yoctopuce modules thanks to the downloadAndUpdate command. The module selection mechanism works like for a traditional command. The [target] is the name of the module that you want to update. You can also use the "any" or "all" aliases, or even a name list, where the names are separated by commas, without spaces.


C:\>Executable [options] [target] command [parameters]

The following example updates all the Yoctopuce modules connected by USB.


C:\>YModule all downloadAndUpdate
ok: Yocto-PowerRelay RELAYHI1-266C8(rev=15430) is up to date.
ok: 0 / 0 hubs in 0.000000s.
ok: 0 / 0 shields in 0.000000s.
ok: 1 / 1 devices in 0.130000s 0.130000s per device.
ok: All devices are now up to date.
C:\>

22.3. The Android application Yocto-Firmware

You can update your module firmware from your Android phone or tablet with the Yocto-Firmware application. This application lists all the Yoctopuce modules connected by USB and checks if a more recent firmware is available on www.yoctopuce.com. If a more recent firmware is available, you can update the module. The application is responsible for downloading and installing the new firmware while preserving the module parameters.

Please note: while the firmware is being updated, the module restarts several times. Android interprets a USB device reboot as a disconnection and reconnection of the USB device and asks the authorization to use the USB port again. The user must click on OK for the update process to end successfully.

22.4. Updating the firmware with the programming library

If you need to integrate firmware updates in your application, the libraries offer you an API to update your modules. 59

Saving and restoring parameters

The get_allSettings() method returns a binary buffer enabling you to save a module persistent parameters. This function is very useful to save the network configuration of a YoctoHub for example.


YWireless wireless = YWireless.FindWireless("reference");
YModule m = wireless.get_module();
byte[] default_config =  m.get_allSettings();
saveFile("default.bin", default_config);
...

You can then apply these parameters to other modules with the set_allSettings() method.


byte[] default_config = loadFile("default.bin");
YModule m = YModule.FirstModule();
while (m != null) {
  if (m.get_productName() == "YoctoHub-Wireless") {
    m.set_allSettings(default_config);
  }
  m = m.next();
}

Finding the correct firmware

The first step to update a Yoctopuce module is to find which firmware you must use. The checkFirmware(path, onlynew) method of the YModule object does exactly this. The method checks that the firmware given as argument (path) is compatible with the module. If the onlynew parameter is set, this method checks that the firmware is more recent than the version currently used by the module. When the file is not compatible (or if the file is older than the installed version), this method returns an empty string. In the opposite, if the file is valid, the method returns a file access path.

The following piece of code checks that the c:\tmp\METEOMK1.17328.byn is compatible with the module stored in the m variable .


YModule m = YModule.FirstModule();
...
...
string path = "c:\\tmp\METEOMK1.17328.byn";
string newfirm = m.checkFirmware(path, false);
if (newfirm != "") {
  Console.WriteLine("firmware " + newfirm + " is compatible");
}
...

The argument can be a directory (instead of a file). In this case, the method checks all the files of the directory recursively and returns the most recent compatible firmware. The following piece of code checks whether there is a more recent firmware in the c:\tmp\ directory.


YModule m = YModule.FirstModule();
...
...
string path = "c:\\tmp";
string newfirm = m.checkFirmware(path, true);
if (newfirm != "") {
  Console.WriteLine("firmware " + newfirm + " is compatible and newer");
}
...

You can also give the "www.yoctopuce.com" string as argument to check whether there is a more recent published firmware on Yoctopuce's web site. In this case, the method returns the firmware URL. You can use this URL to download the firmware on your disk or use this URL when updating the firmware (see below). Obviously, this possibility works only if your machine is connected to Internet.


YModule m = YModule.FirstModule();
...
...
string url = m.checkFirmware("www.yoctopuce.com", true);
if (url != "") {
  Console.WriteLine("new firmware is available at " + url );
}
...

Updating the firmware

A firmware update can take several minutes. That is why the update process is run as a background task and is driven by the user code thanks to the YFirmwareUdpate class.

To update a Yoctopuce module, you must obtain an instance of the YFirmwareUdpate class with the updateFirmware method of a YModule object. The only parameter of this method is the path of the firmware that you want to install. This method does not immediately start the update, but returns a YFirmwareUdpate object configured to update the module.


string newfirm = m.checkFirmware("www.yoctopuce.com", true);
.....
YFirmwareUpdate fw_update = m.updateFirmware(newfirm);

The startUpdate() method starts the update as a background task. This background task automatically takes care of

  1. saving the module parameters
  2. restarting the module in "update" mode
  3. updating the firmware
  4. starting the module with the new firmware version
  5. restoring the parameters

The get_progress() and get_progressMessage() methods enable you to follow the progression of the update. get_progress() returns the progression as a percentage (100 = update complete). get_progressMessage() returns a character string describing the current operation (deleting, writing, rebooting, ...). If the get_progress method returns a negative value, the update process failed. In this case, the get_progressMessage() returns an error message.

The following piece of code starts the update and displays the progress on the standard output.


YFirmwareUpdate fw_update = m.updateFirmware(newfirm);
....
int status = fw_update.startUpdate();
while (status < 100 && status >= 0) {
  int newstatus = fw_update.get_progress();
  if (newstatus != status) {
    Console.WriteLine(status + "% "
      + fw_update.get_progressMessage());
  }
  YAPI.Sleep(500, ref errmsg);
  status = newstatus;
}

if (status < 0) {
  Console.WriteLine("Firmware Update failed: "
    + fw_update.get_progressMessage());
} else {
  Console.WriteLine("Firmware Updated Successfully!");
}

An Android characteristic

You can update a module firmware using the Android library. However, for modules connected by USB, Android asks the user to authorize the application to access the USB port.

During firmware update, the module restarts several times. Android interprets a USB device reboot as a disconnection and a reconnection to the USB port, and prevents all USB access as long as the user has not closed the pop-up window. The use has to click on OK for the update process to continue correctly. You cannot update a module connected by USB to an Android device without having the user interacting with the device.

22.5. The "update" mode

If you want to erase all the parameters of a module or if your module does not start correctly anymore, you can install a firmware from the "update" mode.

To force the module to work in "update" mode, disconnect it, wait a few seconds, and reconnect it while maintaining the Yocto-button down. This will restart the module in "update" mode. This update mode is protected against corruptions and is always available.

In this mode, the module is not detected by the YModule objects anymore. To obtain the list of connected modules in "update" mode, you must use the YAPI.GetAllBootLoaders() function. This function returns a character string array with the serial numbers of the modules in "update" mode.


List<string> allBootLoader = YAPI.GetAllBootLoaders();

The update process is identical to the standard case (see the preceding section), but you must manually instantiate the YFirmwareUpdate object instead of calling module.updateFirmware(). The constructor takes as argument three parameters: the module serial number, the path of the firmware to be installed, and a byte array with the parameters to be restored at the end of the update (or null to restore default parameters).


YFirmwareUpdateupdate fw_update;
fw_update = new YFirmwareUpdate(allBootLoader[0], newfirm, null);
int status = fw_update.startUpdate();
.....

23. Advanced programming

The preceding chapters have introduced, in each available language, the basic programming functions which can be used with your Yocto-3D-V2 module. This chapter presents in a more generic manner a more advanced use of your module. Examples are provided in the language which is the most popular among Yoctopuce customers, that is C#. Nevertheless, you can find complete examples illustrating the concepts presented here in the programming libraries of each language.

To remain as concise as possible, examples provided in this chapter do not perform any error handling. Do not copy them "as is" in a production application.

23.1. Event programming

The methods to manage Yoctopuce modules which we presented to you in preceding chapters were polling functions, consisting in permanently asking the API if something had changed. While easy to understand, this programming technique is not the most efficient, nor the most reactive. Therefore, the Yoctopuce programming API also provides an event programming model. This technique consists in asking the API to signal by itself the important changes as soon as they are detected. Each time a key parameter is modified, the API calls a callback function which you have defined in advance.

Detecting module arrival and departure

Hot-plug management is important when you work with USB modules because, sooner or later, you will have to connect or disconnect a module when your application is running. The API is designed to manage module unexpected arrival or departure in a transparent way. But your application must take this into account if it wants to avoid pretending to use a disconnected module.

Event programming is particularly useful to detect module connection/disconnection. Indeed, it is simpler to be told of new connections rather than to have to permanently list the connected modules to deduce which ones just arrived and which ones left. To be warned as soon as a module is connected, you need three pieces of code.

The callback

The callback is the function which is called each time a new Yoctopuce module is connected. It takes as parameter the relevant module.


 static void deviceArrival(YModule m)
{
  Console.WriteLine("New module  : " + m.get_serialNumber());
}

Initialization

You must then tell the API that it must call the callback when a new module is connected.


YAPI.RegisterDeviceArrivalCallback(deviceArrival);

Note that if modules are already connected when the callback is registered, the callback is called for each of the already connected modules.

Triggering callbacks

A classis issue of callback programming is that these callbacks can be triggered at any time, including at times when the main program is not ready to receive them. This can have undesired side effects, such as dead-locks and other race conditions. Therefore, in the Yoctopuce API, module arrival/departure callbacks are called only when the UpdateDeviceList() function is running. You only need to call UpdateDeviceList() at regular intervals from a timer or from a specific thread to precisely control when the calls to these callbacks happen:


// waiting loop managing callbacks
while (true)
{
    // module arrival / departure callback
    YAPI.UpdateDeviceList(ref errmsg);
    // non active waiting time managing other callbacks
    YAPI.Sleep(500, ref errmsg);
}

In a similar way, it is possible to have a callback when a module is disconnected. You can find a complete example implemented in your favorite programming language in the Examples/Prog-EventBased directory of the corresponding library.

Be aware that in most programming languages, callbacks must be global procedures, and not methods. If you wish for the callback to call the method of an object, define your callback as a global procedure which then calls your method.

Detecting a modification in the value of a sensor

The Yoctopuce API also provides a callback system allowing you to be notified automatically with the value of any sensor, either when the value has changed in a significant way or periodically at a preset frequency. The code necessary to do so is rather similar to the code used to detect when a new module has been connected.

This technique is useful in particular if you want to detect very quick value changes (within a few milliseconds), as it is much more efficient than reading repeatedly the sensor value and therefore gives better performances.

Calliback invocation

To enable a better control, value change callbacks are only called when the YAPI.Sleep() and YAPI.HandleEvents() functions are running. Therefore, you must call one of these functions at a regular interval, either from a timer or from a parallel thread.


while (true)
{
  // inactive waiting loop allowing you to trigger
  // value change callbacks
  YAPI.Sleep(500, ref errmsg);
}

In programming environments where only the interface thread is allowed to interact with the user, it is often appropriate to call YAPI.HandleEvents() from this thread.

The value change callback

This type of callback is called when a magnetometer changes in a significant way. It takes as parameter the relevant function and the new value, as a character string. 60


static void valueChangeCallback(YMagnetometer fct, string value)
{
  Console.WriteLine(fct.get_hardwareId() + "=" + value);
}

In most programming languages, callbacks are global procedures, not methods. If you wish for the callback to call a method of an object, define your callback as a global procedure which then calls your method. If you need to keep a reference to your object, you can store it directly in the YMagnetometer object using function set_userData. You can then retrieve it in the global callback procedure using get_userData.

Setting up a value change callback

The callback is set up for a given Magnetometer function with the help of the registerValueCallback method. The following example sets up a callback for the first available Magnetometer function.


YMagnetometer f = YMagnetometer.FirstMagnetometer();
f.registerValueCallback(magnetometerChangeCallBack)

Note that each module function can thus have its own distinct callback. By the way, if you like to work with value change callbacks, you will appreciate the fact that value change callbacks are not limited to sensors, but are also available for all Yoctopuce devices (for instance, you can also receive a callback any time a relay state changes).

The timed report callback

This type of callback is automatically called at a predefined time interval. The callback frequency can be configured individually for each sensor, with frequencies going from hundred calls per seconds down to one call per hour. The callback takes as parameter the relevant function and the measured value, as an YMeasure object. Contrarily to the value change callback that only receives the latest value, an YMeasure object provides both minimal, maximal and average values since the timed report callback. Moreover, the measure includes precise timestamps, which makes it possible to use timed reports for a time-based graph even when not handled immediately.


static void periodicCallback(YMagnetometer fct, YMeasure measure)
{
  Console.WriteLine(fct.get_hardwareId() + "=" +
                    measure.get_averageValue());
}

Setting up a timed report callback

The callback is set up for a given Magnetometer function with the help of the registerTimedReportCallback method. The callback will only be invoked once a callback frequency as been set using set_reportFrequency (which defaults to timed report callback turned off). The frequency is specified as a string (same as for the data logger), by specifying the number of calls per second (/s), per minute (/m) or per hour (/h). The maximal frequency is 100 times per second (i.e. "100/s"), and the minimal frequency is 1 time per hour (i.e. "1/h"). When the frequency is higher than or equal to 1/s, the measure represents an instant value. When the frequency is below, the measure will include distinct minimal, maximal and average values based on a sampling performed automatically by the device.

The following example sets up a timed report callback 4 times per minute for t he first available Magnetometer function.


YMagnetometer f = YMagnetometer.FirstMagnetometer();
f.set_reportFrequency("4/m");
f.registerTimedReportCallback(periodicCallback);

As for value change callbacks, each module function can thus have its own distinct timed report callback.

Generic callback functions

It is sometimes desirable to use the same callback function for various types of sensors (e.g. for a generic sensor graphing application). This is possible by defining the callback for an object of class YSensor rather than YMagnetometer. Thus, the same callback function will be usable with any subclass of YSensor (and in particular with YMagnetometer). With the callback function, you can use the method get_unt() to get the physical unit of the sensor, if you need to display it.

A complete example

You can find a complete example implemented in your favorite programming language in the Examples/Prog-EventBased directory of the corresponding library.

23.2. The data logger

Your Yocto-3D-V2 is equipped with a data logger able to store non-stop the measures performed by the module. The maximal frequency is 100 times per second (i.e. "100/s"), and the minimal frequency is 1 time per hour (i.e. "1/h"). When the frequency is higher than or equal to 1/s, the measure represents an instant value. When the frequency is below, the measure will include distinct minimal, maximal and average values based on a sampling performed automatically by the device.

Note that is useless and counter-productive to set a recording frequency higher than the native sampling frequency of the recorded sensor.

The data logger flash memory can store about 500'000 instant measures, or 125'000 averaged measures. When the memory is about to be saturated, the oldest measures are automatically erased.

Make sure not to leave the data logger running at high speed unless really needed: the flash memory can only stand a limited number of erase cycles (typically 100'000 cycles). When running at full speed, the datalogger can burn more than 100 cycles per day ! Also be aware that it is useless to record measures at a frequency higher than the refresh frequency of the physical sensor itself.

Starting/stopping the datalogger

The data logger can be started with the set_recording() method.


YDataLogger l = YDataLogger.FirstDataLogger();
l.set_recording(YDataLogger.RECORDING_ON);

It is possible to make the data recording start automatically as soon as the module is powered on.


YDataLogger l = YDataLogger.FirstDataLogger();
l.set_autoStart(YDataLogger.AUTOSTART_ON);
l.get_module().saveToFlash();  // do not forget to save the setting

Note: Yoctopuce modules do not need an active USB connection to work: they start working as soon as they are powered on. The Yocto-3D-V2 can store data without necessarily being connected to a computer: you only need to activate the automatic start of the data logger and to power on the module with a simple USB charger.

Erasing the memory

The memory of the data logger can be erased with the forgetAllDataStreams() function. Be aware that erasing cannot be undone.


YDataLogger l = YDataLogger.FirstDataLogger();
l.forgetAllDataStreams();

Choosing the logging frequency

The logging frequency can be set up individually for each sensor, using the method set_logFrequency(). The frequency is specified as a string (same as for timed report callbacks), by specifying the number of calls per second (/s), per minute (/m) or per hour (/h). The default value is "1/s".

The following example configures the logging frequency at 15 measures per minute for the first sensor found, whatever its type:


YSensor sensor = YSensor.FirstSensor();
sensor.set_logFrequency("15/m");

To avoid wasting flash memory, it is possible to disable logging for specified functions. In order to do so, simply use the value "OFF":


sensor.set_logFrequency("OFF");

Limitation: The Yocto-3D-V2 cannot use a different frequency for timed-report callbacks and for recording data into the datalogger. You can disable either of them individually, but if you enable both timed-report callbacks and logging for a given function, the two will work at the same frequency.

Retrieving the data

To load recorded measures from the Yocto-3D-V2 flash memory, you must call the get_recordedData() method of the desired sensor, and specify the time interval for which you want to retrieve measures. The time interval is given by the start and stop UNIX timestamp. You can also specify 0 if you don't want any start or stop limit.

The get_recordedData() method does not return directly am array of measured values, since in some cases it would cause a huge load that could affect the responsiveness of the application. Instead, this function will return an YDataSet object that can be used to retrieve immediately an overview of the measured data (summary), and then to load progressively the details when desired.

Here are the main methods used to retrieve recorded measures:

  1. dataset = sensor.get_recordedData(0,0): select the desired time interval
  2. dataset.loadMore(): load data from the device, progressively
  3. dataset.get_summary(): get a single measure summarizing the full time interval
  4. dataset.get_preview(): get an array of measures representing a condensed version of the whole set of measures on the selected time interval (reduced by a factor of approx. 200)
  5. dataset.get_measures(): get an array with all detailled measures (that grows while loadMore is being called repeteadly)

Measures are instances of YMeasure 61. They store simultaneously the minimal, average and maximal value at a given time, that you can retrieve using methods get_minValue(), get_averageValue() and get_maxValue() respectively. Here is a small example that uses the functions above:


// We will retrieve all measures, without time limit
YDataSet dataset = sensor.get_recordedData(0, 0);

// First call to loadMore() loads the summary/preview
dataset.loadMore();
YMeasure summary = dataset.get_summary();
string timeFmt = "dd MMM yyyy hh:mm:ss,fff";
string logFmt = "from {0} to {1} : average={2:0.00}{3}";
Console.WriteLine(String.Format(logFmt,
    summary.get_startTimeUTC_asDateTime().ToString(timeFmt),
    summary.get_endTimeUTC_asDateTime().ToString(timeFmt),
    summary.get_averageValue(), sensor.get_unit()));

// Next calls to loadMore() will retrieve measures
Console.WriteLine("loading details");
int progress;
do {
    Console.Write(".");
    progress = dataset.loadMore();
} while(progress < 100);

// All measures have now been loaded
List<YMeasure> details = dataset.get_measures();
foreach (YMeasure m in details) {
    Console.WriteLine(String.Format(logFmt,
        m.get_startTimeUTC_asDateTime().ToString(timeFmt),
        m.get_endTimeUTC_asDateTime().ToString(timeFmt),
        m.get_averageValue(), sensor.get_unit()));
}

You will find a complete example demonstrating how to retrieve data from the logger for each programming language directly in the Yoctopuce library. The example can be found in directory Examples/Prog-DataLogger.

Timestamp

As the Yocto-3D-V2 does not have a battery, it cannot guess alone the current time when powered on. Nevertheless, the Yocto-3D-V2 will automatically try to adjust its real-time reference using the host to which it is connected, in order to properly attach a timestamp to each measure in the datalogger:

When none of these conditions applies (for instance if the module is simply connected to an USB charger), the Yocto-3D-V2 will do its best effort to attach a reasonable timestamp to the measures, using the timestamp found on the latest recorded measures. It is therefore possible to "preset to the real time" an autonomous Yocto-3D-V2 by connecting it to an Android mobile phone, starting the data logger, then connecting the device alone on an USB charger. Nevertheless, be aware that without external time source, the internal clock of the Yocto-3D-V2 might be be subject to a clock skew (theoretically up to 2%).

24. High-level API Reference

This chapter summarizes the high-level API functions to drive your Yocto-3D-V2. Syntax and exact type names may vary from one language to another, but, unless otherwise stated, all the functions are available in every language. For detailed information regarding the types of arguments and return values for a given language, refer to the definition file for this language (yocto_api.* as well as the other yocto_* files that define the function interfaces).

For languages which support exceptions, all of these functions throw exceptions in case of error by default, rather than returning the documented error value for each function. This is by design, to facilitate debugging. It is however possible to disable the use of exceptions using the yDisableExceptions() function, in case you prefer to work with functions that return error values.

This chapter does not repeat the programming concepts described earlier, in order to stay as concise as possible. In case of doubt, do not hesitate to go back to the chapter describing in details all configurable attributes.

24.1. Class YAPI

General functions

These general functions should be used to initialize and configure the Yoctopuce library. In most cases, a simple call to function yRegisterHub() should be enough. The module-specific functions yFind...() or yFirst...() should then be used to retrieve an object that provides interaction with the module.

In order to use the functions described here, you should include:

java
import com.yoctopuce.YoctoAPI.YAPI;
dnp
import YoctoProxyAPI.YAPIProxy
cp
#include "yocto_api_proxy.h"
ml
import YoctoProxyAPI.YAPIProxy"
js
<script type='text/javascript' src='yocto_api.js'></script>
cpp
#include "yocto_api.h"
m
#import "yocto_api.h"
pas
uses yocto_api;
vb
yocto_api.vb
cs
yocto_api.cs
uwp
import com.yoctopuce.YoctoAPI.YModule;
py
from yocto_api import *
php
require_once('yocto_api.php');
ts
in HTML: import { YAPI, YErrorMsg, YModule, YSensor } from '../../dist/esm/yocto_api_browser.js';
in Node.js: import { YAPI, YErrorMsg, YModule, YSensor } from 'yoctolib-cjs/yocto_api_nodejs.js';
es
in HTML: <script src="../../lib/yocto_api.js"></script>
in node.js: require('yoctolib-es2017/yocto_api.js');
vi
YModule.vi
Global functions
YAPI.CheckLogicalName(name)

Checks if a given string is valid as logical name for a module or a function.

YAPI.ClearHTTPCallbackCacheDir(bool_removeFiles)

Disables the HTTP callback cache.

YAPI.DisableExceptions()

Disables the use of exceptions to report runtime errors.

YAPI.EnableExceptions()

Re-enables the use of exceptions for runtime error handling.

YAPI.EnableUSBHost(osContext)

This function is used only on Android.

YAPI.FreeAPI()

Waits for all pending communications with Yoctopuce devices to be completed then frees dynamically allocated resources used by the Yoctopuce library.

YAPI.GetAPIVersion()

Returns the version identifier for the Yoctopuce library in use.

YAPI.GetCacheValidity()

Returns the validity period of the data loaded by the library.

YAPI.GetDeviceListValidity()

Returns the delay between each forced enumeration of the used YoctoHubs.

YAPI.GetDllArchitecture()

Returns the system architecture for the Yoctopuce communication library in use.

YAPI.GetDllPath()

Returns the paths of the DLLs for the Yoctopuce library in use.

YAPI.GetLog(lastLogLine)

Retrieves Yoctopuce low-level library diagnostic logs.

YAPI.GetNetworkTimeout()

Returns the network connection delay for yRegisterHub() and yUpdateDeviceList().

YAPI.GetTickCount()

Returns the current value of a monotone millisecond-based time counter.

YAPI.HandleEvents(errmsg)

Maintains the device-to-library communication channel.

YAPI.InitAPI(mode, errmsg)

Initializes the Yoctopuce programming library explicitly.

YAPI.PreregisterHub(url, errmsg)

Fault-tolerant alternative to yRegisterHub().

YAPI.RegisterDeviceArrivalCallback(arrivalCallback)

Register a callback function, to be called each time a device is plugged.

YAPI.RegisterDeviceRemovalCallback(removalCallback)

Register a callback function, to be called each time a device is unplugged.

YAPI.RegisterHub(url, errmsg)

Setup the Yoctopuce library to use modules connected on a given machine.

YAPI.RegisterHubDiscoveryCallback(hubDiscoveryCallback)

Register a callback function, to be called each time an Network Hub send an SSDP message.

YAPI.RegisterHubWebsocketCallback(ws, errmsg, authpwd)

Variant to yRegisterHub() used to initialize Yoctopuce API on an existing Websocket session, as happens for incoming WebSocket callbacks.

YAPI.RegisterLogFunction(logfun)

Registers a log callback function.

YAPI.SelectArchitecture(arch)

Select the architecture or the library to be loaded to access to USB.

YAPI.SetCacheValidity(cacheValidityMs)

Change the validity period of the data loaded by the library.

YAPI.SetDelegate(object)

(Objective-C only) Register an object that must follow the protocol YDeviceHotPlug.

YAPI.SetDeviceListValidity(deviceListValidity)

Modifies the delay between each forced enumeration of the used YoctoHubs.

YAPI.SetHTTPCallbackCacheDir(str_directory)

Enables the HTTP callback cache.

YAPI.SetNetworkTimeout(networkMsTimeout)

Modifies the network connection delay for yRegisterHub() and yUpdateDeviceList().

YAPI.SetTimeout(callback, ms_timeout, args)

Invoke the specified callback function after a given timeout.

YAPI.SetUSBPacketAckMs(pktAckDelay)

Enables the acknowledge of every USB packet received by the Yoctopuce library.

YAPI.Sleep(ms_duration, errmsg)

Pauses the execution flow for a specified duration.

YAPI.TestHub(url, mstimeout, errmsg)

Test if the hub is reachable.

YAPI.TriggerHubDiscovery(errmsg)

Force a hub discovery, if a callback as been registered with yRegisterHubDiscoveryCallback it will be called for each net work hub that will respond to the discovery.

YAPI.UnregisterHub(url)

Setup the Yoctopuce library to no more use modules connected on a previously registered machine with RegisterHub.

YAPI.UpdateDeviceList(errmsg)

Triggers a (re)detection of connected Yoctopuce modules.

YAPI.UpdateDeviceList_async(callback, context)

Triggers a (re)detection of connected Yoctopuce modules.

YAPI.CheckLogicalName()
YAPI.CheckLogicalName()
yCheckLogicalName()YAPI::CheckLogicalName()[YAPI CheckLogicalName: ]yCheckLogicalName()YAPI.CheckLogicalName()YAPI.CheckLogicalName()YAPI.CheckLogicalName()YAPI.CheckLogicalName()YAPI.CheckLogicalName()YAPI::CheckLogicalName()YAPI.CheckLogicalName()YAPI.CheckLogicalName()

Checks if a given string is valid as logical name for a module or a function.

js
function yCheckLogicalName(name)
cpp
bool CheckLogicalName(string name)
m
+(BOOL) CheckLogicalName:(NSString *) name
pas
boolean yCheckLogicalName(name: string): boolean
vb
function CheckLogicalName(ByVal name As String) As Boolean
cs
static bool CheckLogicalName(string name)
java
boolean CheckLogicalName(String name)
uwp
bool CheckLogicalName(string name)
py
CheckLogicalName(name)
php
function CheckLogicalName($name)
ts
async CheckLogicalName(name: string): Promise<boolean>
es
async CheckLogicalName(name)

A valid logical name has a maximum of 19 characters, all among A..Z, a..z, 0..9, _, and -. If you try to configure a logical name with an incorrect string, the invalid characters are ignored.

Parameters :

namea string containing the name to check.

Returns :

true if the name is valid, false otherwise.

YAPI.ClearHTTPCallbackCacheDir()
YAPI.ClearHTTPCallbackCacheDir()
YAPI::ClearHTTPCallbackCacheDir()

Disables the HTTP callback cache.

php
function ClearHTTPCallbackCacheDir($bool_removeFiles)

This method disables the HTTP callback cache, and can additionally cleanup the cache directory.

Parameters :

bool_removeFilesTrue to clear the content of the cache.

Returns :

nothing.

YAPI.DisableExceptions()
YAPI.DisableExceptions()
yDisableExceptions()YAPI::DisableExceptions()[YAPI DisableExceptions]yDisableExceptions()YAPI.DisableExceptions()YAPI.DisableExceptions()YAPI.DisableExceptions()YAPI.DisableExceptions()YAPI::DisableExceptions()YAPI.DisableExceptions()YAPI.DisableExceptions()

Disables the use of exceptions to report runtime errors.

js
function yDisableExceptions()
cpp
void DisableExceptions()
m
+(void) DisableExceptions
pas
yDisableExceptions()
vb
procedure DisableExceptions()
cs
static void DisableExceptions()
uwp
void DisableExceptions()
py
DisableExceptions()
php
function DisableExceptions()
ts
async DisableExceptions(): Promise<void>
es
async DisableExceptions()

When exceptions are disabled, every function returns a specific error value which depends on its type and which is documented in this reference manual.

YAPI.EnableExceptions()
YAPI.EnableExceptions()
yEnableExceptions()YAPI::EnableExceptions()[YAPI EnableExceptions]yEnableExceptions()YAPI.EnableExceptions()YAPI.EnableExceptions()YAPI.EnableExceptions()YAPI.EnableExceptions()YAPI::EnableExceptions()YAPI.EnableExceptions()YAPI.EnableExceptions()

Re-enables the use of exceptions for runtime error handling.

js
function yEnableExceptions()
cpp
void EnableExceptions()
m
+(void) EnableExceptions
pas
yEnableExceptions()
vb
procedure EnableExceptions()
cs
static void EnableExceptions()
uwp
void EnableExceptions()
py
EnableExceptions()
php
function EnableExceptions()
ts
async EnableExceptions(): Promise<void>
es
async EnableExceptions()

Be aware than when exceptions are enabled, every function that fails triggers an exception. If the exception is not caught by the user code, it either fires the debugger or aborts (i.e. crash) the program. On failure, throws an exception or returns a negative error code.

YAPI.EnableUSBHost()
YAPI.EnableUSBHost()
YAPI.EnableUSBHost()

This function is used only on Android.

java
void EnableUSBHost(Object osContext)

Before calling yRegisterHub("usb") you need to activate the USB host port of the system. This function takes as argument, an object of class android.content.Context (or any subclass). It is not necessary to call this function to reach modules through the network.

Parameters :

On failure, throws an exception.
osContextan object of class android.content.Context (or any subclass).

YAPI.FreeAPI()
YAPI.FreeAPI()
yFreeAPI()YAPI::FreeAPI()[YAPI FreeAPI]yFreeAPI()YAPI.FreeAPI()YAPI.FreeAPI()YAPI.FreeAPI()YAPI.FreeAPI()YAPI.FreeAPI()YAPI::FreeAPI()YAPI.FreeAPI()YAPI.FreeAPI()YAPI.FreeAPI()YAPI.FreeAPI()

Waits for all pending communications with Yoctopuce devices to be completed then frees dynamically allocated resources used by the Yoctopuce library.

js
function yFreeAPI()
cpp
void FreeAPI()
m
+(void) FreeAPI
pas
yFreeAPI()
vb
procedure FreeAPI()
cs
static void FreeAPI()
java
void FreeAPI()
uwp
void FreeAPI()
py
FreeAPI()
php
function FreeAPI()
ts
async FreeAPI(): Promise<void>
es
async FreeAPI()
dnp
static void FreeAPI()
cp
static void FreeAPI()

From an operating system standpoint, it is generally not required to call this function since the OS will automatically free allocated resources once your program is completed. However there are two situations when you may really want to use that function: - Free all dynamically allocated memory blocks in order to track a memory leak. - Send commands to devices right before the end of the program. Since commands are sent in an asynchronous way the program could exit before all commands are effectively sent. You should not call any other library function after calling yFreeAPI(), or your program will crash.

YAPI.GetAPIVersion()
YAPI.GetAPIVersion()
yGetAPIVersion()YAPI::GetAPIVersion()[YAPI GetAPIVersion]yGetAPIVersion()YAPI.GetAPIVersion()YAPI.GetAPIVersion()YAPI.GetAPIVersion()YAPI.GetAPIVersion()YAPI.GetAPIVersion()YAPI::GetAPIVersion()YAPI.GetAPIVersion()YAPI.GetAPIVersion()YAPI.GetAPIVersion()YAPI.GetAPIVersion()

Returns the version identifier for the Yoctopuce library in use.

js
function yGetAPIVersion()
cpp
string GetAPIVersion()
m
+(NSString*) GetAPIVersion
pas
string yGetAPIVersion(): string
vb
function GetAPIVersion() As String
cs
static String GetAPIVersion()
java
static String GetAPIVersion()
uwp
static string GetAPIVersion()
py
GetAPIVersion()
php
function GetAPIVersion()
ts
async GetAPIVersion()
es
async GetAPIVersion()
dnp
static string GetAPIVersion()
cp
static string GetAPIVersion()

The version is a string in the form "Major.Minor.Build", for instance "1.01.5535". For languages using an external DLL (for instance C#, VisualBasic or Delphi), the character string includes as well the DLL version, for instance "1.01.5535 (1.01.5439)".

If you want to verify in your code that the library version is compatible with the version that you have used during development, verify that the major number is strictly equal and that the minor number is greater or equal. The build number is not relevant with respect to the library compatibility.

Returns :

a character string describing the library version.

YAPI.GetCacheValidity()
YAPI.GetCacheValidity()
YAPI::GetCacheValidity()[YAPI GetCacheValidity]yGetCacheValidity()YAPI.GetCacheValidity()YAPI.GetCacheValidity()YAPI.GetCacheValidity()YAPI.GetCacheValidity()YAPI.GetCacheValidity()YAPI::GetCacheValidity()YAPI.GetCacheValidity()YAPI.GetCacheValidity()

Returns the validity period of the data loaded by the library.

cpp
static u64 GetCacheValidity()
m
+(u64) GetCacheValidity
pas
u64 yGetCacheValidity(): u64
vb
function GetCacheValidity() As Long
cs
ulong GetCacheValidity()
java
long GetCacheValidity()
uwp
async Task<ulong> GetCacheValidity()
py
GetCacheValidity()
php
function GetCacheValidity()
ts
async GetCacheValidity(): Promise<number>
es
async GetCacheValidity()

This method returns the cache validity of all attributes module functions. Note: This function must be called after yInitAPI .

Returns :

an integer corresponding to the validity attributed to the loaded function parameters, in milliseconds

YAPI.GetDeviceListValidity()
YAPI.GetDeviceListValidity()
YAPI::GetDeviceListValidity()[YAPI GetDeviceListValidity]yGetDeviceListValidity()YAPI.GetDeviceListValidity()YAPI.GetDeviceListValidity()YAPI.GetDeviceListValidity()YAPI.GetDeviceListValidity()YAPI.GetDeviceListValidity()YAPI::GetDeviceListValidity()YAPI.GetDeviceListValidity()YAPI.GetDeviceListValidity()

Returns the delay between each forced enumeration of the used YoctoHubs.

cpp
static int GetDeviceListValidity()
m
+(int) GetDeviceListValidity
pas
LongInt yGetDeviceListValidity(): LongInt
vb
function GetDeviceListValidity() As Integer
cs
int GetDeviceListValidity()
java
int GetDeviceListValidity()
uwp
async Task<int> GetDeviceListValidity()
py
GetDeviceListValidity()
php
function GetDeviceListValidity()
ts
async GetDeviceListValidity(): Promise<number>
es
async GetDeviceListValidity()

Note: you must call this function after yInitAPI.

Returns :

the number of seconds between each enumeration.

YAPI.GetDllArchitecture()
YAPI.GetDllArchitecture()
YAPI.GetDllArchitecture()

Returns the system architecture for the Yoctopuce communication library in use.

dnp
static string GetDllArchitecture()

On Windows, the architecture can be "Win32" or "Win64". On ARM machines, the architecture is "Armhf32" or "Aarch64". On other Linux machines, the architecture is "Linux32" or "Linux64". On MacOS, the architecture is "MacOs32" or "MacOs64".

Returns :

a character string describing the system architecture of the low-level communication library.

YAPI.GetDllPath()
YAPI.GetDllPath()
YAPI.GetDllPath()

Returns the paths of the DLLs for the Yoctopuce library in use.

dnp
static string GetDllPath()

For architectures that require multiple DLLs, in particular when using a .NET assembly DLL, the returned string takes the form "DotNetProxy=/...; yapi=/...;", where the first path corresponds to the .NET assembly DLL and the second path corresponds to the low-level communication library.

Returns :

a character string describing the DLL path.

YAPI.GetLog()
YAPI.GetLog()
YAPI.GetLog()YAPI.GetLog()

Retrieves Yoctopuce low-level library diagnostic logs.

dnp
static string GetLog(string lastLogLine)
cp
static string GetLog(string lastLogLine)

This method allows to progessively retrieve API logs. The interface is line-based: it must called it within a loop until the returned value is an empty string. Make sure to exit the loop when an empty string is returned, as feeding an empty string into the lastLogLine parameter for the next call would restart enumerating logs from the oldest message available.

Parameters :

lastLogLineOn first call, provide an empty string. On subsequent calls, provide the last log line returned by GetLog().

Returns :

a string with the log line immediately following the one given in argument, if such line exist. Returns an empty string otherwise, when completed.

YAPI.GetNetworkTimeout()
YAPI.GetNetworkTimeout()
YAPI::GetNetworkTimeout()[YAPI GetNetworkTimeout]yGetNetworkTimeout()YAPI.GetNetworkTimeout()YAPI.GetNetworkTimeout()YAPI.GetNetworkTimeout()YAPI.GetNetworkTimeout()YAPI.GetNetworkTimeout()YAPI::GetNetworkTimeout()YAPI.GetNetworkTimeout()YAPI.GetNetworkTimeout()YAPI.GetNetworkTimeout()YAPI.GetNetworkTimeout()

Returns the network connection delay for yRegisterHub() and yUpdateDeviceList().

cpp
static int GetNetworkTimeout()
m
+(int) GetNetworkTimeout
pas
LongInt yGetNetworkTimeout(): LongInt
vb
function GetNetworkTimeout() As Integer
cs
int GetNetworkTimeout()
java
int GetNetworkTimeout()
uwp
async Task<int> GetNetworkTimeout()
py
GetNetworkTimeout()
php
function GetNetworkTimeout()
ts
async GetNetworkTimeout(): Promise<number>
es
async GetNetworkTimeout()
dnp
static int GetNetworkTimeout()
cp
static int GetNetworkTimeout()

This delay impacts only the YoctoHubs and VirtualHub which are accessible through the network. By default, this delay is of 20000 milliseconds, but depending or you network you may want to change this delay, for example if your network infrastructure is based on a GSM connection.

Returns :

the network connection delay in milliseconds.

YAPI.GetTickCount()
YAPI.GetTickCount()
yGetTickCount()YAPI::GetTickCount()[YAPI GetTickCount]yGetTickCount()YAPI.GetTickCount()YAPI.GetTickCount()YAPI.GetTickCount()YAPI.GetTickCount()YAPI.GetTickCount()YAPI::GetTickCount()YAPI.GetTickCount()YAPI.GetTickCount()

Returns the current value of a monotone millisecond-based time counter.

js
function yGetTickCount()
cpp
u64 GetTickCount()
m
+(u64) GetTickCount
pas
u64 yGetTickCount(): u64
vb
function GetTickCount() As Long
cs
static ulong GetTickCount()
java
static long GetTickCount()
uwp
static ulong GetTickCount()
py
GetTickCount()
php
function GetTickCount()
ts
GetTickCount(): number
es
GetTickCount()

This counter can be used to compute delays in relation with Yoctopuce devices, which also uses the millisecond as timebase.

Returns :

a long integer corresponding to the millisecond counter.

YAPI.HandleEvents()
YAPI.HandleEvents()
yHandleEvents()YAPI::HandleEvents()[YAPI HandleEvents: ]yHandleEvents()YAPI.HandleEvents()YAPI.HandleEvents()YAPI.HandleEvents()YAPI.HandleEvents()YAPI.HandleEvents()YAPI::HandleEvents()YAPI.HandleEvents()YAPI.HandleEvents()

Maintains the device-to-library communication channel.

js
function yHandleEvents(errmsg)
cpp
YRETCODE HandleEvents(string errmsg)
m
+(YRETCODE) HandleEvents:(NSError**) errmsg
pas
integer yHandleEvents(var errmsg: string): integer
vb
function HandleEvents(ByRef errmsg As String) As YRETCODE
cs
static YRETCODE HandleEvents(ref string errmsg)
java
int HandleEvents()
uwp
async Task<int> HandleEvents()
py
HandleEvents(errmsg=None)
php
function HandleEvents(&$errmsg)
ts
async HandleEvents(errmsg: YErrorMsg | null): Promise<number>
es
async HandleEvents(errmsg)

If your program includes significant loops, you may want to include a call to this function to make sure that the library takes care of the information pushed by the modules on the communication channels. This is not strictly necessary, but it may improve the reactivity of the library for the following commands.

This function may signal an error in case there is a communication problem while contacting a module.

Parameters :

errmsga string passed by reference to receive any error message.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

YAPI.InitAPI()
YAPI.InitAPI()
yInitAPI()YAPI::InitAPI()[YAPI InitAPI: ]yInitAPI()YAPI.InitAPI()YAPI.InitAPI()YAPI.InitAPI()YAPI.InitAPI()YAPI.InitAPI()YAPI::InitAPI()YAPI.InitAPI()YAPI.InitAPI()

Initializes the Yoctopuce programming library explicitly.

js
function yInitAPI(mode, errmsg)
cpp
YRETCODE InitAPI(int mode, string errmsg)
m
+(YRETCODE) InitAPI:(int) mode :(NSError**) errmsg
pas
integer yInitAPI(mode: integer, var errmsg: string): integer
vb
function InitAPI(ByVal mode As Integer, ByRef errmsg As String) As Integer
cs
static int InitAPI(int mode, ref string errmsg)
java
int InitAPI(int mode)
uwp
async Task<int> InitAPI(int mode)
py
InitAPI(mode, errmsg=None)
php
function InitAPI($mode, &$errmsg)
ts
async InitAPI(mode: number, errmsg: YErrorMsg): Promise<number>
es
async InitAPI(mode, errmsg)

It is not strictly needed to call yInitAPI(), as the library is automatically initialized when calling yRegisterHub() for the first time.

When YAPI.DETECT_NONE is used as detection mode, you must explicitly use yRegisterHub() to point the API to the VirtualHub on which your devices are connected before trying to access them.

Parameters :

modean integer corresponding to the type of automatic device detection to use. Possible values are YAPI.DETECT_NONE, YAPI.DETECT_USB, YAPI.DETECT_NET, and YAPI.DETECT_ALL.
errmsga string passed by reference to receive any error message.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

YAPI.PreregisterHub()
YAPI.PreregisterHub()
yPreregisterHub()YAPI::PreregisterHub()[YAPI PreregisterHub: ]yPreregisterHub()YAPI.PreregisterHub()YAPI.PreregisterHub()YAPI.PreregisterHub()YAPI.PreregisterHub()YAPI.PreregisterHub()YAPI::PreregisterHub()YAPI.PreregisterHub()YAPI.PreregisterHub()YAPI.PreregisterHub()YAPI.PreregisterHub()

Fault-tolerant alternative to yRegisterHub().

js
function yPreregisterHub(url, errmsg)
cpp
YRETCODE PreregisterHub(string url, string errmsg)
m
+(YRETCODE) PreregisterHub:(NSString *) url :(NSError**) errmsg
pas
integer yPreregisterHub(url: string, var errmsg: string): integer
vb
function PreregisterHub(ByVal url As String,
  ByRef errmsg As String) As Integer
cs
static int PreregisterHub(string url, ref string errmsg)
java
int PreregisterHub(String url)
uwp
async Task<int> PreregisterHub(string url)
py
PreregisterHub(url, errmsg=None)
php
function PreregisterHub($url, &$errmsg)
ts
async PreregisterHub(url: string, errmsg: YErrorMsg): Promise<number>
es
async PreregisterHub(url, errmsg)
dnp
static string PreregisterHub(string url)
cp
static string PreregisterHub(string url)

This function has the same purpose and same arguments as yRegisterHub(), but does not trigger an error when the selected hub is not available at the time of the function call. This makes it possible to register a network hub independently of the current connectivity, and to try to contact it only when a device is actively needed.

Parameters :

urla string containing either "usb","callback" or the root URL of the hub to monitor
errmsga string passed by reference to receive any error message.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

YAPI.RegisterDeviceArrivalCallback()
YAPI.RegisterDeviceArrivalCallback()
yRegisterDeviceArrivalCallback()YAPI::RegisterDeviceArrivalCallback()[YAPI RegisterDeviceArrivalCallback: ]yRegisterDeviceArrivalCallback()YAPI.RegisterDeviceArrivalCallback()YAPI.RegisterDeviceArrivalCallback()YAPI.RegisterDeviceArrivalCallback()YAPI.RegisterDeviceArrivalCallback()YAPI.RegisterDeviceArrivalCallback()YAPI::RegisterDeviceArrivalCallback()YAPI.RegisterDeviceArrivalCallback()YAPI.RegisterDeviceArrivalCallback()

Register a callback function, to be called each time a device is plugged.

js
function yRegisterDeviceArrivalCallback(arrivalCallback)
cpp
void RegisterDeviceArrivalCallback(yDeviceUpdateCallback arrivalCallback)
m
+(void) RegisterDeviceArrivalCallback:(yDeviceUpdateCallback) arrivalCallback
pas
yRegisterDeviceArrivalCallback(arrivalCallback: yDeviceUpdateFunc)
vb
procedure RegisterDeviceArrivalCallback(ByVal arrivalCallback As yDeviceUpdateFunc)
cs
static void RegisterDeviceArrivalCallback(yDeviceUpdateFunc arrivalCallback)
java
void RegisterDeviceArrivalCallback(DeviceArrivalCallback arrivalCallback)
uwp
void RegisterDeviceArrivalCallback(DeviceUpdateHandler arrivalCallback)
py
RegisterDeviceArrivalCallback(arrivalCallback)
php
function RegisterDeviceArrivalCallback($arrivalCallback)
ts
async RegisterDeviceArrivalCallback(arrivalCallback: YDeviceUpdateCallback| null): Promise<void>
es
async RegisterDeviceArrivalCallback(arrivalCallback)

This callback will be invoked while yUpdateDeviceList is running. You will have to call this function on a regular basis.

Parameters :

to unregister a previously registered callback.
arrivalCallbacka procedure taking a YModule parameter, or null

YAPI.RegisterDeviceRemovalCallback()
YAPI.RegisterDeviceRemovalCallback()
yRegisterDeviceRemovalCallback()YAPI::RegisterDeviceRemovalCallback()[YAPI RegisterDeviceRemovalCallback: ]yRegisterDeviceRemovalCallback()YAPI.RegisterDeviceRemovalCallback()YAPI.RegisterDeviceRemovalCallback()YAPI.RegisterDeviceRemovalCallback()YAPI.RegisterDeviceRemovalCallback()YAPI.RegisterDeviceRemovalCallback()YAPI::RegisterDeviceRemovalCallback()YAPI.RegisterDeviceRemovalCallback()YAPI.RegisterDeviceRemovalCallback()

Register a callback function, to be called each time a device is unplugged.

js
function yRegisterDeviceRemovalCallback(removalCallback)
cpp
void RegisterDeviceRemovalCallback(yDeviceUpdateCallback removalCallback)
m
+(void) RegisterDeviceRemovalCallback:(yDeviceUpdateCallback) removalCallback
pas
yRegisterDeviceRemovalCallback(removalCallback: yDeviceUpdateFunc)
vb
procedure RegisterDeviceRemovalCallback(ByVal removalCallback As yDeviceUpdateFunc)
cs
static void RegisterDeviceRemovalCallback(yDeviceUpdateFunc removalCallback)
java
void RegisterDeviceRemovalCallback(DeviceRemovalCallback removalCallback)
uwp
void RegisterDeviceRemovalCallback(DeviceUpdateHandler removalCallback)
py
RegisterDeviceRemovalCallback(removalCallback)
php
function RegisterDeviceRemovalCallback($removalCallback)
ts
async RegisterDeviceRemovalCallback(removalCallback: YDeviceUpdateCallback| null): Promise<void>
es
async RegisterDeviceRemovalCallback(removalCallback)

This callback will be invoked while yUpdateDeviceList is running. You will have to call this function on a regular basis.

Parameters :

to unregister a previously registered callback.
removalCallbacka procedure taking a YModule parameter, or null

YAPI.RegisterHub()
YAPI.RegisterHub()
yRegisterHub()YAPI::RegisterHub()[YAPI RegisterHub: ]yRegisterHub()YAPI.RegisterHub()YAPI.RegisterHub()YAPI.RegisterHub()YAPI.RegisterHub()YAPI.RegisterHub()YAPI::RegisterHub()YAPI.RegisterHub()YAPI.RegisterHub()YAPI.RegisterHub()YAPI.RegisterHub()

Setup the Yoctopuce library to use modules connected on a given machine.

js
function yRegisterHub(url, errmsg)
cpp
YRETCODE RegisterHub(string url, string errmsg)
m
+(YRETCODE) RegisterHub:(NSString *) url :(NSError**) errmsg
pas
integer yRegisterHub(url: string, var errmsg: string): integer
vb
function RegisterHub(ByVal url As String,
  ByRef errmsg As String) As Integer
cs
static int RegisterHub(string url, ref string errmsg)
java
int RegisterHub(String url)
uwp
async Task<int> RegisterHub(string url)
py
RegisterHub(url, errmsg=None)
php
function RegisterHub($url, &$errmsg)
ts
async RegisterHub(url: string, errmsg: YErrorMsg): Promise<number>
es
async RegisterHub(url, errmsg)
dnp
static string RegisterHub(string url)
cp
static string RegisterHub(string url)

The parameter will determine how the API will work. Use the following values:

usb: When the usb keyword is used, the API will work with devices connected directly to the USB bus. Some programming languages such a JavaScript, PHP, and Java don't provide direct access to USB hardware, so usb will not work with these. In this case, use a VirtualHub or a networked YoctoHub (see below).

x.x.x.x or hostname: The API will use the devices connected to the host with the given IP address or hostname. That host can be a regular computer running a VirtualHub, or a networked YoctoHub such as YoctoHub-Ethernet or YoctoHub-Wireless. If you want to use the VirtualHub running on you local computer, use the IP address 127.0.0.1.

callback: that keyword make the API run in "HTTP Callback" mode. This a special mode allowing to take control of Yoctopuce devices through a NAT filter when using a VirtualHub or a networked YoctoHub. You only need to configure your hub to call your server script on a regular basis. This mode is currently available for PHP and Node.JS only.

Be aware that only one application can use direct USB access at a given time on a machine. Multiple access would cause conflicts while trying to access the USB modules. In particular, this means that you must stop the VirtualHub software before starting an application that uses direct USB access. The workaround for this limitation is to setup the library to use the VirtualHub rather than direct USB access.

If access control has been activated on the hub, virtual or not, you want to reach, the URL parameter should look like:

http://username:password@address:port

You can call RegisterHub several times to connect to several machines.

Parameters :

urla string containing either "usb","callback" or the root URL of the hub to monitor
errmsga string passed by reference to receive any error message.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

YAPI.RegisterHubDiscoveryCallback()
YAPI.RegisterHubDiscoveryCallback()
YAPI::RegisterHubDiscoveryCallback()[YAPI RegisterHubDiscoveryCallback: ]yRegisterHubDiscoveryCallback()YAPI.RegisterHubDiscoveryCallback()YAPI.RegisterHubDiscoveryCallback()YAPI.RegisterHubDiscoveryCallback()YAPI.RegisterHubDiscoveryCallback()YAPI.RegisterHubDiscoveryCallback()YAPI.RegisterHubDiscoveryCallback()YAPI.RegisterHubDiscoveryCallback()

Register a callback function, to be called each time an Network Hub send an SSDP message.

cpp
void RegisterHubDiscoveryCallback(YHubDiscoveryCallback hubDiscoveryCallback)
m
+(void) RegisterHubDiscoveryCallback: (YHubDiscoveryCallback) hubDiscoveryCallback
pas
yRegisterHubDiscoveryCallback(hubDiscoveryCallback: YHubDiscoveryCallback)
vb
procedure RegisterHubDiscoveryCallback(ByVal hubDiscoveryCallback As YHubDiscoveryCallback)
cs
static void RegisterHubDiscoveryCallback(YHubDiscoveryCallback hubDiscoveryCallback)
java
void RegisterHubDiscoveryCallback(HubDiscoveryCallback hubDiscoveryCallback)
uwp
async Task RegisterHubDiscoveryCallback(HubDiscoveryHandler hubDiscoveryCallback)
py
RegisterHubDiscoveryCallback(hubDiscoveryCallback)
ts
async RegisterHubDiscoveryCallback(hubDiscoveryCallback: YHubDiscoveryCallback): Promise<number>
es
async RegisterHubDiscoveryCallback(hubDiscoveryCallback)

The callback has two string parameter, the first one contain the serial number of the hub and the second contain the URL of the network hub (this URL can be passed to RegisterHub). This callback will be invoked while yUpdateDeviceList is running. You will have to call this function on a regular basis.

Parameters :

number and the hub URL. Use null to unregister a previously registered callback.
hubDiscoveryCallbacka procedure taking two string parameter, the serial

YAPI.RegisterHubWebsocketCallback()
YAPI.RegisterHubWebsocketCallback()

Variant to yRegisterHub() used to initialize Yoctopuce API on an existing Websocket session, as happens for incoming WebSocket callbacks.

Parameters :

wsnode WebSocket object for the incoming WebSocket callback connection
errmsga string passed by reference to receive any error message.
authpwdthe optional authentication password, required only authentication is configured on the calling hub.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

YAPI.RegisterLogFunction()
YAPI.RegisterLogFunction()
YAPI::RegisterLogFunction()[YAPI RegisterLogFunction: ]yRegisterLogFunction()YAPI.RegisterLogFunction()YAPI.RegisterLogFunction()YAPI.RegisterLogFunction()YAPI.RegisterLogFunction()YAPI.RegisterLogFunction()YAPI.RegisterLogFunction()YAPI.RegisterLogFunction()

Registers a log callback function.

cpp
void RegisterLogFunction(yLogFunction logfun)
m
+(void) RegisterLogFunction:(yLogCallback) logfun
pas
yRegisterLogFunction(logfun: yLogFunc)
vb
procedure RegisterLogFunction(ByVal logfun As yLogFunc)
cs
static void RegisterLogFunction(yLogFunc logfun)
java
void RegisterLogFunction(LogCallback logfun)
uwp
void RegisterLogFunction(LogHandler logfun)
py
RegisterLogFunction(logfun)
ts
async RegisterLogFunction(logfun: YLogCallback): Promise<number>
es
async RegisterLogFunction(logfun)

This callback will be called each time the API have something to say. Quite useful to debug the API.

Parameters :

to unregister a previously registered callback.
logfuna procedure taking a string parameter, or null

YAPI.SelectArchitecture()
YAPI.SelectArchitecture()
YAPI.SelectArchitecture()

Select the architecture or the library to be loaded to access to USB.

py
SelectArchitecture(arch)

By default, the Python library automatically detects the appropriate library to use. However, for Linux ARM, it not possible to reliably distinguish between a Hard Float (armhf) and a Soft Float (armel) install. For in this case, it is therefore recommended to manually select the proper architecture by calling SelectArchitecture() before any other call to the library.

Parameters :

archA string containing the architecture to use. Possibles value are: "armhf","armel", "aarch64","i386","x86_64", "32bit", "64bit"

Returns :

nothing.

On failure, throws an exception.

YAPI.SetCacheValidity()
YAPI.SetCacheValidity()
YAPI::SetCacheValidity()[YAPI SetCacheValidity: ]ySetCacheValidity()YAPI.SetCacheValidity()YAPI.SetCacheValidity()YAPI.SetCacheValidity()YAPI.SetCacheValidity()YAPI.SetCacheValidity()YAPI::SetCacheValidity()YAPI.SetCacheValidity()YAPI.SetCacheValidity()

Change the validity period of the data loaded by the library.

cpp
static void SetCacheValidity(u64 cacheValidityMs)
m
+(void) SetCacheValidity: (u64) cacheValidityMs
pas
ySetCacheValidity(cacheValidityMs: u64)
vb
procedure SetCacheValidity(ByVal cacheValidityMs As Long)
cs
void SetCacheValidity(ulong cacheValidityMs)
java
void SetCacheValidity(long cacheValidityMs)
uwp
async Task SetCacheValidity(ulong cacheValidityMs)
py
SetCacheValidity(cacheValidityMs)
php
function SetCacheValidity($cacheValidityMs)
ts
async SetCacheValidity(cacheValidityMs: number): Promise<void>
es
async SetCacheValidity(cacheValidityMs)

By default, when accessing a module, all the attributes of the module functions are automatically kept in cache for the standard duration (5 ms). This method can be used to change this standard duration, for example in order to reduce network or USB traffic. This parameter does not affect value change callbacks Note: This function must be called after yInitAPI.

Parameters :

cacheValidityMsan integer corresponding to the validity attributed to the loaded function parameters, in milliseconds.

YAPI.SetDelegate()
YAPI.SetDelegate()
[YAPI SetDelegate: ]

(Objective-C only) Register an object that must follow the protocol YDeviceHotPlug.

m
+(void) SetDelegate:(id) object

The methods yDeviceArrival and yDeviceRemoval will be invoked while yUpdateDeviceList is running. You will have to call this function on a regular basis.

Parameters :

to unregister a previously registered object.
objectan object that must follow the protocol YAPIDelegate, or nil

YAPI.SetDeviceListValidity()
YAPI.SetDeviceListValidity()
YAPI::SetDeviceListValidity()[YAPI SetDeviceListValidity: ]ySetDeviceListValidity()YAPI.SetDeviceListValidity()YAPI.SetDeviceListValidity()YAPI.SetDeviceListValidity()YAPI.SetDeviceListValidity()YAPI.SetDeviceListValidity()YAPI::SetDeviceListValidity()YAPI.SetDeviceListValidity()YAPI.SetDeviceListValidity()

Modifies the delay between each forced enumeration of the used YoctoHubs.

cpp
static void SetDeviceListValidity(int deviceListValidity)
m
+(void) SetDeviceListValidity: (int) deviceListValidity
pas
ySetDeviceListValidity(deviceListValidity: LongInt)
vb
procedure SetDeviceListValidity(ByVal deviceListValidity As Integer)
cs
void SetDeviceListValidity(int deviceListValidity)
java
void SetDeviceListValidity(int deviceListValidity)
uwp
async Task SetDeviceListValidity(int deviceListValidity)
py
SetDeviceListValidity(deviceListValidity)
php
function SetDeviceListValidity($deviceListValidity)
ts
async SetDeviceListValidity(deviceListValidity: number): Promise<void>
es
async SetDeviceListValidity(deviceListValidity)

By default, the library performs a full enumeration every 10 seconds. To reduce network traffic, you can increase this delay. It's particularly useful when a YoctoHub is connected to the GSM network where traffic is billed. This parameter doesn't impact modules connected by USB, nor the working of module arrival/removal callbacks. Note: you must call this function after yInitAPI.

Parameters :

deviceListValiditynubmer of seconds between each enumeration.

YAPI.SetHTTPCallbackCacheDir()
YAPI.SetHTTPCallbackCacheDir()
YAPI::SetHTTPCallbackCacheDir()

Enables the HTTP callback cache.

php
function SetHTTPCallbackCacheDir($str_directory)

When enabled, this cache reduces the quantity of data sent to the PHP script by 50% to 70%. To enable this cache, the method ySetHTTPCallbackCacheDir() must be called before any call to yRegisterHub(). This method takes in parameter the path of the directory used for saving data between each callback. This folder must exist and the PHP script needs to have write access to it. It is recommended to use a folder that is not published on the Web server since the library will save some data of Yoctopuce devices into this folder.

Note: This feature is supported by YoctoHub and VirtualHub since version 27750.

Parameters :

str_directorythe path of the folder that will be used as cache.

Returns :

nothing.

On failure, throws an exception.

YAPI.SetNetworkTimeout()
YAPI.SetNetworkTimeout()
YAPI::SetNetworkTimeout()[YAPI SetNetworkTimeout: ]ySetNetworkTimeout()YAPI.SetNetworkTimeout()YAPI.SetNetworkTimeout()YAPI.SetNetworkTimeout()YAPI.SetNetworkTimeout()YAPI.SetNetworkTimeout()YAPI::SetNetworkTimeout()YAPI.SetNetworkTimeout()YAPI.SetNetworkTimeout()YAPI.SetNetworkTimeout()YAPI.SetNetworkTimeout()

Modifies the network connection delay for yRegisterHub() and yUpdateDeviceList().

cpp
static void SetNetworkTimeout(int networkMsTimeout)
m
+(void) SetNetworkTimeout: (int) networkMsTimeout
pas
ySetNetworkTimeout(networkMsTimeout: LongInt)
vb
procedure SetNetworkTimeout(ByVal networkMsTimeout As Integer)
cs
void SetNetworkTimeout(int networkMsTimeout)
java
void SetNetworkTimeout(int networkMsTimeout)
uwp
async Task SetNetworkTimeout(int networkMsTimeout)
py
SetNetworkTimeout(networkMsTimeout)
php
function SetNetworkTimeout($networkMsTimeout)
ts
async SetNetworkTimeout(networkMsTimeout: number): Promise<void>
es
async SetNetworkTimeout(networkMsTimeout)
dnp
static void SetNetworkTimeout(int networkMsTimeout)
cp
static void SetNetworkTimeout(int networkMsTimeout)

This delay impacts only the YoctoHubs and VirtualHub which are accessible through the network. By default, this delay is of 20000 milliseconds, but depending or you network you may want to change this delay, gor example if your network infrastructure is based on a GSM connection.

Parameters :

networkMsTimeoutthe network connection delay in milliseconds.

YAPI.SetTimeout()
YAPI.SetTimeout()
ySetTimeout()YAPI.SetTimeout()YAPI.SetTimeout()

Invoke the specified callback function after a given timeout.

js
function ySetTimeout(callback, ms_timeout, args)
ts
SetTimeout(callback: Function, ms_timeout: number): number
es
SetTimeout(callback, ms_timeout, args)

This function behaves more or less like Javascript setTimeout, but during the waiting time, it will call yHandleEvents and yUpdateDeviceList periodically, in order to keep the API up-to-date with current devices.

Parameters :

callbackthe function to call after the timeout occurs. On Microsoft Internet Explorer, the callback must be provided as a string to be evaluated.
ms_timeoutan integer corresponding to the duration of the timeout, in milliseconds.
argsadditional arguments to be passed to the callback function can be provided, if needed (not supported on Microsoft Internet Explorer).

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

YAPI.SetUSBPacketAckMs()
YAPI.SetUSBPacketAckMs()
YAPI.SetUSBPacketAckMs()

Enables the acknowledge of every USB packet received by the Yoctopuce library.

java
void SetUSBPacketAckMs(int pktAckDelay)

This function allows the library to run on Android phones that tend to loose USB packets. By default, this feature is disabled because it doubles the number of packets sent and slows down the API considerably. Therefore, the acknowledge of incoming USB packets should only be enabled on phones or tablets that loose USB packets. A delay of 50 milliseconds is generally enough. In case of doubt, contact Yoctopuce support. To disable USB packets acknowledge, call this function with the value 0. Note: this feature is only available on Android.

Parameters :

resend the last USB packet.
pktAckDelaythen number of milliseconds before the module

YAPI.Sleep()
YAPI.Sleep()
ySleep()YAPI::Sleep()[YAPI Sleep: ]ySleep()YAPI.Sleep()YAPI.Sleep()YAPI.Sleep()YAPI.Sleep()YAPI.Sleep()YAPI::Sleep()YAPI.Sleep()YAPI.Sleep()

Pauses the execution flow for a specified duration.

js
function ySleep(ms_duration, errmsg)
cpp
YRETCODE Sleep(unsigned ms_duration, string errmsg)
m
+(YRETCODE) Sleep:(unsigned) ms_duration :(NSError **) errmsg
pas
integer ySleep(ms_duration: integer, var errmsg: string): integer
vb
function Sleep(ByVal ms_duration As Integer,
  ByRef errmsg As String) As Integer
cs
static int Sleep(int ms_duration, ref string errmsg)
java
int Sleep(long ms_duration)
uwp
async Task<int> Sleep(ulong ms_duration)
py
Sleep(ms_duration, errmsg=None)
php
function Sleep($ms_duration, &$errmsg)
ts
async Sleep(ms_duration: number, errmsg: YErrorMsg | null): Promise<number>
es
async Sleep(ms_duration, errmsg)

This function implements a passive waiting loop, meaning that it does not consume CPU cycles significantly. The processor is left available for other threads and processes. During the pause, the library nevertheless reads from time to time information from the Yoctopuce modules by calling yHandleEvents(), in order to stay up-to-date.

This function may signal an error in case there is a communication problem while contacting a module.

Parameters :

ms_durationan integer corresponding to the duration of the pause, in milliseconds.
errmsga string passed by reference to receive any error message.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

YAPI.TestHub()
YAPI.TestHub()
YAPI::TestHub()[YAPI TestHub: ]yTestHub()YAPI.TestHub()YAPI.TestHub()YAPI.TestHub()YAPI.TestHub()YAPI.TestHub()YAPI::TestHub()YAPI.TestHub()YAPI.TestHub()YAPI.TestHub()YAPI.TestHub()

Test if the hub is reachable.

cpp
YRETCODE TestHub(string url, int mstimeout, string errmsg)
m
+(YRETCODE) TestHub: (NSString*) url
  : (int) mstimeout
  : (NSError**) errmsg
pas
integer yTestHub(url: string,
  mstimeout: integer,
  var errmsg: string): integer
vb
function TestHub(ByVal url As String,
  ByVal mstimeout As Integer,
  ByRef errmsg As String) As Integer
cs
static int TestHub(string url, int mstimeout, ref string errmsg)
java
int TestHub(String url, int mstimeout)
uwp
async Task<int> TestHub(string url, uint mstimeout)
py
TestHub(url, mstimeout, errmsg=None)
php
function TestHub($url, $mstimeout, &$errmsg)
ts
async TestHub(url: string, mstimeout: number, errmsg: YErrorMsg): Promise<number>
es
async TestHub(url, mstimeout, errmsg)
dnp
static string TestHub(string url, int mstimeout)
cp
static string TestHub(string url, int mstimeout)

This method do not register the hub, it only test if the hub is usable. The url parameter follow the same convention as the yRegisterHub method. This method is useful to verify the authentication parameters for a hub. It is possible to force this method to return after mstimeout milliseconds.

Parameters :

urla string containing either "usb","callback" or the root URL of the hub to monitor
mstimeoutthe number of millisecond available to test the connection.
errmsga string passed by reference to receive any error message.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure returns a negative error code.

YAPI.TriggerHubDiscovery()
YAPI.TriggerHubDiscovery()
YAPI::TriggerHubDiscovery()[YAPI TriggerHubDiscovery: ]yTriggerHubDiscovery()YAPI.TriggerHubDiscovery()YAPI.TriggerHubDiscovery()YAPI.TriggerHubDiscovery()YAPI.TriggerHubDiscovery()YAPI.TriggerHubDiscovery()YAPI.TriggerHubDiscovery()YAPI.TriggerHubDiscovery()

Force a hub discovery, if a callback as been registered with yRegisterHubDiscoveryCallback it will be called for each net work hub that will respond to the discovery.

cpp
YRETCODE TriggerHubDiscovery(string errmsg)
m
+(YRETCODE) TriggerHubDiscovery: (NSError**) errmsg
pas
integer yTriggerHubDiscovery(var errmsg: string): integer
vb
function TriggerHubDiscovery(ByRef errmsg As String) As Integer
cs
static int TriggerHubDiscovery(ref string errmsg)
java
int TriggerHubDiscovery()
uwp
Task<int> TriggerHubDiscovery()
py
TriggerHubDiscovery(errmsg=None)
ts
async TriggerHubDiscovery(errmsg: YErrorMsg | null): Promise<number>
es
async TriggerHubDiscovery(errmsg)

Parameters :

errmsga string passed by reference to receive any error message.

Returns :

YAPI.SUCCESS when the call succeeds. On failure, throws an exception or returns a negative error code.

YAPI.UnregisterHub()
YAPI.UnregisterHub()
yUnregisterHub()YAPI::UnregisterHub()[YAPI UnregisterHub: ]yUnregisterHub()YAPI.UnregisterHub()YAPI.UnregisterHub()YAPI.UnregisterHub()YAPI.UnregisterHub()YAPI.UnregisterHub()YAPI::UnregisterHub()YAPI.UnregisterHub()YAPI.UnregisterHub()

Setup the Yoctopuce library to no more use modules connected on a previously registered machine with RegisterHub.

js
function yUnregisterHub(url)
cpp
void UnregisterHub(string url)
m
+(void) UnregisterHub:(NSString *) url
pas
yUnregisterHub(url: string)
vb
procedure UnregisterHub(ByVal url As String)
cs
static void UnregisterHub(string url)
java
void UnregisterHub(String url)
uwp
async Task UnregisterHub(string url)
py
UnregisterHub(url)
php
function UnregisterHub($url)
ts
async UnregisterHub(url: string): Promise<void>
es
async UnregisterHub(url)

Parameters :

root URL of the hub to monitor
urla string containing either "usb" or the

YAPI.UpdateDeviceList()
YAPI.UpdateDeviceList()
yUpdateDeviceList()YAPI::UpdateDeviceList()[YAPI UpdateDeviceList: ]yUpdateDeviceList()YAPI.UpdateDeviceList()YAPI.UpdateDeviceList()YAPI.UpdateDeviceList()YAPI.UpdateDeviceList()YAPI.UpdateDeviceList()YAPI::UpdateDeviceList()YAPI.UpdateDeviceList()YAPI.UpdateDeviceList()

Triggers a (re)detection of connected Yoctopuce modules.

js
function yUpdateDeviceList(errmsg)
cpp
YRETCODE UpdateDeviceList(string errmsg)
m
+(YRETCODE) UpdateDeviceList:(NSError**) errmsg
pas
integer yUpdateDeviceList(var errmsg: string): integer
vb
function UpdateDeviceList(ByRef errmsg As String) As YRETCODE
cs
static YRETCODE UpdateDeviceList(ref string errmsg)
java
int UpdateDeviceList()
uwp
async Task<int> UpdateDeviceList()
py
UpdateDeviceList(errmsg=None)
php
function UpdateDeviceList(&$errmsg)
ts
async UpdateDeviceList(errmsg: YErrorMsg | null): Promise<number>
es
async UpdateDeviceList(errmsg)

The library searches the machines or USB ports previously registered using yRegisterHub(), and invokes any user-defined callback function in case a change in the list of connected devices is detected.

This function can be called as frequently as desired to refresh the device list and to make the application aware of hot-plug events. However, since device detection is quite a heavy process, UpdateDeviceList shouldn't be called more than once every two seconds.

Parameters :

errmsga string passed by reference to receive any error message.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

YAPI.UpdateDeviceList_async()
YAPI.UpdateDeviceList_async()
yUpdateDeviceList_async()

Triggers a (re)detection of connected Yoctopuce modules.

js
function yUpdateDeviceList_async(callback, context)

The library searches the machines or USB ports previously registered using yRegisterHub(), and invokes any user-defined callback function in case a change in the list of connected devices is detected.

This function can be called as frequently as desired to refresh the device list and to make the application aware of hot-plug events.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking Firefox JavaScript VM that does not implement context switching during blocking I/O calls.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the result code (YAPI.SUCCESS if the operation completes successfully) and the error message.
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

24.2. Class YModule

Global parameters control interface for all Yoctopuce devices

The YModule class can be used with all Yoctopuce USB devices. It can be used to control the module global parameters, and to enumerate the functions provided by each module.

In order to use the functions described here, you should include:

js
<script type='text/javascript' src='yocto_api.js'></script>
cpp
#include "yocto_api.h"
m
#import "yocto_api.h"
pas
uses yocto_api;
vb
yocto_api.vb
cs
yocto_api.cs
java
import com.yoctopuce.YoctoAPI.YModule;
uwp
import com.yoctopuce.YoctoAPI.YModule;
py
from yocto_api import *
php
require_once('yocto_api.php');
ts
in HTML: import { YAPI, YErrorMsg, YModule, YSensor } from '../../dist/esm/yocto_api_browser.js';
in Node.js: import { YAPI, YErrorMsg, YModule, YSensor } from 'yoctolib-cjs/yocto_api_nodejs.js';
es
in HTML: <script src="../../lib/yocto_api.js"></script>
in node.js: require('yoctolib-es2017/yocto_api.js');
dnp
import YoctoProxyAPI.YModuleProxy
cp
#include "yocto_module_proxy.h"
vi
YModule.vi
ml
import YoctoProxyAPI.YModuleProxy"
Global functions
YModule.FindModule(func)

Allows you to find a module from its serial number or from its logical name.

YModule.FindModuleInContext(yctx, func)

Retrieves a module for a given identifier in a YAPI context.

YModule.FirstModule()

Starts the enumeration of modules currently accessible.

YModule properties
module→Beacon [writable]

State of the localization beacon.

module→FirmwareRelease [read-only]

Version of the firmware embedded in the module.

module→FunctionId [read-only]

Retrieves the hardware identifier of the nth function on the module.

module→HardwareId [read-only]

Unique hardware identifier of the module.

module→IsOnline [read-only]

Checks if the module is currently reachable.

module→LogicalName [writable]

Logical name of the module.

module→Luminosity [writable]

Luminosity of the module informative LEDs (from 0 to 100).

module→ProductId [read-only]

USB device identifier of the module.

module→ProductName [read-only]

Commercial name of the module, as set by the factory.

module→ProductRelease [read-only]

Release number of the module hardware, preprogrammed at the factory.

module→SerialNumber [read-only]

Serial number of the module, as set by the factory.

YModule methods
module→checkFirmware(path, onlynew)

Tests whether the byn file is valid for this module.

module→clearCache()

Invalidates the cache.

module→describe()

Returns a descriptive text that identifies the module.

module→download(pathname)

Downloads the specified built-in file and returns a binary buffer with its content.

module→functionBaseType(functionIndex)

Retrieves the base type of the nth function on the module.

module→functionCount()

Returns the number of functions (beside the "module" interface) available on the module.

module→functionId(functionIndex)

Retrieves the hardware identifier of the nth function on the module.

module→functionName(functionIndex)

Retrieves the logical name of the nth function on the module.

module→functionType(functionIndex)

Retrieves the type of the nth function on the module.

module→functionValue(functionIndex)

Retrieves the advertised value of the nth function on the module.

module→get_allSettings()

Returns all the settings and uploaded files of the module.

module→get_beacon()

Returns the state of the localization beacon.

module→get_errorMessage()

Returns the error message of the latest error with this module object.

module→get_errorType()

Returns the numerical error code of the latest error with this module object.

module→get_firmwareRelease()

Returns the version of the firmware embedded in the module.

module→get_functionIds(funType)

Retrieve all hardware identifier that match the type passed in argument.

module→get_hardwareId()

Returns the unique hardware identifier of the module.

module→get_icon2d()

Returns the icon of the module.

module→get_lastLogs()

Returns a string with last logs of the module.

module→get_logicalName()

Returns the logical name of the module.

module→get_luminosity()

Returns the luminosity of the module informative LEDs (from 0 to 100).

module→get_parentHub()

Returns the serial number of the YoctoHub on which this module is connected.

module→get_persistentSettings()

Returns the current state of persistent module settings.

module→get_productId()

Returns the USB device identifier of the module.

module→get_productName()

Returns the commercial name of the module, as set by the factory.

module→get_productRelease()

Returns the release number of the module hardware, preprogrammed at the factory.

module→get_rebootCountdown()

Returns the remaining number of seconds before the module restarts, or zero when no reboot has been scheduled.

module→get_serialNumber()

Returns the serial number of the module, as set by the factory.

module→get_subDevices()

Returns a list of all the modules that are plugged into the current module.

module→get_upTime()

Returns the number of milliseconds spent since the module was powered on.

module→get_url()

Returns the URL used to access the module.

module→get_usbCurrent()

Returns the current consumed by the module on the USB bus, in milli-amps.

module→get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

module→get_userVar()

Returns the value previously stored in this attribute.

module→hasFunction(funcId)

Tests if the device includes a specific function.

module→isOnline()

Checks if the module is currently reachable, without raising any error.

module→isOnline_async(callback, context)

Checks if the module is currently reachable, without raising any error.

module→load(msValidity)

Preloads the module cache with a specified validity duration.

module→load_async(msValidity, callback, context)

Preloads the module cache with a specified validity duration (asynchronous version).

module→log(text)

Adds a text message to the device logs.

module→nextModule()

Continues the module enumeration started using yFirstModule().

module→reboot(secBeforeReboot)

Schedules a simple module reboot after the given number of seconds.

module→registerBeaconCallback(callback)

Register a callback function, to be called when the localization beacon of the module has been changed.

module→registerConfigChangeCallback(callback)

Register a callback function, to be called when a persistent settings in a device configuration has been changed (e.g.

module→registerLogCallback(callback)

Registers a device log callback function.

module→revertFromFlash()

Reloads the settings stored in the nonvolatile memory, as when the module is powered on.

module→saveToFlash()

Saves current settings in the nonvolatile memory of the module.

module→set_allSettings(settings)

Restores all the settings of the device.

module→set_allSettingsAndFiles(settings)

Restores all the settings and uploaded files to the module.

module→set_beacon(newval)

Turns on or off the module localization beacon.

module→set_logicalName(newval)

Changes the logical name of the module.

module→set_luminosity(newval)

Changes the luminosity of the module informative leds.

module→set_userData(data)

Stores a user context provided as argument in the userData attribute of the function.

module→set_userVar(newval)

Stores a 32 bit value in the device RAM.

module→triggerConfigChangeCallback()

Triggers a configuration change callback, to check if they are supported or not.

module→triggerFirmwareUpdate(secBeforeReboot)

Schedules a module reboot into special firmware update mode.

module→updateFirmware(path)

Prepares a firmware update of the module.

module→updateFirmwareEx(path, force)

Prepares a firmware update of the module.

module→wait_async(callback, context)

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

YModule.FindModule()
YModule.FindModule()
yFindModule()YModule::FindModule()[YModule FindModule: ]yFindModule()YModule.FindModule()YModule.FindModule()YModule.FindModule()YModule.FindModule()YModule.FindModule()YModule::FindModule()YModule.FindModule()YModule.FindModule()YModule.FindModule()YModule.FindModule()

Allows you to find a module from its serial number or from its logical name.

js
function yFindModule(func)
cpp
YModule* FindModule(string func)
m
+(YModule*) FindModule: (NSString*) func
pas
TYModule yFindModule(func: string): TYModule
vb
function FindModule(ByVal func As String) As YModule
cs
static YModule FindModule(string func)
java
static YModule FindModule(String func)
uwp
static YModule FindModule(string func)
py
FindModule(func)
php
function FindModule($func)
ts
static FindModule(func: string): YModule
es
static FindModule(func)
dnp
static YModuleProxy FindModule(string func)
cp
static YModuleProxy * FindModule(string func)

This function does not require that the module is online at the time it is invoked. The returned object is nevertheless valid. Use the method YModule.isOnline() to test if the module is indeed online at a given time. In case of ambiguity when looking for a module by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

If a call to this object's is_online() method returns FALSE although you are certain that the device is plugged, make sure that you did call registerHub() at application initialization time.

Parameters :

funca string containing either the serial number or the logical name of the desired module

Returns :

a YModule object allowing you to drive the module or get additional information on the module.

YModule.FindModuleInContext()
YModule.FindModuleInContext()
YModule.FindModuleInContext()YModule.FindModuleInContext()YModule.FindModuleInContext()YModule.FindModuleInContext()

Retrieves a module for a given identifier in a YAPI context.

java
static YModule FindModuleInContext(YAPIContext yctx, String func)
uwp
static YModule FindModuleInContext(YAPIContext yctx, string func)
ts
static FindModuleInContext(yctx: YAPIContext, func: string): YModule
es
static FindModuleInContext(yctx, func)

The identifier can be specified using several formats:

This function does not require that the module is online at the time it is invoked. The returned object is nevertheless valid. Use the method YModule.isOnline() to test if the module is indeed online at a given time. In case of ambiguity when looking for a module by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

Parameters :

yctxa YAPI context
funca string that uniquely characterizes the module, for instance MyDevice.module.

Returns :

a YModule object allowing you to drive the module.

YModule.FirstModule()
YModule.FirstModule()
yFirstModule()YModule::FirstModule()[YModule FirstModule]yFirstModule()YModule.FirstModule()YModule.FirstModule()YModule.FirstModule()YModule.FirstModule()YModule.FirstModule()YModule::FirstModule()YModule.FirstModule()YModule.FirstModule()

Starts the enumeration of modules currently accessible.

js
function yFirstModule()
cpp
YModule * FirstModule()
m
+(YModule*) FirstModule
pas
TYModule yFirstModule(): TYModule
vb
function FirstModule() As YModule
cs
static YModule FirstModule()
java
static YModule FirstModule()
uwp
static YModule FirstModule()
py
FirstModule()
php
function FirstModule()
ts
static FirstModule(): YModule | null
es
static FirstModule()

Use the method YModule.nextModule() to iterate on the next modules.

Returns :

a pointer to a YModule object, corresponding to the first module currently online, or a null pointer if there are none.

module→Beaconmodule.Beacon

State of the localization beacon.

dnp
int Beacon

Writable. Turns on or off the module localization beacon.

module→FirmwareReleasemodule.FirmwareRelease

Version of the firmware embedded in the module.

dnp
string FirmwareRelease

module→FunctionIdmodule.FunctionId

Retrieves the hardware identifier of the nth function on the module.

dnp
string FunctionId

@param functionIndex : the index of the function for which the information is desired, starting at 0 for the first function.

module→HardwareIdmodule.HardwareId

Unique hardware identifier of the module.

dnp
string HardwareId

The unique hardware identifier is made of the device serial number followed by string ".module".

module→IsOnlinemodule.IsOnline

Checks if the module is currently reachable.

dnp
bool IsOnline

If there are valid cached values for the module, that have not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the requested module.

module→LogicalNamemodule.LogicalName

Logical name of the module.

dnp
string LogicalName

Writable. You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

module→Luminositymodule.Luminosity

Luminosity of the module informative LEDs (from 0 to 100).

dnp
int Luminosity

Writable. Changes the luminosity of the module informative leds. The parameter is a value between 0 and 100. Remember to call the saveToFlash() method of the module if the modification must be kept.

module→ProductIdmodule.ProductId

USB device identifier of the module.

dnp
int ProductId

module→ProductNamemodule.ProductName

Commercial name of the module, as set by the factory.

dnp
string ProductName

module→ProductReleasemodule.ProductRelease

Release number of the module hardware, preprogrammed at the factory.

dnp
int ProductRelease

The original hardware release returns value 1, revision B returns value 2, etc.

module→SerialNumbermodule.SerialNumber

Serial number of the module, as set by the factory.

dnp
string SerialNumber

module→checkFirmware()module.checkFirmware()module→checkFirmware()[module checkFirmware: ]module.checkFirmware()module.checkFirmware()module.checkFirmware()module.checkFirmware()module.checkFirmware()module.checkFirmware()module→checkFirmware()module.checkFirmware()module.checkFirmware()module.checkFirmware()module.checkFirmware()YModule checkFirmware

Tests whether the byn file is valid for this module.

js
function checkFirmware(path, onlynew)
cpp
string checkFirmware(string path, bool onlynew)
m
-(NSString*) checkFirmware: (NSString*) path
  : (bool) onlynew
pas
string checkFirmware(path: string, onlynew: boolean): string
vb
function checkFirmware(ByVal path As String, ByVal onlynew As Boolean) As String
cs
string checkFirmware(string path, bool onlynew)
java
String checkFirmware(String path, boolean onlynew)
uwp
async Task<string> checkFirmware(string path, bool onlynew)
py
checkFirmware(path, onlynew)
php
function checkFirmware($path, $onlynew)
ts
async checkFirmware(path: string, onlynew: boolean): Promise<string>
es
async checkFirmware(path, onlynew)
dnp
string checkFirmware(string path, bool onlynew)
cp
string checkFirmware(string path, bool onlynew)
cmd
YModule target checkFirmware path onlynew

This method is useful to test if the module needs to be updated. It is possible to pass a directory as argument instead of a file. In this case, this method returns the path of the most recent appropriate .byn file. If the parameter onlynew is true, the function discards firmwares that are older or equal to the installed firmware.

Parameters :

paththe path of a byn file or a directory that contains byn files
onlynewreturns only files that are strictly newer

Returns :

the path of the byn file to use or a empty string if no byn files matches the requirement

On failure, throws an exception or returns a string that start with "error:".

module→clearCache()module.clearCache()module→clearCache()[module clearCache]module.clearCache()module.clearCache()module.clearCache()module.clearCache()module.clearCache()module→clearCache()module.clearCache()module.clearCache()

Invalidates the cache.

js
function clearCache()
cpp
void clearCache()
m
-(void) clearCache
pas
clearCache()
vb
procedure clearCache()
cs
void clearCache()
java
void clearCache()
py
clearCache()
php
function clearCache()
ts
async clearCache(): Promise<void>
es
async clearCache()

Invalidates the cache of the module attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.

module→describe()module.describe()module→describe()[module describe]module.describe()module.describe()module.describe()module.describe()module.describe()module→describe()module.describe()module.describe()

Returns a descriptive text that identifies the module.

js
function describe()
cpp
string describe()
m
-(NSString*) describe
pas
string describe(): string
vb
function describe() As String
cs
string describe()
java
String describe()
py
describe()
php
function describe()
ts
async describe(): Promise<string>
es
async describe()

The text may include either the logical name or the serial number of the module.

Returns :

a string that describes the module

module→download()module.download()module→download()[module download: ]module.download()module.download()module.download()module.download()module.download()module.download()module→download()module.download()module.download()module.download()module.download()YModule download

Downloads the specified built-in file and returns a binary buffer with its content.

js
function download(pathname)
cpp
string download(string pathname)
m
-(NSMutableData*) download: (NSString*) pathname
pas
TByteArray download(pathname: string): TByteArray
vb
function download(ByVal pathname As String) As Byte
cs
byte[] download(string pathname)
java
byte[] download(String pathname)
uwp
async Task<byte[]> download(string pathname)
py
download(pathname)
php
function download($pathname)
ts
async download(pathname: string): Promise<Uint8Array>
es
async download(pathname)
dnp
byte[] download(string pathname)
cp
string download(string pathname)
cmd
YModule target download pathname

Parameters :

pathnamename of the new file to load

Returns :

a binary buffer with the file content

On failure, throws an exception or returns YAPI_INVALID_STRING.

module→functionBaseType()module.functionBaseType()module→functionBaseType()module.functionBaseType()module.functionBaseType()module.functionBaseType()module.functionBaseType()module.functionBaseType()module→functionBaseType()module.functionBaseType()module.functionBaseType()

Retrieves the base type of the nth function on the module.

js
function functionBaseType(functionIndex)
cpp
string functionBaseType(int functionIndex)
pas
string functionBaseType(functionIndex: integer): string
vb
function functionBaseType(ByVal functionIndex As Integer) As String
cs
string functionBaseType(int functionIndex)
java
String functionBaseType(int functionIndex)
py
functionBaseType(functionIndex)
php
function functionBaseType($functionIndex)
ts
async functionBaseType(functionIndex: number): Promise<string>
es
async functionBaseType(functionIndex)

For instance, the base type of all measuring functions is "Sensor".

Parameters :

functionIndexthe index of the function for which the information is desired, starting at 0 for the first function.

Returns :

a string corresponding to the base type of the function

On failure, throws an exception or returns an empty string.

module→functionCount()module.functionCount()module→functionCount()[module functionCount]module.functionCount()module.functionCount()module.functionCount()module.functionCount()module.functionCount()module→functionCount()module.functionCount()module.functionCount()

Returns the number of functions (beside the "module" interface) available on the module.

js
function functionCount()
cpp
int functionCount()
m
-(int) functionCount
pas
integer functionCount(): integer
vb
function functionCount() As Integer
cs
int functionCount()
java
int functionCount()
py
functionCount()
php
function functionCount()
ts
async functionCount(): Promise<number>
es
async functionCount()

Returns :

the number of functions on the module

On failure, throws an exception or returns a negative error code.

module→functionId()module.functionId()module→functionId()[module functionId: ]module.functionId()module.functionId()module.functionId()module.functionId()module.functionId()module→functionId()module.functionId()module.functionId()

Retrieves the hardware identifier of the nth function on the module.

js
function functionId(functionIndex)
cpp
string functionId(int functionIndex)
m
-(NSString*) functionId: (int) functionIndex
pas
string functionId(functionIndex: integer): string
vb
function functionId(ByVal functionIndex As Integer) As String
cs
string functionId(int functionIndex)
java
String functionId(int functionIndex)
py
functionId(functionIndex)
php
function functionId($functionIndex)
ts
async functionId(functionIndex: number): Promise<string>
es
async functionId(functionIndex)

Parameters :

functionIndexthe index of the function for which the information is desired, starting at 0 for the first function.

Returns :

a string corresponding to the unambiguous hardware identifier of the requested module function

On failure, throws an exception or returns an empty string.

module→functionName()module.functionName()module→functionName()[module functionName: ]module.functionName()module.functionName()module.functionName()module.functionName()module.functionName()module→functionName()module.functionName()module.functionName()

Retrieves the logical name of the nth function on the module.

js
function functionName(functionIndex)
cpp
string functionName(int functionIndex)
m
-(NSString*) functionName: (int) functionIndex
pas
string functionName(functionIndex: integer): string
vb
function functionName(ByVal functionIndex As Integer) As String
cs
string functionName(int functionIndex)
java
String functionName(int functionIndex)
py
functionName(functionIndex)
php
function functionName($functionIndex)
ts
async functionName(functionIndex: number): Promise<string>
es
async functionName(functionIndex)

Parameters :

functionIndexthe index of the function for which the information is desired, starting at 0 for the first function.

Returns :

a string corresponding to the logical name of the requested module function

On failure, throws an exception or returns an empty string.

module→functionType()module.functionType()module→functionType()module.functionType()module.functionType()module.functionType()module.functionType()module.functionType()module→functionType()module.functionType()module.functionType()

Retrieves the type of the nth function on the module.

js
function functionType(functionIndex)
cpp
string functionType(int functionIndex)
pas
string functionType(functionIndex: integer): string
vb
function functionType(ByVal functionIndex As Integer) As String
cs
string functionType(int functionIndex)
java
String functionType(int functionIndex)
py
functionType(functionIndex)
php
function functionType($functionIndex)
ts
async functionType(functionIndex: number): Promise<string>
es
async functionType(functionIndex)

Parameters :

functionIndexthe index of the function for which the information is desired, starting at 0 for the first function.

Returns :

a string corresponding to the type of the function

On failure, throws an exception or returns an empty string.

module→functionValue()module.functionValue()module→functionValue()[module functionValue: ]module.functionValue()module.functionValue()module.functionValue()module.functionValue()module.functionValue()module→functionValue()module.functionValue()module.functionValue()

Retrieves the advertised value of the nth function on the module.

js
function functionValue(functionIndex)
cpp
string functionValue(int functionIndex)
m
-(NSString*) functionValue: (int) functionIndex
pas
string functionValue(functionIndex: integer): string
vb
function functionValue(ByVal functionIndex As Integer) As String
cs
string functionValue(int functionIndex)
java
String functionValue(int functionIndex)
py
functionValue(functionIndex)
php
function functionValue($functionIndex)
ts
async functionValue(functionIndex: number): Promise<string>
es
async functionValue(functionIndex)

Parameters :

functionIndexthe index of the function for which the information is desired, starting at 0 for the first function.

Returns :

a short string (up to 6 characters) corresponding to the advertised value of the requested module function

On failure, throws an exception or returns an empty string.

module→get_allSettings()
module→allSettings()
module.get_allSettings()module→get_allSettings()[module allSettings]module.get_allSettings()module.get_allSettings()module.get_allSettings()module.get_allSettings()module.get_allSettings()module.get_allSettings()module→get_allSettings()module.get_allSettings()module.get_allSettings()module.get_allSettings()module.get_allSettings()YModule get_allSettings

Returns all the settings and uploaded files of the module.

js
function get_allSettings()
cpp
string get_allSettings()
m
-(NSMutableData*) allSettings
pas
TByteArray get_allSettings(): TByteArray
vb
function get_allSettings() As Byte
cs
byte[] get_allSettings()
java
byte[] get_allSettings()
uwp
async Task<byte[]> get_allSettings()
py
get_allSettings()
php
function get_allSettings()
ts
async get_allSettings(): Promise<Uint8Array>
es
async get_allSettings()
dnp
byte[] get_allSettings()
cp
string get_allSettings()
cmd
YModule target get_allSettings

Useful to backup all the logical names, calibrations parameters, and uploaded files of a device.

Returns :

a binary buffer with all the settings.

On failure, throws an exception or returns an binary object of size 0.

module→get_beacon()
module→beacon()
module.get_beacon()module→get_beacon()[module beacon]module.get_beacon()module.get_beacon()module.get_beacon()module.get_beacon()module.get_beacon()module.get_beacon()module→get_beacon()module.get_beacon()module.get_beacon()module.get_beacon()module.get_beacon()YModule get_beacon

Returns the state of the localization beacon.

js
function get_beacon()
cpp
Y_BEACON_enum get_beacon()
m
-(Y_BEACON_enum) beacon
pas
Integer get_beacon(): Integer
vb
function get_beacon() As Integer
cs
int get_beacon()
java
int get_beacon()
uwp
async Task<int> get_beacon()
py
get_beacon()
php
function get_beacon()
ts
async get_beacon(): Promise<YModule_Beacon>
es
async get_beacon()
dnp
int get_beacon()
cp
int get_beacon()
cmd
YModule target get_beacon

Returns :

either YModule.BEACON_OFF or YModule.BEACON_ON, according to the state of the localization beacon

On failure, throws an exception or returns YModule.BEACON_INVALID.

module→get_errorMessage()
module→errorMessage()
module.get_errorMessage()module→get_errorMessage()[module errorMessage]module.get_errorMessage()module.get_errorMessage()module.get_errorMessage()module.get_errorMessage()module.get_errorMessage()module→get_errorMessage()module.get_errorMessage()module.get_errorMessage()

Returns the error message of the latest error with this module object.

js
function get_errorMessage()
cpp
string get_errorMessage()
m
-(NSString*) errorMessage
pas
string get_errorMessage(): string
vb
function get_errorMessage() As String
cs
string get_errorMessage()
java
String get_errorMessage()
py
get_errorMessage()
php
function get_errorMessage()
ts
get_errorMessage(): string
es
get_errorMessage()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a string corresponding to the latest error message that occurred while using this module object

module→get_errorType()
module→errorType()
module.get_errorType()module→get_errorType()[module errorType]module.get_errorType()module.get_errorType()module.get_errorType()module.get_errorType()module.get_errorType()module→get_errorType()module.get_errorType()module.get_errorType()

Returns the numerical error code of the latest error with this module object.

js
function get_errorType()
cpp
YRETCODE get_errorType()
m
-(YRETCODE) errorType
pas
YRETCODE get_errorType(): YRETCODE
vb
function get_errorType() As YRETCODE
cs
YRETCODE get_errorType()
java
int get_errorType()
py
get_errorType()
php
function get_errorType()
ts
get_errorType(): number
es
get_errorType()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a number corresponding to the code of the latest error that occurred while using this module object

module→get_firmwareRelease()
module→firmwareRelease()
module.get_firmwareRelease()module→get_firmwareRelease()[module firmwareRelease]module.get_firmwareRelease()module.get_firmwareRelease()module.get_firmwareRelease()module.get_firmwareRelease()module.get_firmwareRelease()module.get_firmwareRelease()module→get_firmwareRelease()module.get_firmwareRelease()module.get_firmwareRelease()module.get_firmwareRelease()module.get_firmwareRelease()YModule get_firmwareRelease

Returns the version of the firmware embedded in the module.

js
function get_firmwareRelease()
cpp
string get_firmwareRelease()
m
-(NSString*) firmwareRelease
pas
string get_firmwareRelease(): string
vb
function get_firmwareRelease() As String
cs
string get_firmwareRelease()
java
String get_firmwareRelease()
uwp
async Task<string> get_firmwareRelease()
py
get_firmwareRelease()
php
function get_firmwareRelease()
ts
async get_firmwareRelease(): Promise<string>
es
async get_firmwareRelease()
dnp
string get_firmwareRelease()
cp
string get_firmwareRelease()
cmd
YModule target get_firmwareRelease

Returns :

a string corresponding to the version of the firmware embedded in the module

On failure, throws an exception or returns YModule.FIRMWARERELEASE_INVALID.

module→get_functionIds()
module→functionIds()
module.get_functionIds()module→get_functionIds()[module functionIds: ]module.get_functionIds()module.get_functionIds()module.get_functionIds()module.get_functionIds()module.get_functionIds()module.get_functionIds()module→get_functionIds()module.get_functionIds()module.get_functionIds()module.get_functionIds()module.get_functionIds()YModule get_functionIds

Retrieve all hardware identifier that match the type passed in argument.

js
function get_functionIds(funType)
cpp
vector<string> get_functionIds(string funType)
m
-(NSMutableArray*) functionIds: (NSString*) funType
pas
TStringArray get_functionIds(funType: string): TStringArray
vb
function get_functionIds(ByVal funType As String) As List
cs
List<string> get_functionIds(string funType)
java
ArrayList<String> get_functionIds(String funType)
uwp
async Task<List<string>> get_functionIds(string funType)
py
get_functionIds(funType)
php
function get_functionIds($funType)
ts
async get_functionIds(funType: string): Promise<string[]
es
async get_functionIds(funType)
dnp
string[] get_functionIds(string funType)
cp
vector<string> get_functionIds(string funType)
cmd
YModule target get_functionIds funType

Parameters :

funTypeThe type of function (Relay, LightSensor, Voltage,...)

Returns :

an array of strings.

module→get_hardwareId()
module→hardwareId()
module.get_hardwareId()module→get_hardwareId()[module hardwareId]module.get_hardwareId()module.get_hardwareId()module.get_hardwareId()module.get_hardwareId()module→get_hardwareId()module.get_hardwareId()module.get_hardwareId()module.get_hardwareId()module.get_hardwareId()module.get_hardwareId()module.get_hardwareId()YModule get_hardwareId

Returns the unique hardware identifier of the module.

js
function get_hardwareId()
cpp
string get_hardwareId()
m
-(NSString*) hardwareId
vb
function get_hardwareId() As String
cs
string get_hardwareId()
java
String get_hardwareId()
py
get_hardwareId()
php
function get_hardwareId()
ts
async get_hardwareId(): Promise<string>
es
async get_hardwareId()
dnp
string get_hardwareId()
cp
string get_hardwareId()
pas
string get_hardwareId(): string
uwp
async Task<string> get_hardwareId()
cmd
YModule target get_hardwareId

The unique hardware identifier is made of the device serial number followed by string ".module".

Returns :

a string that uniquely identifies the module

module→get_icon2d()
module→icon2d()
module.get_icon2d()module→get_icon2d()[module icon2d]module.get_icon2d()module.get_icon2d()module.get_icon2d()module.get_icon2d()module.get_icon2d()module.get_icon2d()module→get_icon2d()module.get_icon2d()module.get_icon2d()module.get_icon2d()module.get_icon2d()YModule get_icon2d

Returns the icon of the module.

js
function get_icon2d()
cpp
string get_icon2d()
m
-(NSMutableData*) icon2d
pas
TByteArray get_icon2d(): TByteArray
vb
function get_icon2d() As Byte
cs
byte[] get_icon2d()
java
byte[] get_icon2d()
uwp
async Task<byte[]> get_icon2d()
py
get_icon2d()
php
function get_icon2d()
ts
async get_icon2d(): Promise<Uint8Array>
es
async get_icon2d()
dnp
byte[] get_icon2d()
cp
string get_icon2d()
cmd
YModule target get_icon2d

The icon is a PNG image and does not exceeds 1536 bytes.

Returns :

a binary buffer with module icon, in png format. On failure, throws an exception or returns YAPI_INVALID_STRING.

module→get_lastLogs()
module→lastLogs()
module.get_lastLogs()module→get_lastLogs()[module lastLogs]module.get_lastLogs()module.get_lastLogs()module.get_lastLogs()module.get_lastLogs()module.get_lastLogs()module.get_lastLogs()module→get_lastLogs()module.get_lastLogs()module.get_lastLogs()module.get_lastLogs()module.get_lastLogs()YModule get_lastLogs

Returns a string with last logs of the module.

js
function get_lastLogs()
cpp
string get_lastLogs()
m
-(NSString*) lastLogs
pas
string get_lastLogs(): string
vb
function get_lastLogs() As String
cs
string get_lastLogs()
java
String get_lastLogs()
uwp
async Task<string> get_lastLogs()
py
get_lastLogs()
php
function get_lastLogs()
ts
async get_lastLogs(): Promise<string>
es
async get_lastLogs()
dnp
string get_lastLogs()
cp
string get_lastLogs()
cmd
YModule target get_lastLogs

This method return only logs that are still in the module.

Returns :

a string with last logs of the module. On failure, throws an exception or returns YAPI_INVALID_STRING.

module→get_logicalName()
module→logicalName()
module.get_logicalName()module→get_logicalName()[module logicalName]module.get_logicalName()module.get_logicalName()module.get_logicalName()module.get_logicalName()module.get_logicalName()module.get_logicalName()module→get_logicalName()module.get_logicalName()module.get_logicalName()module.get_logicalName()module.get_logicalName()YModule get_logicalName

Returns the logical name of the module.

js
function get_logicalName()
cpp
string get_logicalName()
m
-(NSString*) logicalName
pas
string get_logicalName(): string
vb
function get_logicalName() As String
cs
string get_logicalName()
java
String get_logicalName()
uwp
async Task<string> get_logicalName()
py
get_logicalName()
php
function get_logicalName()
ts
async get_logicalName(): Promise<string>
es
async get_logicalName()
dnp
string get_logicalName()
cp
string get_logicalName()
cmd
YModule target get_logicalName

Returns :

a string corresponding to the logical name of the module

On failure, throws an exception or returns YModule.LOGICALNAME_INVALID.

module→get_luminosity()
module→luminosity()
module.get_luminosity()module→get_luminosity()[module luminosity]module.get_luminosity()module.get_luminosity()module.get_luminosity()module.get_luminosity()module.get_luminosity()module.get_luminosity()module→get_luminosity()module.get_luminosity()module.get_luminosity()module.get_luminosity()module.get_luminosity()YModule get_luminosity

Returns the luminosity of the module informative LEDs (from 0 to 100).

js
function get_luminosity()
cpp
int get_luminosity()
m
-(int) luminosity
pas
LongInt get_luminosity(): LongInt
vb
function get_luminosity() As Integer
cs
int get_luminosity()
java
int get_luminosity()
uwp
async Task<int> get_luminosity()
py
get_luminosity()
php
function get_luminosity()
ts
async get_luminosity(): Promise<number>
es
async get_luminosity()
dnp
int get_luminosity()
cp
int get_luminosity()
cmd
YModule target get_luminosity

Returns :

an integer corresponding to the luminosity of the module informative LEDs (from 0 to 100)

On failure, throws an exception or returns YModule.LUMINOSITY_INVALID.

module→get_parentHub()
module→parentHub()
module.get_parentHub()module→get_parentHub()[module parentHub]module.get_parentHub()module.get_parentHub()module.get_parentHub()module.get_parentHub()module.get_parentHub()module.get_parentHub()module→get_parentHub()module.get_parentHub()module.get_parentHub()module.get_parentHub()module.get_parentHub()YModule get_parentHub

Returns the serial number of the YoctoHub on which this module is connected.

js
function get_parentHub()
cpp
string get_parentHub()
m
-(NSString*) parentHub
pas
string get_parentHub(): string
vb
function get_parentHub() As String
cs
string get_parentHub()
java
String get_parentHub()
uwp
async Task<string> get_parentHub()
py
get_parentHub()
php
function get_parentHub()
ts
async get_parentHub(): Promise<string>
es
async get_parentHub()
dnp
string get_parentHub()
cp
string get_parentHub()
cmd
YModule target get_parentHub

If the module is connected by USB, or if the module is the root YoctoHub, an empty string is returned.

Returns :

a string with the serial number of the YoctoHub or an empty string

module→get_persistentSettings()
module→persistentSettings()
module.get_persistentSettings()module→get_persistentSettings()[module persistentSettings]module.get_persistentSettings()module.get_persistentSettings()module.get_persistentSettings()module.get_persistentSettings()module.get_persistentSettings()module.get_persistentSettings()module→get_persistentSettings()module.get_persistentSettings()module.get_persistentSettings()module.get_persistentSettings()module.get_persistentSettings()YModule get_persistentSettings

Returns the current state of persistent module settings.

js
function get_persistentSettings()
cpp
Y_PERSISTENTSETTINGS_enum get_persistentSettings()
m
-(Y_PERSISTENTSETTINGS_enum) persistentSettings
pas
Integer get_persistentSettings(): Integer
vb
function get_persistentSettings() As Integer
cs
int get_persistentSettings()
java
int get_persistentSettings()
uwp
async Task<int> get_persistentSettings()
py
get_persistentSettings()
php
function get_persistentSettings()
ts
async get_persistentSettings(): Promise<YModule_PersistentSettings>
es
async get_persistentSettings()
dnp
int get_persistentSettings()
cp
int get_persistentSettings()
cmd
YModule target get_persistentSettings

Returns :

a value among YModule.PERSISTENTSETTINGS_LOADED, YModule.PERSISTENTSETTINGS_SAVED and YModule.PERSISTENTSETTINGS_MODIFIED corresponding to the current state of persistent module settings

On failure, throws an exception or returns YModule.PERSISTENTSETTINGS_INVALID.

module→get_productId()
module→productId()
module.get_productId()module→get_productId()[module productId]module.get_productId()module.get_productId()module.get_productId()module.get_productId()module.get_productId()module.get_productId()module→get_productId()module.get_productId()module.get_productId()module.get_productId()module.get_productId()YModule get_productId

Returns the USB device identifier of the module.

js
function get_productId()
cpp
int get_productId()
m
-(int) productId
pas
LongInt get_productId(): LongInt
vb
function get_productId() As Integer
cs
int get_productId()
java
int get_productId()
uwp
async Task<int> get_productId()
py
get_productId()
php
function get_productId()
ts
async get_productId(): Promise<number>
es
async get_productId()
dnp
int get_productId()
cp
int get_productId()
cmd
YModule target get_productId

Returns :

an integer corresponding to the USB device identifier of the module

On failure, throws an exception or returns YModule.PRODUCTID_INVALID.

module→get_productName()
module→productName()
module.get_productName()module→get_productName()[module productName]module.get_productName()module.get_productName()module.get_productName()module.get_productName()module.get_productName()module.get_productName()module→get_productName()module.get_productName()module.get_productName()module.get_productName()module.get_productName()YModule get_productName

Returns the commercial name of the module, as set by the factory.

js
function get_productName()
cpp
string get_productName()
m
-(NSString*) productName
pas
string get_productName(): string
vb
function get_productName() As String
cs
string get_productName()
java
String get_productName()
uwp
async Task<string> get_productName()
py
get_productName()
php
function get_productName()
ts
async get_productName(): Promise<string>
es
async get_productName()
dnp
string get_productName()
cp
string get_productName()
cmd
YModule target get_productName

Returns :

a string corresponding to the commercial name of the module, as set by the factory

On failure, throws an exception or returns YModule.PRODUCTNAME_INVALID.

module→get_productRelease()
module→productRelease()
module.get_productRelease()module→get_productRelease()[module productRelease]module.get_productRelease()module.get_productRelease()module.get_productRelease()module.get_productRelease()module.get_productRelease()module.get_productRelease()module→get_productRelease()module.get_productRelease()module.get_productRelease()module.get_productRelease()module.get_productRelease()YModule get_productRelease

Returns the release number of the module hardware, preprogrammed at the factory.

js
function get_productRelease()
cpp
int get_productRelease()
m
-(int) productRelease
pas
LongInt get_productRelease(): LongInt
vb
function get_productRelease() As Integer
cs
int get_productRelease()
java
int get_productRelease()
uwp
async Task<int> get_productRelease()
py
get_productRelease()
php
function get_productRelease()
ts
async get_productRelease(): Promise<number>
es
async get_productRelease()
dnp
int get_productRelease()
cp
int get_productRelease()
cmd
YModule target get_productRelease

The original hardware release returns value 1, revision B returns value 2, etc.

Returns :

an integer corresponding to the release number of the module hardware, preprogrammed at the factory

On failure, throws an exception or returns YModule.PRODUCTRELEASE_INVALID.

module→get_rebootCountdown()
module→rebootCountdown()
module.get_rebootCountdown()module→get_rebootCountdown()[module rebootCountdown]module.get_rebootCountdown()module.get_rebootCountdown()module.get_rebootCountdown()module.get_rebootCountdown()module.get_rebootCountdown()module.get_rebootCountdown()module→get_rebootCountdown()module.get_rebootCountdown()module.get_rebootCountdown()module.get_rebootCountdown()module.get_rebootCountdown()YModule get_rebootCountdown

Returns the remaining number of seconds before the module restarts, or zero when no reboot has been scheduled.

js
function get_rebootCountdown()
cpp
int get_rebootCountdown()
m
-(int) rebootCountdown
pas
LongInt get_rebootCountdown(): LongInt
vb
function get_rebootCountdown() As Integer
cs
int get_rebootCountdown()
java
int get_rebootCountdown()
uwp
async Task<int> get_rebootCountdown()
py
get_rebootCountdown()
php
function get_rebootCountdown()
ts
async get_rebootCountdown(): Promise<number>
es
async get_rebootCountdown()
dnp
int get_rebootCountdown()
cp
int get_rebootCountdown()
cmd
YModule target get_rebootCountdown

Returns :

an integer corresponding to the remaining number of seconds before the module restarts, or zero when no reboot has been scheduled

On failure, throws an exception or returns YModule.REBOOTCOUNTDOWN_INVALID.

module→get_serialNumber()
module→serialNumber()
module.get_serialNumber()module→get_serialNumber()[module serialNumber]module.get_serialNumber()module.get_serialNumber()module.get_serialNumber()module.get_serialNumber()module.get_serialNumber()module.get_serialNumber()module→get_serialNumber()module.get_serialNumber()module.get_serialNumber()module.get_serialNumber()module.get_serialNumber()YModule get_serialNumber

Returns the serial number of the module, as set by the factory.

js
function get_serialNumber()
cpp
string get_serialNumber()
m
-(NSString*) serialNumber
pas
string get_serialNumber(): string
vb
function get_serialNumber() As String
cs
string get_serialNumber()
java
String get_serialNumber()
uwp
async Task<string> get_serialNumber()
py
get_serialNumber()
php
function get_serialNumber()
ts
async get_serialNumber(): Promise<string>
es
async get_serialNumber()
dnp
string get_serialNumber()
cp
string get_serialNumber()
cmd
YModule target get_serialNumber

Returns :

a string corresponding to the serial number of the module, as set by the factory

On failure, throws an exception or returns YModule.SERIALNUMBER_INVALID.

module→get_subDevices()
module→subDevices()
module.get_subDevices()module→get_subDevices()[module subDevices]module.get_subDevices()module.get_subDevices()module.get_subDevices()module.get_subDevices()module.get_subDevices()module.get_subDevices()module→get_subDevices()module.get_subDevices()module.get_subDevices()module.get_subDevices()module.get_subDevices()YModule get_subDevices

Returns a list of all the modules that are plugged into the current module.

js
function get_subDevices()
cpp
vector<string> get_subDevices()
m
-(NSMutableArray*) subDevices
pas
TStringArray get_subDevices(): TStringArray
vb
function get_subDevices() As List
cs
List<string> get_subDevices()
java
ArrayList<String> get_subDevices()
uwp
async Task<List<string>> get_subDevices()
py
get_subDevices()
php
function get_subDevices()
ts
async get_subDevices(): Promise<string[]
es
async get_subDevices()
dnp
string[] get_subDevices()
cp
vector<string> get_subDevices()
cmd
YModule target get_subDevices

This method only makes sense when called for a YoctoHub/VirtualHub. Otherwise, an empty array will be returned.

Returns :

an array of strings containing the sub modules.

module→get_upTime()
module→upTime()
module.get_upTime()module→get_upTime()[module upTime]module.get_upTime()module.get_upTime()module.get_upTime()module.get_upTime()module.get_upTime()module.get_upTime()module→get_upTime()module.get_upTime()module.get_upTime()module.get_upTime()module.get_upTime()YModule get_upTime

Returns the number of milliseconds spent since the module was powered on.

js
function get_upTime()
cpp
s64 get_upTime()
m
-(s64) upTime
pas
int64 get_upTime(): int64
vb
function get_upTime() As Long
cs
long get_upTime()
java
long get_upTime()
uwp
async Task<long> get_upTime()
py
get_upTime()
php
function get_upTime()
ts
async get_upTime(): Promise<number>
es
async get_upTime()
dnp
long get_upTime()
cp
s64 get_upTime()
cmd
YModule target get_upTime

Returns :

an integer corresponding to the number of milliseconds spent since the module was powered on

On failure, throws an exception or returns YModule.UPTIME_INVALID.

module→get_url()
module→url()
module.get_url()module→get_url()[module url]module.get_url()module.get_url()module.get_url()module.get_url()module.get_url()module.get_url()module→get_url()module.get_url()module.get_url()module.get_url()module.get_url()YModule get_url

Returns the URL used to access the module.

js
function get_url()
cpp
string get_url()
m
-(NSString*) url
pas
string get_url(): string
vb
function get_url() As String
cs
string get_url()
java
String get_url()
uwp
async Task<string> get_url()
py
get_url()
php
function get_url()
ts
async get_url(): Promise<string>
es
async get_url()
dnp
string get_url()
cp
string get_url()
cmd
YModule target get_url

If the module is connected by USB, the string 'usb' is returned.

Returns :

a string with the URL of the module.

module→get_usbCurrent()
module→usbCurrent()
module.get_usbCurrent()module→get_usbCurrent()[module usbCurrent]module.get_usbCurrent()module.get_usbCurrent()module.get_usbCurrent()module.get_usbCurrent()module.get_usbCurrent()module.get_usbCurrent()module→get_usbCurrent()module.get_usbCurrent()module.get_usbCurrent()module.get_usbCurrent()module.get_usbCurrent()YModule get_usbCurrent

Returns the current consumed by the module on the USB bus, in milli-amps.

js
function get_usbCurrent()
cpp
int get_usbCurrent()
m
-(int) usbCurrent
pas
LongInt get_usbCurrent(): LongInt
vb
function get_usbCurrent() As Integer
cs
int get_usbCurrent()
java
int get_usbCurrent()
uwp
async Task<int> get_usbCurrent()
py
get_usbCurrent()
php
function get_usbCurrent()
ts
async get_usbCurrent(): Promise<number>
es
async get_usbCurrent()
dnp
int get_usbCurrent()
cp
int get_usbCurrent()
cmd
YModule target get_usbCurrent

Returns :

an integer corresponding to the current consumed by the module on the USB bus, in milli-amps

On failure, throws an exception or returns YModule.USBCURRENT_INVALID.

module→get_userData()
module→userData()
module.get_userData()module→get_userData()[module userData]module.get_userData()module.get_userData()module.get_userData()module.get_userData()module.get_userData()module→get_userData()module.get_userData()module.get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

js
function get_userData()
cpp
void * get_userData()
m
-(id) userData
pas
Tobject get_userData(): Tobject
vb
function get_userData() As Object
cs
object get_userData()
java
Object get_userData()
py
get_userData()
php
function get_userData()
ts
async get_userData(): Promise<object|null>
es
async get_userData()

This attribute is never touched directly by the API, and is at disposal of the caller to store a context.

Returns :

the object stored previously by the caller.

module→get_userVar()
module→userVar()
module.get_userVar()module→get_userVar()[module userVar]module.get_userVar()module.get_userVar()module.get_userVar()module.get_userVar()module.get_userVar()module.get_userVar()module→get_userVar()module.get_userVar()module.get_userVar()module.get_userVar()module.get_userVar()YModule get_userVar

Returns the value previously stored in this attribute.

js
function get_userVar()
cpp
int get_userVar()
m
-(int) userVar
pas
LongInt get_userVar(): LongInt
vb
function get_userVar() As Integer
cs
int get_userVar()
java
int get_userVar()
uwp
async Task<int> get_userVar()
py
get_userVar()
php
function get_userVar()
ts
async get_userVar(): Promise<number>
es
async get_userVar()
dnp
int get_userVar()
cp
int get_userVar()
cmd
YModule target get_userVar

On startup and after a device reboot, the value is always reset to zero.

Returns :

an integer corresponding to the value previously stored in this attribute

On failure, throws an exception or returns YModule.USERVAR_INVALID.

module→hasFunction()module.hasFunction()module→hasFunction()[module hasFunction: ]module.hasFunction()module.hasFunction()module.hasFunction()module.hasFunction()module.hasFunction()module.hasFunction()module→hasFunction()module.hasFunction()module.hasFunction()module.hasFunction()module.hasFunction()YModule hasFunction

Tests if the device includes a specific function.

js
function hasFunction(funcId)
cpp
bool hasFunction(string funcId)
m
-(bool) hasFunction: (NSString*) funcId
pas
boolean hasFunction(funcId: string): boolean
vb
function hasFunction(ByVal funcId As String) As Boolean
cs
bool hasFunction(string funcId)
java
boolean hasFunction(String funcId)
uwp
async Task<bool> hasFunction(string funcId)
py
hasFunction(funcId)
php
function hasFunction($funcId)
ts
async hasFunction(funcId: string): Promise<boolean>
es
async hasFunction(funcId)
dnp
bool hasFunction(string funcId)
cp
bool hasFunction(string funcId)
cmd
YModule target hasFunction funcId

This method takes a function identifier and returns a boolean.

Parameters :

funcIdthe requested function identifier

Returns :

true if the device has the function identifier

module→isOnline()module.isOnline()module→isOnline()[module isOnline]module.isOnline()module.isOnline()module.isOnline()module.isOnline()module.isOnline()module→isOnline()module.isOnline()module.isOnline()module.isOnline()module.isOnline()

Checks if the module is currently reachable, without raising any error.

js
function isOnline()
cpp
bool isOnline()
m
-(BOOL) isOnline
pas
boolean isOnline(): boolean
vb
function isOnline() As Boolean
cs
bool isOnline()
java
boolean isOnline()
py
isOnline()
php
function isOnline()
ts
async isOnline(): Promise<boolean>
es
async isOnline()
dnp
bool isOnline()
cp
bool isOnline()

If there are valid cached values for the module, that have not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the requested module.

Returns :

true if the module can be reached, and false otherwise

module→isOnline_async()module.isOnline_async()

Checks if the module is currently reachable, without raising any error.

js
function isOnline_async(callback, context)

If there are valid cached values for the module, that have not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the requested module.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking Firefox JavaScript VM that does not implement context switching during blocking I/O calls.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving module object and the boolean result
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

module→load()module.load()module→load()[module load: ]module.load()module.load()module.load()module.load()module.load()module→load()module.load()module.load()

Preloads the module cache with a specified validity duration.

js
function load(msValidity)
cpp
YRETCODE load(int msValidity)
m
-(YRETCODE) load: (u64) msValidity
pas
YRETCODE load(msValidity: u64): YRETCODE
vb
function load(ByVal msValidity As Long) As YRETCODE
cs
YRETCODE load(ulong msValidity)
java
int load(long msValidity)
py
load(msValidity)
php
function load($msValidity)
ts
async load(msValidity: number): Promise<number>
es
async load(msValidity)

By default, whenever accessing a device, all module attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

Parameters :

msValidityan integer corresponding to the validity attributed to the loaded module parameters, in milliseconds

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

module→load_async()module.load_async()

Preloads the module cache with a specified validity duration (asynchronous version).

js
function load_async(msValidity, callback, context)

By default, whenever accessing a device, all module attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking Firefox JavaScript VM that does not implement context switching during blocking I/O calls. See the documentation section on asynchronous JavaScript calls for more details.

Parameters :

msValidityan integer corresponding to the validity of the loaded module parameters, in milliseconds
callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving module object and the error code (or YAPI.SUCCESS)
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

module→log()module.log()module→log()[module log: ]module.log()module.log()module.log()module.log()module.log()module.log()module→log()module.log()module.log()module.log()module.log()YModule log

Adds a text message to the device logs.

js
function log(text)
cpp
int log(string text)
m
-(int) log: (NSString*) text
pas
LongInt log(text: string): LongInt
vb
function log(ByVal text As String) As Integer
cs
int log(string text)
java
int log(String text)
uwp
async Task<int> log(string text)
py
log(text)
php
function log($text)
ts
async log(text: string): Promise<number>
es
async log(text)
dnp
int log(string text)
cp
int log(string text)
cmd
YModule target log text

This function is useful in particular to trace the execution of HTTP callbacks. If a newline is desired after the message, it must be included in the string.

Parameters :

textthe string to append to the logs.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

module→nextModule()module.nextModule()module→nextModule()[module nextModule]module.nextModule()module.nextModule()module.nextModule()module.nextModule()module.nextModule()module.nextModule()module→nextModule()module.nextModule()module.nextModule()

Continues the module enumeration started using yFirstModule().

js
function nextModule()
cpp
YModule * nextModule()
m
-(nullable YModule*) nextModule
pas
TYModule nextModule(): TYModule
vb
function nextModule() As YModule
cs
YModule nextModule()
java
YModule nextModule()
uwp
YModule nextModule()
py
nextModule()
php
function nextModule()
ts
nextModule(): YModule | null
es
nextModule()

Caution: You can't make any assumption about the returned modules order. If you want to find a specific module, use Module.findModule() and a hardwareID or a logical name.

Returns :

a pointer to a YModule object, corresponding to the next module found, or a null pointer if there are no more modules to enumerate.

module→reboot()module.reboot()module→reboot()[module reboot: ]module.reboot()module.reboot()module.reboot()module.reboot()module.reboot()module.reboot()module→reboot()module.reboot()module.reboot()module.reboot()module.reboot()YModule reboot

Schedules a simple module reboot after the given number of seconds.

js
function reboot(secBeforeReboot)
cpp
int reboot(int secBeforeReboot)
m
-(int) reboot: (int) secBeforeReboot
pas
LongInt reboot(secBeforeReboot: LongInt): LongInt
vb
function reboot(ByVal secBeforeReboot As Integer) As Integer
cs
int reboot(int secBeforeReboot)
java
int reboot(int secBeforeReboot)
uwp
async Task<int> reboot(int secBeforeReboot)
py
reboot(secBeforeReboot)
php
function reboot($secBeforeReboot)
ts
async reboot(secBeforeReboot: number): Promise<number>
es
async reboot(secBeforeReboot)
dnp
int reboot(int secBeforeReboot)
cp
int reboot(int secBeforeReboot)
cmd
YModule target reboot secBeforeReboot

Parameters :

secBeforeRebootnumber of seconds before rebooting

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

module→registerBeaconCallback()module.registerBeaconCallback()module→registerBeaconCallback()[module registerBeaconCallback: ]module.registerBeaconCallback()module.registerBeaconCallback()module.registerBeaconCallback()module.registerBeaconCallback()module.registerBeaconCallback()module.registerBeaconCallback()module→registerBeaconCallback()module.registerBeaconCallback()module.registerBeaconCallback()

Register a callback function, to be called when the localization beacon of the module has been changed.

js
function registerBeaconCallback(callback)
cpp
int registerBeaconCallback(YModuleBeaconCallback callback)
m
-(int) registerBeaconCallback: (YModuleBeaconCallback _Nullable) callback
pas
LongInt registerBeaconCallback(callback: TYModuleBeaconCallback): LongInt
vb
function registerBeaconCallback(ByVal callback As YModuleBeaconCallback) As Integer
cs
int registerBeaconCallback(BeaconCallback callback)
java
int registerBeaconCallback(BeaconCallback callback)
uwp
async Task<int> registerBeaconCallback(BeaconCallback callback)
py
registerBeaconCallback(callback)
php
function registerBeaconCallback($callback)
ts
async registerBeaconCallback(callback: YModuleBeaconCallback | null): Promise<number>
es
async registerBeaconCallback(callback)

The callback function should take two arguments: the YModule object of which the beacon has changed, and an integer describing the new beacon state.

Parameters :

previously registered callback.
callbackThe callback function to call, or null to unregister a

module→registerConfigChangeCallback()module.registerConfigChangeCallback()module→registerConfigChangeCallback()[module registerConfigChangeCallback: ]module.registerConfigChangeCallback()module.registerConfigChangeCallback()module.registerConfigChangeCallback()module.registerConfigChangeCallback()module.registerConfigChangeCallback()module.registerConfigChangeCallback()module→registerConfigChangeCallback()module.registerConfigChangeCallback()module.registerConfigChangeCallback()

Register a callback function, to be called when a persistent settings in a device configuration has been changed (e.g.

js
function registerConfigChangeCallback(callback)
cpp
int registerConfigChangeCallback(YModuleConfigChangeCallback callback)
m
-(int) registerConfigChangeCallback: (YModuleConfigChangeCallback _Nullable) callback
pas
LongInt registerConfigChangeCallback(callback: TYModuleConfigChangeCallback): LongInt
vb
function registerConfigChangeCallback(ByVal callback As YModuleConfigChangeCallback) As Integer
cs
int registerConfigChangeCallback(ConfigChangeCallback callback)
java
int registerConfigChangeCallback(ConfigChangeCallback callback)
uwp
async Task<int> registerConfigChangeCallback(ConfigChangeCallback callback)
py
registerConfigChangeCallback(callback)
php
function registerConfigChangeCallback($callback)
ts
async registerConfigChangeCallback(callback: YModuleConfigChangeCallback | null): Promise<number>
es
async registerConfigChangeCallback(callback)

change of unit, etc).

Parameters :

to unregister a previously registered callback.
callbacka procedure taking a YModule parameter, or null

module→registerLogCallback()module.registerLogCallback()module→registerLogCallback()[module registerLogCallback: ]module.registerLogCallback()module.registerLogCallback()module.registerLogCallback()module.registerLogCallback()module.registerLogCallback()module.registerLogCallback()module→registerLogCallback()module.registerLogCallback()module.registerLogCallback()

Registers a device log callback function.

js
function registerLogCallback(callback)
cpp
int registerLogCallback(YModuleLogCallback callback)
m
-(int) registerLogCallback: (YModuleLogCallback _Nullable) callback
pas
LongInt registerLogCallback(callback: TYModuleLogCallback): LongInt
vb
function registerLogCallback(ByVal callback As YModuleLogCallback) As Integer
cs
int registerLogCallback(LogCallback callback)
java
int registerLogCallback(LogCallback callback)
uwp
async Task<int> registerLogCallback(LogCallback callback)
py
registerLogCallback(callback)
php
function registerLogCallback($callback)
ts
async registerLogCallback(callback: YModuleLogCallback | null): Promise<number>
es
async registerLogCallback(callback)

This callback will be called each time that a module sends a new log message. Mostly useful to debug a Yoctopuce module.

Parameters :

On failure, throws an exception or returns a negative error code.
callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the module object that emitted the log message, and the character string containing the log.

module→revertFromFlash()module.revertFromFlash()module→revertFromFlash()[module revertFromFlash]module.revertFromFlash()module.revertFromFlash()module.revertFromFlash()module.revertFromFlash()module.revertFromFlash()module.revertFromFlash()module→revertFromFlash()module.revertFromFlash()module.revertFromFlash()module.revertFromFlash()module.revertFromFlash()YModule revertFromFlash

Reloads the settings stored in the nonvolatile memory, as when the module is powered on.

js
function revertFromFlash()
cpp
int revertFromFlash()
m
-(int) revertFromFlash
pas
LongInt revertFromFlash(): LongInt
vb
function revertFromFlash() As Integer
cs
int revertFromFlash()
java
int revertFromFlash()
uwp
async Task<int> revertFromFlash()
py
revertFromFlash()
php
function revertFromFlash()
ts
async revertFromFlash(): Promise<number>
es
async revertFromFlash()
dnp
int revertFromFlash()
cp
int revertFromFlash()
cmd
YModule target revertFromFlash

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

module→saveToFlash()module.saveToFlash()module→saveToFlash()[module saveToFlash]module.saveToFlash()module.saveToFlash()module.saveToFlash()module.saveToFlash()module.saveToFlash()module.saveToFlash()module→saveToFlash()module.saveToFlash()module.saveToFlash()module.saveToFlash()module.saveToFlash()YModule saveToFlash

Saves current settings in the nonvolatile memory of the module.

js
function saveToFlash()
cpp
int saveToFlash()
m
-(int) saveToFlash
pas
LongInt saveToFlash(): LongInt
vb
function saveToFlash() As Integer
cs
int saveToFlash()
java
int saveToFlash()
uwp
async Task<int> saveToFlash()
py
saveToFlash()
php
function saveToFlash()
ts
async saveToFlash(): Promise<number>
es
async saveToFlash()
dnp
int saveToFlash()
cp
int saveToFlash()
cmd
YModule target saveToFlash

Warning: the number of allowed save operations during a module life is limited (about 100000 cycles). Do not call this function within a loop.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

module→set_allSettings()
module→setAllSettings()
module.set_allSettings()module→set_allSettings()[module setAllSettings: ]module.set_allSettings()module.set_allSettings()module.set_allSettings()module.set_allSettings()module.set_allSettings()module.set_allSettings()module→set_allSettings()module.set_allSettings()module.set_allSettings()module.set_allSettings()module.set_allSettings()YModule set_allSettings

Restores all the settings of the device.

js
function set_allSettings(settings)
cpp
int set_allSettings(string settings)
m
-(int) setAllSettings: (NSData*) settings
pas
LongInt set_allSettings(settings: TByteArray): LongInt
vb
procedure set_allSettings(ByVal settings As Byte()
cs
int set_allSettings(byte[] settings)
java
int set_allSettings(byte[] settings)
uwp
async Task<int> set_allSettings(byte[] settings)
py
set_allSettings(settings)
php
function set_allSettings($settings)
ts
async set_allSettings(settings: Uint8Array): Promise<number>
es
async set_allSettings(settings)
dnp
int set_allSettings(byte[] settings)
cp
int set_allSettings(string settings)
cmd
YModule target set_allSettings settings

Useful to restore all the logical names and calibrations parameters of a module from a backup.Remember to call the saveToFlash() method of the module if the modifications must be kept.

Parameters :

settingsa binary buffer with all the settings.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

module→set_allSettingsAndFiles()
module→setAllSettingsAndFiles()
module.set_allSettingsAndFiles()module→set_allSettingsAndFiles()[module setAllSettingsAndFiles: ]module.set_allSettingsAndFiles()module.set_allSettingsAndFiles()module.set_allSettingsAndFiles()module.set_allSettingsAndFiles()module.set_allSettingsAndFiles()module.set_allSettingsAndFiles()module→set_allSettingsAndFiles()module.set_allSettingsAndFiles()module.set_allSettingsAndFiles()module.set_allSettingsAndFiles()module.set_allSettingsAndFiles()YModule set_allSettingsAndFiles

Restores all the settings and uploaded files to the module.

js
function set_allSettingsAndFiles(settings)
cpp
int set_allSettingsAndFiles(string settings)
m
-(int) setAllSettingsAndFiles: (NSData*) settings
pas
LongInt set_allSettingsAndFiles(settings: TByteArray): LongInt
vb
procedure set_allSettingsAndFiles(ByVal settings As Byte()
cs
int set_allSettingsAndFiles(byte[] settings)
java
int set_allSettingsAndFiles(byte[] settings)
uwp
async Task<int> set_allSettingsAndFiles(byte[] settings)
py
set_allSettingsAndFiles(settings)
php
function set_allSettingsAndFiles($settings)
ts
async set_allSettingsAndFiles(settings: Uint8Array): Promise<number>
es
async set_allSettingsAndFiles(settings)
dnp
int set_allSettingsAndFiles(byte[] settings)
cp
int set_allSettingsAndFiles(string settings)
cmd
YModule target set_allSettingsAndFiles settings

This method is useful to restore all the logical names and calibrations parameters, uploaded files etc. of a device from a backup. Remember to call the saveToFlash() method of the module if the modifications must be kept.

Parameters :

settingsa binary buffer with all the settings.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

module→set_beacon()
module→setBeacon()
module.set_beacon()module→set_beacon()[module setBeacon: ]module.set_beacon()module.set_beacon()module.set_beacon()module.set_beacon()module.set_beacon()module.set_beacon()module→set_beacon()module.set_beacon()module.set_beacon()module.set_beacon()module.set_beacon()YModule set_beacon

Turns on or off the module localization beacon.

js
function set_beacon(newval)
cpp
int set_beacon(Y_BEACON_enum newval)
m
-(int) setBeacon: (Y_BEACON_enum) newval
pas
integer set_beacon(newval: Integer): integer
vb
function set_beacon(ByVal newval As Integer) As Integer
cs
int set_beacon(int newval)
java
int set_beacon(int newval)
uwp
async Task<int> set_beacon(int newval)
py
set_beacon(newval)
php
function set_beacon($newval)
ts
async set_beacon(newval: YModule_Beacon): Promise<number>
es
async set_beacon(newval)
dnp
int set_beacon(int newval)
cp
int set_beacon(int newval)
cmd
YModule target set_beacon newval

Parameters :

newvaleither YModule.BEACON_OFF or YModule.BEACON_ON

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

module→set_logicalName()
module→setLogicalName()
module.set_logicalName()module→set_logicalName()[module setLogicalName: ]module.set_logicalName()module.set_logicalName()module.set_logicalName()module.set_logicalName()module.set_logicalName()module.set_logicalName()module→set_logicalName()module.set_logicalName()module.set_logicalName()module.set_logicalName()module.set_logicalName()YModule set_logicalName

Changes the logical name of the module.

js
function set_logicalName(newval)
cpp
int set_logicalName(string newval)
m
-(int) setLogicalName: (NSString*) newval
pas
integer set_logicalName(newval: string): integer
vb
function set_logicalName(ByVal newval As String) As Integer
cs
int set_logicalName(string newval)
java
int set_logicalName(String newval)
uwp
async Task<int> set_logicalName(string newval)
py
set_logicalName(newval)
php
function set_logicalName($newval)
ts
async set_logicalName(newval: string): Promise<number>
es
async set_logicalName(newval)
dnp
int set_logicalName(string newval)
cp
int set_logicalName(string newval)
cmd
YModule target set_logicalName newval

You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the logical name of the module

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

module→set_luminosity()
module→setLuminosity()
module.set_luminosity()module→set_luminosity()[module setLuminosity: ]module.set_luminosity()module.set_luminosity()module.set_luminosity()module.set_luminosity()module.set_luminosity()module.set_luminosity()module→set_luminosity()module.set_luminosity()module.set_luminosity()module.set_luminosity()module.set_luminosity()YModule set_luminosity

Changes the luminosity of the module informative leds.

js
function set_luminosity(newval)
cpp
int set_luminosity(int newval)
m
-(int) setLuminosity: (int) newval
pas
integer set_luminosity(newval: LongInt): integer
vb
function set_luminosity(ByVal newval As Integer) As Integer
cs
int set_luminosity(int newval)
java
int set_luminosity(int newval)
uwp
async Task<int> set_luminosity(int newval)
py
set_luminosity(newval)
php
function set_luminosity($newval)
ts
async set_luminosity(newval: number): Promise<number>
es
async set_luminosity(newval)
dnp
int set_luminosity(int newval)
cp
int set_luminosity(int newval)
cmd
YModule target set_luminosity newval

The parameter is a value between 0 and 100. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvalan integer corresponding to the luminosity of the module informative leds

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

module→set_userData()
module→setUserData()
module.set_userData()module→set_userData()[module setUserData: ]module.set_userData()module.set_userData()module.set_userData()module.set_userData()module.set_userData()module→set_userData()module.set_userData()module.set_userData()

Stores a user context provided as argument in the userData attribute of the function.

js
function set_userData(data)
cpp
void set_userData(void * data)
m
-(void) setUserData: (id) data
pas
set_userData(data: Tobject)
vb
procedure set_userData(ByVal data As Object)
cs
void set_userData(object data)
java
void set_userData(Object data)
py
set_userData(data)
php
function set_userData($data)
ts
async set_userData(data: object|null): Promise<void>
es
async set_userData(data)

This attribute is never touched by the API, and is at disposal of the caller to store a context.

Parameters :

dataany kind of object to be stored

module→set_userVar()
module→setUserVar()
module.set_userVar()module→set_userVar()[module setUserVar: ]module.set_userVar()module.set_userVar()module.set_userVar()module.set_userVar()module.set_userVar()module.set_userVar()module→set_userVar()module.set_userVar()module.set_userVar()module.set_userVar()module.set_userVar()YModule set_userVar

Stores a 32 bit value in the device RAM.

js
function set_userVar(newval)
cpp
int set_userVar(int newval)
m
-(int) setUserVar: (int) newval
pas
integer set_userVar(newval: LongInt): integer
vb
function set_userVar(ByVal newval As Integer) As Integer
cs
int set_userVar(int newval)
java
int set_userVar(int newval)
uwp
async Task<int> set_userVar(int newval)
py
set_userVar(newval)
php
function set_userVar($newval)
ts
async set_userVar(newval: number): Promise<number>
es
async set_userVar(newval)
dnp
int set_userVar(int newval)
cp
int set_userVar(int newval)
cmd
YModule target set_userVar newval

This attribute is at programmer disposal, should he need to store a state variable. On startup and after a device reboot, the value is always reset to zero.

Parameters :

newvalan integer

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

module→triggerConfigChangeCallback()module.triggerConfigChangeCallback()module→triggerConfigChangeCallback()[module triggerConfigChangeCallback]module.triggerConfigChangeCallback()module.triggerConfigChangeCallback()module.triggerConfigChangeCallback()module.triggerConfigChangeCallback()module.triggerConfigChangeCallback()module.triggerConfigChangeCallback()module→triggerConfigChangeCallback()module.triggerConfigChangeCallback()module.triggerConfigChangeCallback()module.triggerConfigChangeCallback()module.triggerConfigChangeCallback()YModule triggerConfigChangeCallback

Triggers a configuration change callback, to check if they are supported or not.

js
function triggerConfigChangeCallback()
cpp
int triggerConfigChangeCallback()
m
-(int) triggerConfigChangeCallback
pas
LongInt triggerConfigChangeCallback(): LongInt
vb
function triggerConfigChangeCallback() As Integer
cs
int triggerConfigChangeCallback()
java
int triggerConfigChangeCallback()
uwp
async Task<int> triggerConfigChangeCallback()
py
triggerConfigChangeCallback()
php
function triggerConfigChangeCallback()
ts
async triggerConfigChangeCallback(): Promise<number>
es
async triggerConfigChangeCallback()
dnp
int triggerConfigChangeCallback()
cp
int triggerConfigChangeCallback()
cmd
YModule target triggerConfigChangeCallback

module→triggerFirmwareUpdate()module.triggerFirmwareUpdate()module→triggerFirmwareUpdate()[module triggerFirmwareUpdate: ]module.triggerFirmwareUpdate()module.triggerFirmwareUpdate()module.triggerFirmwareUpdate()module.triggerFirmwareUpdate()module.triggerFirmwareUpdate()module.triggerFirmwareUpdate()module→triggerFirmwareUpdate()module.triggerFirmwareUpdate()module.triggerFirmwareUpdate()module.triggerFirmwareUpdate()module.triggerFirmwareUpdate()YModule triggerFirmwareUpdate

Schedules a module reboot into special firmware update mode.

js
function triggerFirmwareUpdate(secBeforeReboot)
cpp
int triggerFirmwareUpdate(int secBeforeReboot)
m
-(int) triggerFirmwareUpdate: (int) secBeforeReboot
pas
LongInt triggerFirmwareUpdate(secBeforeReboot: LongInt): LongInt
vb
function triggerFirmwareUpdate(ByVal secBeforeReboot As Integer) As Integer
cs
int triggerFirmwareUpdate(int secBeforeReboot)
java
int triggerFirmwareUpdate(int secBeforeReboot)
uwp
async Task<int> triggerFirmwareUpdate(int secBeforeReboot)
py
triggerFirmwareUpdate(secBeforeReboot)
php
function triggerFirmwareUpdate($secBeforeReboot)
ts
async triggerFirmwareUpdate(secBeforeReboot: number): Promise<number>
es
async triggerFirmwareUpdate(secBeforeReboot)
dnp
int triggerFirmwareUpdate(int secBeforeReboot)
cp
int triggerFirmwareUpdate(int secBeforeReboot)
cmd
YModule target triggerFirmwareUpdate secBeforeReboot

Parameters :

secBeforeRebootnumber of seconds before rebooting

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

module→updateFirmware()module.updateFirmware()module→updateFirmware()[module updateFirmware: ]module.updateFirmware()module.updateFirmware()module.updateFirmware()module.updateFirmware()module.updateFirmware()module.updateFirmware()module→updateFirmware()module.updateFirmware()module.updateFirmware()module.updateFirmware()module.updateFirmware()YModule updateFirmware

Prepares a firmware update of the module.

js
function updateFirmware(path)
cpp
YFirmwareUpdate updateFirmware(string path)
m
-(YFirmwareUpdate*) updateFirmware: (NSString*) path
pas
TYFirmwareUpdate updateFirmware(path: string): TYFirmwareUpdate
vb
function updateFirmware(ByVal path As String) As YFirmwareUpdate
cs
YFirmwareUpdate updateFirmware(string path)
java
YFirmwareUpdate updateFirmware(String path)
uwp
async Task<YFirmwareUpdate> updateFirmware(string path)
py
updateFirmware(path)
php
function updateFirmware($path)
ts
async updateFirmware(path: string): Promise<YFirmwareUpdate>
es
async updateFirmware(path)
dnp
YFirmwareUpdateProxy updateFirmware(string path)
cp
YFirmwareUpdateProxy* updateFirmware(string path)
cmd
YModule target updateFirmware path

This method returns a YFirmwareUpdate object which handles the firmware update process.

Parameters :

paththe path of the .byn file to use.

Returns :

a YFirmwareUpdate object or NULL on error.

module→updateFirmwareEx()module.updateFirmwareEx()module→updateFirmwareEx()[module updateFirmwareEx: ]module.updateFirmwareEx()module.updateFirmwareEx()module.updateFirmwareEx()module.updateFirmwareEx()module.updateFirmwareEx()module.updateFirmwareEx()module→updateFirmwareEx()module.updateFirmwareEx()module.updateFirmwareEx()module.updateFirmwareEx()module.updateFirmwareEx()YModule updateFirmwareEx

Prepares a firmware update of the module.

js
function updateFirmwareEx(path, force)
cpp
YFirmwareUpdate updateFirmwareEx(string path, bool force)
m
-(YFirmwareUpdate*) updateFirmwareEx: (NSString*) path
  : (bool) force
pas
TYFirmwareUpdate updateFirmwareEx(path: string, force: boolean): TYFirmwareUpdate
vb
function updateFirmwareEx(ByVal path As String,
  ByVal force As Boolean) As YFirmwareUpdate
cs
YFirmwareUpdate updateFirmwareEx(string path, bool force)
java
YFirmwareUpdate updateFirmwareEx(String path, boolean force)
uwp
async Task<YFirmwareUpdate> updateFirmwareEx(string path, bool force)
py
updateFirmwareEx(path, force)
php
function updateFirmwareEx($path, $force)
ts
async updateFirmwareEx(path: string, force: boolean): Promise<YFirmwareUpdate>
es
async updateFirmwareEx(path, force)
dnp
YFirmwareUpdateProxy updateFirmwareEx(string path, bool force)
cp
YFirmwareUpdateProxy* updateFirmwareEx(string path,
  bool force)
cmd
YModule target updateFirmwareEx path force

This method returns a YFirmwareUpdate object which handles the firmware update process.

Parameters :

paththe path of the .byn file to use.
forcetrue to force the firmware update even if some prerequisites appear not to be met

Returns :

a YFirmwareUpdate object or NULL on error.

module→wait_async()module.wait_async()module.wait_async()module.wait_async()

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

js
function wait_async(callback, context)
ts
wait_async(callback: Function, context: object)
es
wait_async(callback, context)

The callback function can therefore freely issue synchronous or asynchronous commands, without risking to block the JavaScript VM.

Parameters :

callbackcallback function that is invoked when all pending commands on the module are completed. The callback function receives two arguments: the caller-specific context object and the receiving function object.
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing.

24.3. Class YAccelerometer

Accelerometer control interface, available for instance in the Yocto-3D-V2 or the Yocto-Inclinometer

The YAccelerometer class allows you to read and configure Yoctopuce accelerometers. It inherits from YSensor class the core functions to read measurements, to register callback functions, and to access the autonomous datalogger. This class adds the possibility to access x, y and z components of the acceleration vector separately.

In order to use the functions described here, you should include:

es
in HTML: <script src="../../lib/yocto_accelerometer.js"></script>
in node.js: require('yoctolib-es2017/yocto_accelerometer.js');
js
<script type='text/javascript' src='yocto_accelerometer.js'></script>
cpp
#include "yocto_accelerometer.h"
m
#import "yocto_accelerometer.h"
pas
uses yocto_accelerometer;
vb
yocto_accelerometer.vb
cs
yocto_accelerometer.cs
java
import com.yoctopuce.YoctoAPI.YAccelerometer;
uwp
import com.yoctopuce.YoctoAPI.YAccelerometer;
py
from yocto_accelerometer import *
php
require_once('yocto_accelerometer.php');
ts
in HTML: import { YAccelerometer } from '../../dist/esm/yocto_accelerometer.js';
in Node.js: import { YAccelerometer } from 'yoctolib-cjs/yocto_accelerometer.js';
dnp
import YoctoProxyAPI.YAccelerometerProxy
cp
#include "yocto_accelerometer_proxy.h"
vi
YAccelerometer.vi
ml
import YoctoProxyAPI.YAccelerometerProxy
Global functions
YAccelerometer.FindAccelerometer(func)

Retrieves an accelerometer for a given identifier.

YAccelerometer.FindAccelerometerInContext(yctx, func)

Retrieves an accelerometer for a given identifier in a YAPI context.

YAccelerometer.FirstAccelerometer()

Starts the enumeration of accelerometers currently accessible.

YAccelerometer.FirstAccelerometerInContext(yctx)

Starts the enumeration of accelerometers currently accessible.

YAccelerometer.GetSimilarFunctions()

Enumerates all functions of type Accelerometer available on the devices currently reachable by the library, and returns their unique hardware ID.

YAccelerometer properties
accelerometer→AdvMode [writable]

Measuring mode used for the advertised value pushed to the parent hub.

accelerometer→AdvertisedValue [read-only]

Short string representing the current state of the function.

accelerometer→Bandwidth [writable]

Measure update frequency, measured in Hz.

accelerometer→FriendlyName [read-only]

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

accelerometer→FunctionId [read-only]

Hardware identifier of the sensor, without reference to the module.

accelerometer→HardwareId [read-only]

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

accelerometer→IsOnline [read-only]

Checks if the function is currently reachable.

accelerometer→LogFrequency [writable]

Datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

accelerometer→LogicalName [writable]

Logical name of the function.

accelerometer→ReportFrequency [writable]

Timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

accelerometer→Resolution [writable]

Resolution of the measured values.

accelerometer→SerialNumber [read-only]

Serial number of the module, as set by the factory.

YAccelerometer methods
accelerometer→calibrateFromPoints(rawValues, refValues)

Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.

accelerometer→clearCache()

Invalidates the cache.

accelerometer→describe()

Returns a short text that describes unambiguously the instance of the accelerometer in the form TYPE(NAME)=SERIAL.FUNCTIONID.

accelerometer→get_advMode()

Returns the measuring mode used for the advertised value pushed to the parent hub.

accelerometer→get_advertisedValue()

Returns the current value of the accelerometer (no more than 6 characters).

accelerometer→get_bandwidth()

Returns the measure update frequency, measured in Hz.

accelerometer→get_currentRawValue()

Returns the uncalibrated, unrounded raw value returned by the sensor, in g, as a floating point number.

accelerometer→get_currentValue()

Returns the current value of the acceleration, in g, as a floating point number.

accelerometer→get_dataLogger()

Returns the YDatalogger object of the device hosting the sensor.

accelerometer→get_errorMessage()

Returns the error message of the latest error with the accelerometer.

accelerometer→get_errorType()

Returns the numerical error code of the latest error with the accelerometer.

accelerometer→get_friendlyName()

Returns a global identifier of the accelerometer in the format MODULE_NAME.FUNCTION_NAME.

accelerometer→get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

accelerometer→get_functionId()

Returns the hardware identifier of the accelerometer, without reference to the module.

accelerometer→get_hardwareId()

Returns the unique hardware identifier of the accelerometer in the form SERIAL.FUNCTIONID.

accelerometer→get_highestValue()

Returns the maximal value observed for the acceleration since the device was started.

accelerometer→get_logFrequency()

Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

accelerometer→get_logicalName()

Returns the logical name of the accelerometer.

accelerometer→get_lowestValue()

Returns the minimal value observed for the acceleration since the device was started.

accelerometer→get_module()

Gets the YModule object for the device on which the function is located.

accelerometer→get_module_async(callback, context)

Gets the YModule object for the device on which the function is located (asynchronous version).

accelerometer→get_recordedData(startTime, endTime)

Retrieves a YDataSet object holding historical data for this sensor, for a specified time interval.

accelerometer→get_reportFrequency()

Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

accelerometer→get_resolution()

Returns the resolution of the measured values.

accelerometer→get_sensorState()

Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.

accelerometer→get_serialNumber()

Returns the serial number of the module, as set by the factory.

accelerometer→get_unit()

Returns the measuring unit for the acceleration.

accelerometer→get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

accelerometer→get_xValue()

Returns the X component of the acceleration, as a floating point number.

accelerometer→get_yValue()

Returns the Y component of the acceleration, as a floating point number.

accelerometer→get_zValue()

Returns the Z component of the acceleration, as a floating point number.

accelerometer→isOnline()

Checks if the accelerometer is currently reachable, without raising any error.

accelerometer→isOnline_async(callback, context)

Checks if the accelerometer is currently reachable, without raising any error (asynchronous version).

accelerometer→isReadOnly()

Test if the function is readOnly.

accelerometer→isSensorReady()

Checks if the sensor is currently able to provide an up-to-date measure.

accelerometer→load(msValidity)

Preloads the accelerometer cache with a specified validity duration.

accelerometer→loadAttribute(attrName)

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

accelerometer→loadCalibrationPoints(rawValues, refValues)

Retrieves error correction data points previously entered using the method calibrateFromPoints.

accelerometer→load_async(msValidity, callback, context)

Preloads the accelerometer cache with a specified validity duration (asynchronous version).

accelerometer→muteValueCallbacks()

Disables the propagation of every new advertised value to the parent hub.

accelerometer→nextAccelerometer()

Continues the enumeration of accelerometers started using yFirstAccelerometer().

accelerometer→registerTimedReportCallback(callback)

Registers the callback function that is invoked on every periodic timed notification.

accelerometer→registerValueCallback(callback)

Registers the callback function that is invoked on every change of advertised value.

accelerometer→set_advMode(newval)

Changes the measuring mode used for the advertised value pushed to the parent hub.

accelerometer→set_bandwidth(newval)

Changes the measure update frequency, measured in Hz.

accelerometer→set_highestValue(newval)

Changes the recorded maximal value observed.

accelerometer→set_logFrequency(newval)

Changes the datalogger recording frequency for this function.

accelerometer→set_logicalName(newval)

Changes the logical name of the accelerometer.

accelerometer→set_lowestValue(newval)

Changes the recorded minimal value observed.

accelerometer→set_reportFrequency(newval)

Changes the timed value notification frequency for this function.

accelerometer→set_resolution(newval)

Changes the resolution of the measured physical values.

accelerometer→set_userData(data)

Stores a user context provided as argument in the userData attribute of the function.

accelerometer→startDataLogger()

Starts the data logger on the device.

accelerometer→stopDataLogger()

Stops the datalogger on the device.

accelerometer→unmuteValueCallbacks()

Re-enables the propagation of every new advertised value to the parent hub.

accelerometer→wait_async(callback, context)

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

YAccelerometer.FindAccelerometer()
YAccelerometer.FindAccelerometer()
yFindAccelerometer()YAccelerometer::FindAccelerometer()[YAccelerometer FindAccelerometer: ]yFindAccelerometer()YAccelerometer.FindAccelerometer()YAccelerometer.FindAccelerometer()YAccelerometer.FindAccelerometer()YAccelerometer.FindAccelerometer()YAccelerometer.FindAccelerometer()YAccelerometer::FindAccelerometer()YAccelerometer.FindAccelerometer()YAccelerometer.FindAccelerometer()YAccelerometer.FindAccelerometer()YAccelerometer.FindAccelerometer()

Retrieves an accelerometer for a given identifier.

js
function yFindAccelerometer(func)
cpp
YAccelerometer* FindAccelerometer(string func)
m
+(YAccelerometer*) FindAccelerometer: (NSString*) func
pas
TYAccelerometer yFindAccelerometer(func: string): TYAccelerometer
vb
function FindAccelerometer(ByVal func As String) As YAccelerometer
cs
static YAccelerometer FindAccelerometer(string func)
java
static YAccelerometer FindAccelerometer(String func)
uwp
static YAccelerometer FindAccelerometer(string func)
py
FindAccelerometer(func)
php
function FindAccelerometer($func)
ts
static FindAccelerometer(func: string): YAccelerometer
es
static FindAccelerometer(func)
dnp
static YAccelerometerProxy FindAccelerometer(string func)
cp
static YAccelerometerProxy * FindAccelerometer(string func)

The identifier can be specified using several formats:

This function does not require that the accelerometer is online at the time it is invoked. The returned object is nevertheless valid. Use the method YAccelerometer.isOnline() to test if the accelerometer is indeed online at a given time. In case of ambiguity when looking for an accelerometer by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

If a call to this object's is_online() method returns FALSE although you are certain that the matching device is plugged, make sure that you did call registerHub() at application initialization time.

Parameters :

funca string that uniquely characterizes the accelerometer, for instance Y3DMK002.accelerometer.

Returns :

a YAccelerometer object allowing you to drive the accelerometer.

YAccelerometer.FindAccelerometerInContext()
YAccelerometer.FindAccelerometerInContext()
YAccelerometer.FindAccelerometerInContext()YAccelerometer.FindAccelerometerInContext()YAccelerometer.FindAccelerometerInContext()YAccelerometer.FindAccelerometerInContext()

Retrieves an accelerometer for a given identifier in a YAPI context.

java
static YAccelerometer FindAccelerometerInContext(YAPIContext yctx,
  String func)
uwp
static YAccelerometer FindAccelerometerInContext(YAPIContext yctx,
  string func)
ts
static FindAccelerometerInContext(yctx: YAPIContext, func: string): YAccelerometer
es
static FindAccelerometerInContext(yctx, func)

The identifier can be specified using several formats:

This function does not require that the accelerometer is online at the time it is invoked. The returned object is nevertheless valid. Use the method YAccelerometer.isOnline() to test if the accelerometer is indeed online at a given time. In case of ambiguity when looking for an accelerometer by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

Parameters :

yctxa YAPI context
funca string that uniquely characterizes the accelerometer, for instance Y3DMK002.accelerometer.

Returns :

a YAccelerometer object allowing you to drive the accelerometer.

YAccelerometer.FirstAccelerometer()
YAccelerometer.FirstAccelerometer()
yFirstAccelerometer()YAccelerometer::FirstAccelerometer()[YAccelerometer FirstAccelerometer]yFirstAccelerometer()YAccelerometer.FirstAccelerometer()YAccelerometer.FirstAccelerometer()YAccelerometer.FirstAccelerometer()YAccelerometer.FirstAccelerometer()YAccelerometer.FirstAccelerometer()YAccelerometer::FirstAccelerometer()YAccelerometer.FirstAccelerometer()YAccelerometer.FirstAccelerometer()

Starts the enumeration of accelerometers currently accessible.

js
function yFirstAccelerometer()
cpp
YAccelerometer * FirstAccelerometer()
m
+(YAccelerometer*) FirstAccelerometer
pas
TYAccelerometer yFirstAccelerometer(): TYAccelerometer
vb
function FirstAccelerometer() As YAccelerometer
cs
static YAccelerometer FirstAccelerometer()
java
static YAccelerometer FirstAccelerometer()
uwp
static YAccelerometer FirstAccelerometer()
py
FirstAccelerometer()
php
function FirstAccelerometer()
ts
static FirstAccelerometer(): YAccelerometer | null
es
static FirstAccelerometer()

Use the method YAccelerometer.nextAccelerometer() to iterate on next accelerometers.

Returns :

a pointer to a YAccelerometer object, corresponding to the first accelerometer currently online, or a null pointer if there are none.

YAccelerometer.FirstAccelerometerInContext()
YAccelerometer.FirstAccelerometerInContext()
YAccelerometer.FirstAccelerometerInContext()YAccelerometer.FirstAccelerometerInContext()YAccelerometer.FirstAccelerometerInContext()YAccelerometer.FirstAccelerometerInContext()

Starts the enumeration of accelerometers currently accessible.

java
static YAccelerometer FirstAccelerometerInContext(YAPIContext yctx)
uwp
static YAccelerometer FirstAccelerometerInContext(YAPIContext yctx)
ts
static FirstAccelerometerInContext(yctx: YAPIContext): YAccelerometer | null
es
static FirstAccelerometerInContext(yctx)

Use the method YAccelerometer.nextAccelerometer() to iterate on next accelerometers.

Parameters :

yctxa YAPI context.

Returns :

a pointer to a YAccelerometer object, corresponding to the first accelerometer currently online, or a null pointer if there are none.

YAccelerometer.GetSimilarFunctions()
YAccelerometer.GetSimilarFunctions()
YAccelerometer.GetSimilarFunctions()YAccelerometer.GetSimilarFunctions()

Enumerates all functions of type Accelerometer available on the devices currently reachable by the library, and returns their unique hardware ID.

dnp
static new string[] GetSimilarFunctions()
cp
static vector<string> GetSimilarFunctions()

Each of these IDs can be provided as argument to the method YAccelerometer.FindAccelerometer to obtain an object that can control the corresponding device.

Returns :

an array of strings, each string containing the unique hardwareId of a device function currently connected.

accelerometer→AdvModeaccelerometer.AdvMode

Measuring mode used for the advertised value pushed to the parent hub.

dnp
int AdvMode

Writable. Remember to call the saveToFlash() method of the module if the modification must be kept.

accelerometer→AdvertisedValueaccelerometer.AdvertisedValue

Short string representing the current state of the function.

dnp
string AdvertisedValue

accelerometer→Bandwidthaccelerometer.Bandwidth

Measure update frequency, measured in Hz.

dnp
int Bandwidth

Writable. When the frequency is lower, the device performs averaging. Remember to call the saveToFlash() method of the module if the modification must be kept.

accelerometer→FriendlyNameaccelerometer.FriendlyName

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

dnp
string FriendlyName

The returned string uses the logical names of the module and of the function if they are defined, otherwise the serial number of the module and the hardware identifier of the function (for example: MyCustomName.relay1)

accelerometer→FunctionIdaccelerometer.FunctionId

Hardware identifier of the sensor, without reference to the module.

dnp
string FunctionId

For example relay1

accelerometer→HardwareIdaccelerometer.HardwareId

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

dnp
string HardwareId

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the function (for example RELAYLO1-123456.relay1).

accelerometer→IsOnlineaccelerometer.IsOnline

Checks if the function is currently reachable.

dnp
bool IsOnline

If there is a cached value for the function in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the function.

accelerometer→LogFrequencyaccelerometer.LogFrequency

Datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

dnp
string LogFrequency

Writable. Changes the datalogger recording frequency for this function. The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (eg. "4/h"). To disable recording for this function, use the value "OFF". Note that setting the datalogger recording frequency to a greater value than the sensor native sampling frequency is useless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

accelerometer→LogicalNameaccelerometer.LogicalName

Logical name of the function.

dnp
string LogicalName

Writable. You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

accelerometer→ReportFrequencyaccelerometer.ReportFrequency

Timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

dnp
string ReportFrequency

Writable. Changes the timed value notification frequency for this function. The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (e.g. "4/h"). To disable timed value notifications for this function, use the value "OFF". Note that setting the timed value notification frequency to a greater value than the sensor native sampling frequency is unless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

accelerometer→Resolutionaccelerometer.Resolution

Resolution of the measured values.

dnp
double Resolution

The resolution corresponds to the numerical precision of the measures, which is not always the same as the actual precision of the sensor. Remember to call the saveToFlash() method of the module if the modification must be kept.

Writable. Changes the resolution of the measured physical values. The resolution corresponds to the numerical precision when displaying value. It does not change the precision of the measure itself. Remember to call the saveToFlash() method of the module if the modification must be kept.

accelerometer→SerialNumberaccelerometer.SerialNumber

Serial number of the module, as set by the factory.

dnp
string SerialNumber

accelerometer→calibrateFromPoints()accelerometer.calibrateFromPoints()accelerometer→calibrateFromPoints()[accelerometer calibrateFromPoints: ]accelerometer.calibrateFromPoints()accelerometer.calibrateFromPoints()accelerometer.calibrateFromPoints()accelerometer.calibrateFromPoints()accelerometer.calibrateFromPoints()accelerometer.calibrateFromPoints()accelerometer→calibrateFromPoints()accelerometer.calibrateFromPoints()accelerometer.calibrateFromPoints()accelerometer.calibrateFromPoints()accelerometer.calibrateFromPoints()YAccelerometer calibrateFromPoints

Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.

js
function calibrateFromPoints(rawValues, refValues)
cpp
int calibrateFromPoints(vector<double> rawValues,
  vector<double> refValues)
m
-(int) calibrateFromPoints: (NSMutableArray*) rawValues
  : (NSMutableArray*) refValues
pas
LongInt calibrateFromPoints(rawValues: TDoubleArray,
  refValues: TDoubleArray): LongInt
vb
procedure calibrateFromPoints(ByVal rawValues As List(Of)
cs
int calibrateFromPoints(List<double> rawValues,
  List<double> refValues)
java
int calibrateFromPoints(ArrayList<Double> rawValues,
  ArrayList<Double> refValues)
uwp
async Task<int> calibrateFromPoints(List<double> rawValues,
  List<double> refValues)
py
calibrateFromPoints(rawValues, refValues)
php
function calibrateFromPoints($rawValues, $refValues)
ts
async calibrateFromPoints(rawValues: number[], refValues: number[]): Promise<number>
es
async calibrateFromPoints(rawValues, refValues)
dnp
int calibrateFromPoints(double[] rawValues,
  double[] refValues)
cp
int calibrateFromPoints(vector<double> rawValues,
  vector<double> refValues)
cmd
YAccelerometer target calibrateFromPoints rawValues refValues

It is possible to configure up to five correction points. Correction points must be provided in ascending order, and be in the range of the sensor. The device will automatically perform a linear interpolation of the error correction between specified points. Remember to call the saveToFlash() method of the module if the modification must be kept.

For more information on advanced capabilities to refine the calibration of sensors, please contact support@yoctopuce.com.

Parameters :

rawValuesarray of floating point numbers, corresponding to the raw values returned by the sensor for the correction points.
refValuesarray of floating point numbers, corresponding to the corrected values for the correction points.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→clearCache()accelerometer.clearCache()accelerometer→clearCache()[accelerometer clearCache]accelerometer.clearCache()accelerometer.clearCache()accelerometer.clearCache()accelerometer.clearCache()accelerometer.clearCache()accelerometer→clearCache()accelerometer.clearCache()accelerometer.clearCache()

Invalidates the cache.

js
function clearCache()
cpp
void clearCache()
m
-(void) clearCache
pas
clearCache()
vb
procedure clearCache()
cs
void clearCache()
java
void clearCache()
py
clearCache()
php
function clearCache()
ts
async clearCache(): Promise<void>
es
async clearCache()

Invalidates the cache of the accelerometer attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.

accelerometer→describe()accelerometer.describe()accelerometer→describe()[accelerometer describe]accelerometer.describe()accelerometer.describe()accelerometer.describe()accelerometer.describe()accelerometer.describe()accelerometer→describe()accelerometer.describe()accelerometer.describe()

Returns a short text that describes unambiguously the instance of the accelerometer in the form TYPE(NAME)=SERIAL.FUNCTIONID.

js
function describe()
cpp
string describe()
m
-(NSString*) describe
pas
string describe(): string
vb
function describe() As String
cs
string describe()
java
String describe()
py
describe()
php
function describe()
ts
async describe(): Promise<string>
es
async describe()

More precisely, TYPE is the type of the function, NAME it the name used for the first access to the function, SERIAL is the serial number of the module if the module is connected or "unresolved", and FUNCTIONID is the hardware identifier of the function if the module is connected. For example, this method returns Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1 if the module is already connected or Relay(BadCustomeName.relay1)=unresolved if the module has not yet been connected. This method does not trigger any USB or TCP transaction and can therefore be used in a debugger.

Returns :

a string that describes the accelerometer (ex: Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1)

accelerometer→get_advMode()
accelerometer→advMode()
accelerometer.get_advMode()accelerometer→get_advMode()[accelerometer advMode]accelerometer.get_advMode()accelerometer.get_advMode()accelerometer.get_advMode()accelerometer.get_advMode()accelerometer.get_advMode()accelerometer.get_advMode()accelerometer→get_advMode()accelerometer.get_advMode()accelerometer.get_advMode()accelerometer.get_advMode()accelerometer.get_advMode()YAccelerometer get_advMode

Returns the measuring mode used for the advertised value pushed to the parent hub.

js
function get_advMode()
cpp
Y_ADVMODE_enum get_advMode()
m
-(Y_ADVMODE_enum) advMode
pas
Integer get_advMode(): Integer
vb
function get_advMode() As Integer
cs
int get_advMode()
java
int get_advMode()
uwp
async Task<int> get_advMode()
py
get_advMode()
php
function get_advMode()
ts
async get_advMode(): Promise<YSensor_AdvMode>
es
async get_advMode()
dnp
int get_advMode()
cp
int get_advMode()
cmd
YAccelerometer target get_advMode

Returns :

a value among YAccelerometer.ADVMODE_IMMEDIATE, YAccelerometer.ADVMODE_PERIOD_AVG, YAccelerometer.ADVMODE_PERIOD_MIN and YAccelerometer.ADVMODE_PERIOD_MAX corresponding to the measuring mode used for the advertised value pushed to the parent hub

On failure, throws an exception or returns YAccelerometer.ADVMODE_INVALID.

accelerometer→get_advertisedValue()
accelerometer→advertisedValue()
accelerometer.get_advertisedValue()accelerometer→get_advertisedValue()[accelerometer advertisedValue]accelerometer.get_advertisedValue()accelerometer.get_advertisedValue()accelerometer.get_advertisedValue()accelerometer.get_advertisedValue()accelerometer.get_advertisedValue()accelerometer.get_advertisedValue()accelerometer→get_advertisedValue()accelerometer.get_advertisedValue()accelerometer.get_advertisedValue()accelerometer.get_advertisedValue()accelerometer.get_advertisedValue()YAccelerometer get_advertisedValue

Returns the current value of the accelerometer (no more than 6 characters).

js
function get_advertisedValue()
cpp
string get_advertisedValue()
m
-(NSString*) advertisedValue
pas
string get_advertisedValue(): string
vb
function get_advertisedValue() As String
cs
string get_advertisedValue()
java
String get_advertisedValue()
uwp
async Task<string> get_advertisedValue()
py
get_advertisedValue()
php
function get_advertisedValue()
ts
async get_advertisedValue(): Promise<string>
es
async get_advertisedValue()
dnp
string get_advertisedValue()
cp
string get_advertisedValue()
cmd
YAccelerometer target get_advertisedValue

Returns :

a string corresponding to the current value of the accelerometer (no more than 6 characters).

On failure, throws an exception or returns YAccelerometer.ADVERTISEDVALUE_INVALID.

accelerometer→get_bandwidth()
accelerometer→bandwidth()
accelerometer.get_bandwidth()accelerometer→get_bandwidth()[accelerometer bandwidth]accelerometer.get_bandwidth()accelerometer.get_bandwidth()accelerometer.get_bandwidth()accelerometer.get_bandwidth()accelerometer.get_bandwidth()accelerometer.get_bandwidth()accelerometer→get_bandwidth()accelerometer.get_bandwidth()accelerometer.get_bandwidth()accelerometer.get_bandwidth()accelerometer.get_bandwidth()YAccelerometer get_bandwidth

Returns the measure update frequency, measured in Hz.

js
function get_bandwidth()
cpp
int get_bandwidth()
m
-(int) bandwidth
pas
LongInt get_bandwidth(): LongInt
vb
function get_bandwidth() As Integer
cs
int get_bandwidth()
java
int get_bandwidth()
uwp
async Task<int> get_bandwidth()
py
get_bandwidth()
php
function get_bandwidth()
ts
async get_bandwidth(): Promise<number>
es
async get_bandwidth()
dnp
int get_bandwidth()
cp
int get_bandwidth()
cmd
YAccelerometer target get_bandwidth

Returns :

an integer corresponding to the measure update frequency, measured in Hz

On failure, throws an exception or returns YAccelerometer.BANDWIDTH_INVALID.

accelerometer→get_currentRawValue()
accelerometer→currentRawValue()
accelerometer.get_currentRawValue()accelerometer→get_currentRawValue()[accelerometer currentRawValue]accelerometer.get_currentRawValue()accelerometer.get_currentRawValue()accelerometer.get_currentRawValue()accelerometer.get_currentRawValue()accelerometer.get_currentRawValue()accelerometer.get_currentRawValue()accelerometer→get_currentRawValue()accelerometer.get_currentRawValue()accelerometer.get_currentRawValue()accelerometer.get_currentRawValue()accelerometer.get_currentRawValue()YAccelerometer get_currentRawValue

Returns the uncalibrated, unrounded raw value returned by the sensor, in g, as a floating point number.

js
function get_currentRawValue()
cpp
double get_currentRawValue()
m
-(double) currentRawValue
pas
double get_currentRawValue(): double
vb
function get_currentRawValue() As Double
cs
double get_currentRawValue()
java
double get_currentRawValue()
uwp
async Task<double> get_currentRawValue()
py
get_currentRawValue()
php
function get_currentRawValue()
ts
async get_currentRawValue(): Promise<number>
es
async get_currentRawValue()
dnp
double get_currentRawValue()
cp
double get_currentRawValue()
cmd
YAccelerometer target get_currentRawValue

Returns :

a floating point number corresponding to the uncalibrated, unrounded raw value returned by the sensor, in g, as a floating point number

On failure, throws an exception or returns YAccelerometer.CURRENTRAWVALUE_INVALID.

accelerometer→get_currentValue()
accelerometer→currentValue()
accelerometer.get_currentValue()accelerometer→get_currentValue()[accelerometer currentValue]accelerometer.get_currentValue()accelerometer.get_currentValue()accelerometer.get_currentValue()accelerometer.get_currentValue()accelerometer.get_currentValue()accelerometer.get_currentValue()accelerometer→get_currentValue()accelerometer.get_currentValue()accelerometer.get_currentValue()accelerometer.get_currentValue()accelerometer.get_currentValue()YAccelerometer get_currentValue

Returns the current value of the acceleration, in g, as a floating point number.

js
function get_currentValue()
cpp
double get_currentValue()
m
-(double) currentValue
pas
double get_currentValue(): double
vb
function get_currentValue() As Double
cs
double get_currentValue()
java
double get_currentValue()
uwp
async Task<double> get_currentValue()
py
get_currentValue()
php
function get_currentValue()
ts
async get_currentValue(): Promise<number>
es
async get_currentValue()
dnp
double get_currentValue()
cp
double get_currentValue()
cmd
YAccelerometer target get_currentValue

Note that a get_currentValue() call will *not* start a measure in the device, it will just return the last measure that occurred in the device. Indeed, internally, each Yoctopuce devices is continuously making measurements at a hardware specific frequency.

If continuously calling get_currentValue() leads you to performances issues, then you might consider to switch to callback programming model. Check the "advanced programming" chapter in in your device user manual for more information.

Returns :

a floating point number corresponding to the current value of the acceleration, in g, as a floating point number

On failure, throws an exception or returns YAccelerometer.CURRENTVALUE_INVALID.

accelerometer→get_dataLogger()
accelerometer→dataLogger()
accelerometer.get_dataLogger()accelerometer→get_dataLogger()[accelerometer dataLogger]accelerometer.get_dataLogger()accelerometer.get_dataLogger()accelerometer.get_dataLogger()accelerometer.get_dataLogger()accelerometer.get_dataLogger()accelerometer.get_dataLogger()accelerometer→get_dataLogger()accelerometer.get_dataLogger()accelerometer.get_dataLogger()accelerometer.get_dataLogger()accelerometer.get_dataLogger()

Returns the YDatalogger object of the device hosting the sensor.

js
function get_dataLogger()
cpp
YDataLogger* get_dataLogger()
m
-(YDataLogger*) dataLogger
pas
TYDataLogger get_dataLogger(): TYDataLogger
vb
function get_dataLogger() As YDataLogger
cs
YDataLogger get_dataLogger()
java
YDataLogger get_dataLogger()
uwp
async Task<YDataLogger> get_dataLogger()
py
get_dataLogger()
php
function get_dataLogger()
ts
async get_dataLogger(): Promise<YDataLogger | null>
es
async get_dataLogger()
dnp
YDataLoggerProxy get_dataLogger()
cp
YDataLoggerProxy* get_dataLogger()

This method returns an object that can control global parameters of the data logger. The returned object should not be freed.

Returns :

an YDatalogger object, or null on error.

accelerometer→get_errorMessage()
accelerometer→errorMessage()
accelerometer.get_errorMessage()accelerometer→get_errorMessage()[accelerometer errorMessage]accelerometer.get_errorMessage()accelerometer.get_errorMessage()accelerometer.get_errorMessage()accelerometer.get_errorMessage()accelerometer.get_errorMessage()accelerometer→get_errorMessage()accelerometer.get_errorMessage()accelerometer.get_errorMessage()

Returns the error message of the latest error with the accelerometer.

js
function get_errorMessage()
cpp
string get_errorMessage()
m
-(NSString*) errorMessage
pas
string get_errorMessage(): string
vb
function get_errorMessage() As String
cs
string get_errorMessage()
java
String get_errorMessage()
py
get_errorMessage()
php
function get_errorMessage()
ts
get_errorMessage(): string
es
get_errorMessage()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a string corresponding to the latest error message that occured while using the accelerometer object

accelerometer→get_errorType()
accelerometer→errorType()
accelerometer.get_errorType()accelerometer→get_errorType()[accelerometer errorType]accelerometer.get_errorType()accelerometer.get_errorType()accelerometer.get_errorType()accelerometer.get_errorType()accelerometer.get_errorType()accelerometer→get_errorType()accelerometer.get_errorType()accelerometer.get_errorType()

Returns the numerical error code of the latest error with the accelerometer.

js
function get_errorType()
cpp
YRETCODE get_errorType()
m
-(YRETCODE) errorType
pas
YRETCODE get_errorType(): YRETCODE
vb
function get_errorType() As YRETCODE
cs
YRETCODE get_errorType()
java
int get_errorType()
py
get_errorType()
php
function get_errorType()
ts
get_errorType(): number
es
get_errorType()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a number corresponding to the code of the latest error that occurred while using the accelerometer object

accelerometer→get_friendlyName()
accelerometer→friendlyName()
accelerometer.get_friendlyName()accelerometer→get_friendlyName()[accelerometer friendlyName]accelerometer.get_friendlyName()accelerometer.get_friendlyName()accelerometer.get_friendlyName()accelerometer→get_friendlyName()accelerometer.get_friendlyName()accelerometer.get_friendlyName()accelerometer.get_friendlyName()accelerometer.get_friendlyName()

Returns a global identifier of the accelerometer in the format MODULE_NAME.FUNCTION_NAME.

js
function get_friendlyName()
cpp
string get_friendlyName()
m
-(NSString*) friendlyName
cs
string get_friendlyName()
java
String get_friendlyName()
py
get_friendlyName()
php
function get_friendlyName()
ts
async get_friendlyName(): Promise<string>
es
async get_friendlyName()
dnp
string get_friendlyName()
cp
string get_friendlyName()

The returned string uses the logical names of the module and of the accelerometer if they are defined, otherwise the serial number of the module and the hardware identifier of the accelerometer (for example: MyCustomName.relay1)

Returns :

a string that uniquely identifies the accelerometer using logical names (ex: MyCustomName.relay1)

On failure, throws an exception or returns YAccelerometer.FRIENDLYNAME_INVALID.

accelerometer→get_functionDescriptor()
accelerometer→functionDescriptor()
accelerometer.get_functionDescriptor()accelerometer→get_functionDescriptor()[accelerometer functionDescriptor]accelerometer.get_functionDescriptor()accelerometer.get_functionDescriptor()accelerometer.get_functionDescriptor()accelerometer.get_functionDescriptor()accelerometer.get_functionDescriptor()accelerometer→get_functionDescriptor()accelerometer.get_functionDescriptor()accelerometer.get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

js
function get_functionDescriptor()
cpp
YFUN_DESCR get_functionDescriptor()
m
-(YFUN_DESCR) functionDescriptor
pas
YFUN_DESCR get_functionDescriptor(): YFUN_DESCR
vb
function get_functionDescriptor() As YFUN_DESCR
cs
YFUN_DESCR get_functionDescriptor()
java
String get_functionDescriptor()
py
get_functionDescriptor()
php
function get_functionDescriptor()
ts
async get_functionDescriptor(): Promise<string>
es
async get_functionDescriptor()

This identifier can be used to test if two instances of YFunction reference the same physical function on the same physical device.

Returns :

an identifier of type YFUN_DESCR.

If the function has never been contacted, the returned value is Y$CLASSNAME$.FUNCTIONDESCRIPTOR_INVALID.

accelerometer→get_functionId()
accelerometer→functionId()
accelerometer.get_functionId()accelerometer→get_functionId()[accelerometer functionId]accelerometer.get_functionId()accelerometer.get_functionId()accelerometer.get_functionId()accelerometer.get_functionId()accelerometer→get_functionId()accelerometer.get_functionId()accelerometer.get_functionId()accelerometer.get_functionId()accelerometer.get_functionId()

Returns the hardware identifier of the accelerometer, without reference to the module.

js
function get_functionId()
cpp
string get_functionId()
m
-(NSString*) functionId
vb
function get_functionId() As String
cs
string get_functionId()
java
String get_functionId()
py
get_functionId()
php
function get_functionId()
ts
async get_functionId(): Promise<string>
es
async get_functionId()
dnp
string get_functionId()
cp
string get_functionId()

For example relay1

Returns :

a string that identifies the accelerometer (ex: relay1)

On failure, throws an exception or returns YAccelerometer.FUNCTIONID_INVALID.

accelerometer→get_hardwareId()
accelerometer→hardwareId()
accelerometer.get_hardwareId()accelerometer→get_hardwareId()[accelerometer hardwareId]accelerometer.get_hardwareId()accelerometer.get_hardwareId()accelerometer.get_hardwareId()accelerometer.get_hardwareId()accelerometer→get_hardwareId()accelerometer.get_hardwareId()accelerometer.get_hardwareId()accelerometer.get_hardwareId()accelerometer.get_hardwareId()

Returns the unique hardware identifier of the accelerometer in the form SERIAL.FUNCTIONID.

js
function get_hardwareId()
cpp
string get_hardwareId()
m
-(NSString*) hardwareId
vb
function get_hardwareId() As String
cs
string get_hardwareId()
java
String get_hardwareId()
py
get_hardwareId()
php
function get_hardwareId()
ts
async get_hardwareId(): Promise<string>
es
async get_hardwareId()
dnp
string get_hardwareId()
cp
string get_hardwareId()

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the accelerometer (for example RELAYLO1-123456.relay1).

Returns :

a string that uniquely identifies the accelerometer (ex: RELAYLO1-123456.relay1)

On failure, throws an exception or returns YAccelerometer.HARDWAREID_INVALID.

accelerometer→get_highestValue()
accelerometer→highestValue()
accelerometer.get_highestValue()accelerometer→get_highestValue()[accelerometer highestValue]accelerometer.get_highestValue()accelerometer.get_highestValue()accelerometer.get_highestValue()accelerometer.get_highestValue()accelerometer.get_highestValue()accelerometer.get_highestValue()accelerometer→get_highestValue()accelerometer.get_highestValue()accelerometer.get_highestValue()accelerometer.get_highestValue()accelerometer.get_highestValue()YAccelerometer get_highestValue

Returns the maximal value observed for the acceleration since the device was started.

js
function get_highestValue()
cpp
double get_highestValue()
m
-(double) highestValue
pas
double get_highestValue(): double
vb
function get_highestValue() As Double
cs
double get_highestValue()
java
double get_highestValue()
uwp
async Task<double> get_highestValue()
py
get_highestValue()
php
function get_highestValue()
ts
async get_highestValue(): Promise<number>
es
async get_highestValue()
dnp
double get_highestValue()
cp
double get_highestValue()
cmd
YAccelerometer target get_highestValue

Can be reset to an arbitrary value thanks to set_highestValue().

Returns :

a floating point number corresponding to the maximal value observed for the acceleration since the device was started

On failure, throws an exception or returns YAccelerometer.HIGHESTVALUE_INVALID.

accelerometer→get_logFrequency()
accelerometer→logFrequency()
accelerometer.get_logFrequency()accelerometer→get_logFrequency()[accelerometer logFrequency]accelerometer.get_logFrequency()accelerometer.get_logFrequency()accelerometer.get_logFrequency()accelerometer.get_logFrequency()accelerometer.get_logFrequency()accelerometer.get_logFrequency()accelerometer→get_logFrequency()accelerometer.get_logFrequency()accelerometer.get_logFrequency()accelerometer.get_logFrequency()accelerometer.get_logFrequency()YAccelerometer get_logFrequency

Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

js
function get_logFrequency()
cpp
string get_logFrequency()
m
-(NSString*) logFrequency
pas
string get_logFrequency(): string
vb
function get_logFrequency() As String
cs
string get_logFrequency()
java
String get_logFrequency()
uwp
async Task<string> get_logFrequency()
py
get_logFrequency()
php
function get_logFrequency()
ts
async get_logFrequency(): Promise<string>
es
async get_logFrequency()
dnp
string get_logFrequency()
cp
string get_logFrequency()
cmd
YAccelerometer target get_logFrequency

Returns :

a string corresponding to the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory

On failure, throws an exception or returns YAccelerometer.LOGFREQUENCY_INVALID.

accelerometer→get_logicalName()
accelerometer→logicalName()
accelerometer.get_logicalName()accelerometer→get_logicalName()[accelerometer logicalName]accelerometer.get_logicalName()accelerometer.get_logicalName()accelerometer.get_logicalName()accelerometer.get_logicalName()accelerometer.get_logicalName()accelerometer.get_logicalName()accelerometer→get_logicalName()accelerometer.get_logicalName()accelerometer.get_logicalName()accelerometer.get_logicalName()accelerometer.get_logicalName()YAccelerometer get_logicalName

Returns the logical name of the accelerometer.

js
function get_logicalName()
cpp
string get_logicalName()
m
-(NSString*) logicalName
pas
string get_logicalName(): string
vb
function get_logicalName() As String
cs
string get_logicalName()
java
String get_logicalName()
uwp
async Task<string> get_logicalName()
py
get_logicalName()
php
function get_logicalName()
ts
async get_logicalName(): Promise<string>
es
async get_logicalName()
dnp
string get_logicalName()
cp
string get_logicalName()
cmd
YAccelerometer target get_logicalName

Returns :

a string corresponding to the logical name of the accelerometer.

On failure, throws an exception or returns YAccelerometer.LOGICALNAME_INVALID.

accelerometer→get_lowestValue()
accelerometer→lowestValue()
accelerometer.get_lowestValue()accelerometer→get_lowestValue()[accelerometer lowestValue]accelerometer.get_lowestValue()accelerometer.get_lowestValue()accelerometer.get_lowestValue()accelerometer.get_lowestValue()accelerometer.get_lowestValue()accelerometer.get_lowestValue()accelerometer→get_lowestValue()accelerometer.get_lowestValue()accelerometer.get_lowestValue()accelerometer.get_lowestValue()accelerometer.get_lowestValue()YAccelerometer get_lowestValue

Returns the minimal value observed for the acceleration since the device was started.

js
function get_lowestValue()
cpp
double get_lowestValue()
m
-(double) lowestValue
pas
double get_lowestValue(): double
vb
function get_lowestValue() As Double
cs
double get_lowestValue()
java
double get_lowestValue()
uwp
async Task<double> get_lowestValue()
py
get_lowestValue()
php
function get_lowestValue()
ts
async get_lowestValue(): Promise<number>
es
async get_lowestValue()
dnp
double get_lowestValue()
cp
double get_lowestValue()
cmd
YAccelerometer target get_lowestValue

Can be reset to an arbitrary value thanks to set_lowestValue().

Returns :

a floating point number corresponding to the minimal value observed for the acceleration since the device was started

On failure, throws an exception or returns YAccelerometer.LOWESTVALUE_INVALID.

accelerometer→get_module()
accelerometer→module()
accelerometer.get_module()accelerometer→get_module()[accelerometer module]accelerometer.get_module()accelerometer.get_module()accelerometer.get_module()accelerometer.get_module()accelerometer.get_module()accelerometer→get_module()accelerometer.get_module()accelerometer.get_module()accelerometer.get_module()accelerometer.get_module()

Gets the YModule object for the device on which the function is located.

js
function get_module()
cpp
YModule * get_module()
m
-(YModule*) module
pas
TYModule get_module(): TYModule
vb
function get_module() As YModule
cs
YModule get_module()
java
YModule get_module()
py
get_module()
php
function get_module()
ts
async get_module(): Promise<YModule>
es
async get_module()
dnp
YModuleProxy get_module()
cp
YModuleProxy * get_module()

If the function cannot be located on any module, the returned instance of YModule is not shown as on-line.

Returns :

an instance of YModule

accelerometer→get_module_async()
accelerometer→module_async()
accelerometer.get_module_async()

Gets the YModule object for the device on which the function is located (asynchronous version).

js
function get_module_async(callback, context)

If the function cannot be located on any module, the returned YModule object does not show as on-line.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking Firefox JavaScript VM that does not implement context switching during blocking I/O calls. See the documentation section on asynchronous JavasSript calls for more details.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the requested YModule object
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

accelerometer→get_recordedData()
accelerometer→recordedData()
accelerometer.get_recordedData()accelerometer→get_recordedData()[accelerometer recordedData: ]accelerometer.get_recordedData()accelerometer.get_recordedData()accelerometer.get_recordedData()accelerometer.get_recordedData()accelerometer.get_recordedData()accelerometer.get_recordedData()accelerometer→get_recordedData()accelerometer.get_recordedData()accelerometer.get_recordedData()accelerometer.get_recordedData()accelerometer.get_recordedData()YAccelerometer get_recordedData

Retrieves a YDataSet object holding historical data for this sensor, for a specified time interval.

js
function get_recordedData(startTime, endTime)
cpp
YDataSet get_recordedData(double startTime, double endTime)
m
-(YDataSet*) recordedData: (double) startTime
  : (double) endTime
pas
TYDataSet get_recordedData(startTime: double, endTime: double): TYDataSet
vb
function get_recordedData(ByVal startTime As Double,
  ByVal endTime As Double) As YDataSet
cs
YDataSet get_recordedData(double startTime, double endTime)
java
YDataSet get_recordedData(double startTime, double endTime)
uwp
async Task<YDataSet> get_recordedData(double startTime,
  double endTime)
py
get_recordedData(startTime, endTime)
php
function get_recordedData($startTime, $endTime)
ts
async get_recordedData(startTime: number, endTime: number): Promise<YDataSet>
es
async get_recordedData(startTime, endTime)
dnp
YDataSetProxy get_recordedData(double startTime,
  double endTime)
cp
YDataSetProxy* get_recordedData(double startTime,
  double endTime)
cmd
YAccelerometer target get_recordedData startTime endTime

The measures will be retrieved from the data logger, which must have been turned on at the desired time. See the documentation of the YDataSet class for information on how to get an overview of the recorded data, and how to load progressively a large set of measures from the data logger.

This function only works if the device uses a recent firmware, as YDataSet objects are not supported by firmwares older than version 13000.

Parameters :

startTimethe start of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without initial limit.
endTimethe end of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without ending limit.

Returns :

an instance of YDataSet, providing access to historical data. Past measures can be loaded progressively using methods from the YDataSet object.

accelerometer→get_reportFrequency()
accelerometer→reportFrequency()
accelerometer.get_reportFrequency()accelerometer→get_reportFrequency()[accelerometer reportFrequency]accelerometer.get_reportFrequency()accelerometer.get_reportFrequency()accelerometer.get_reportFrequency()accelerometer.get_reportFrequency()accelerometer.get_reportFrequency()accelerometer.get_reportFrequency()accelerometer→get_reportFrequency()accelerometer.get_reportFrequency()accelerometer.get_reportFrequency()accelerometer.get_reportFrequency()accelerometer.get_reportFrequency()YAccelerometer get_reportFrequency

Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

js
function get_reportFrequency()
cpp
string get_reportFrequency()
m
-(NSString*) reportFrequency
pas
string get_reportFrequency(): string
vb
function get_reportFrequency() As String
cs
string get_reportFrequency()
java
String get_reportFrequency()
uwp
async Task<string> get_reportFrequency()
py
get_reportFrequency()
php
function get_reportFrequency()
ts
async get_reportFrequency(): Promise<string>
es
async get_reportFrequency()
dnp
string get_reportFrequency()
cp
string get_reportFrequency()
cmd
YAccelerometer target get_reportFrequency

Returns :

a string corresponding to the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function

On failure, throws an exception or returns YAccelerometer.REPORTFREQUENCY_INVALID.

accelerometer→get_resolution()
accelerometer→resolution()
accelerometer.get_resolution()accelerometer→get_resolution()[accelerometer resolution]accelerometer.get_resolution()accelerometer.get_resolution()accelerometer.get_resolution()accelerometer.get_resolution()accelerometer.get_resolution()accelerometer.get_resolution()accelerometer→get_resolution()accelerometer.get_resolution()accelerometer.get_resolution()accelerometer.get_resolution()accelerometer.get_resolution()YAccelerometer get_resolution

Returns the resolution of the measured values.

js
function get_resolution()
cpp
double get_resolution()
m
-(double) resolution
pas
double get_resolution(): double
vb
function get_resolution() As Double
cs
double get_resolution()
java
double get_resolution()
uwp
async Task<double> get_resolution()
py
get_resolution()
php
function get_resolution()
ts
async get_resolution(): Promise<number>
es
async get_resolution()
dnp
double get_resolution()
cp
double get_resolution()
cmd
YAccelerometer target get_resolution

The resolution corresponds to the numerical precision of the measures, which is not always the same as the actual precision of the sensor. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

a floating point number corresponding to the resolution of the measured values

On failure, throws an exception or returns YAccelerometer.RESOLUTION_INVALID.

accelerometer→get_sensorState()
accelerometer→sensorState()
accelerometer.get_sensorState()accelerometer→get_sensorState()[accelerometer sensorState]accelerometer.get_sensorState()accelerometer.get_sensorState()accelerometer.get_sensorState()accelerometer.get_sensorState()accelerometer.get_sensorState()accelerometer.get_sensorState()accelerometer→get_sensorState()accelerometer.get_sensorState()accelerometer.get_sensorState()accelerometer.get_sensorState()accelerometer.get_sensorState()YAccelerometer get_sensorState

Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.

js
function get_sensorState()
cpp
int get_sensorState()
m
-(int) sensorState
pas
LongInt get_sensorState(): LongInt
vb
function get_sensorState() As Integer
cs
int get_sensorState()
java
int get_sensorState()
uwp
async Task<int> get_sensorState()
py
get_sensorState()
php
function get_sensorState()
ts
async get_sensorState(): Promise<number>
es
async get_sensorState()
dnp
int get_sensorState()
cp
int get_sensorState()
cmd
YAccelerometer target get_sensorState

Returns :

an integer corresponding to the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now

On failure, throws an exception or returns YAccelerometer.SENSORSTATE_INVALID.

accelerometer→get_serialNumber()
accelerometer→serialNumber()
accelerometer.get_serialNumber()accelerometer→get_serialNumber()[accelerometer serialNumber]accelerometer.get_serialNumber()accelerometer.get_serialNumber()accelerometer.get_serialNumber()accelerometer.get_serialNumber()accelerometer.get_serialNumber()accelerometer.get_serialNumber()accelerometer→get_serialNumber()accelerometer.get_serialNumber()accelerometer.get_serialNumber()accelerometer.get_serialNumber()accelerometer.get_serialNumber()YAccelerometer get_serialNumber

Returns the serial number of the module, as set by the factory.

js
function get_serialNumber()
cpp
string get_serialNumber()
m
-(NSString*) serialNumber
pas
string get_serialNumber(): string
vb
function get_serialNumber() As String
cs
string get_serialNumber()
java
String get_serialNumber()
uwp
async Task<string> get_serialNumber()
py
get_serialNumber()
php
function get_serialNumber()
ts
async get_serialNumber(): Promise<string>
es
async get_serialNumber()
dnp
string get_serialNumber()
cp
string get_serialNumber()
cmd
YAccelerometer target get_serialNumber

Returns :

a string corresponding to the serial number of the module, as set by the factory.

On failure, throws an exception or returns YFunction.SERIALNUMBER_INVALID.

accelerometer→get_unit()
accelerometer→unit()
accelerometer.get_unit()accelerometer→get_unit()[accelerometer unit]accelerometer.get_unit()accelerometer.get_unit()accelerometer.get_unit()accelerometer.get_unit()accelerometer.get_unit()accelerometer.get_unit()accelerometer→get_unit()accelerometer.get_unit()accelerometer.get_unit()accelerometer.get_unit()accelerometer.get_unit()YAccelerometer get_unit

Returns the measuring unit for the acceleration.

js
function get_unit()
cpp
string get_unit()
m
-(NSString*) unit
pas
string get_unit(): string
vb
function get_unit() As String
cs
string get_unit()
java
String get_unit()
uwp
async Task<string> get_unit()
py
get_unit()
php
function get_unit()
ts
async get_unit(): Promise<string>
es
async get_unit()
dnp
string get_unit()
cp
string get_unit()
cmd
YAccelerometer target get_unit

Returns :

a string corresponding to the measuring unit for the acceleration

On failure, throws an exception or returns YAccelerometer.UNIT_INVALID.

accelerometer→get_userData()
accelerometer→userData()
accelerometer.get_userData()accelerometer→get_userData()[accelerometer userData]accelerometer.get_userData()accelerometer.get_userData()accelerometer.get_userData()accelerometer.get_userData()accelerometer.get_userData()accelerometer→get_userData()accelerometer.get_userData()accelerometer.get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

js
function get_userData()
cpp
void * get_userData()
m
-(id) userData
pas
Tobject get_userData(): Tobject
vb
function get_userData() As Object
cs
object get_userData()
java
Object get_userData()
py
get_userData()
php
function get_userData()
ts
async get_userData(): Promise<object|null>
es
async get_userData()

This attribute is never touched directly by the API, and is at disposal of the caller to store a context.

Returns :

the object stored previously by the caller.

accelerometer→get_xValue()
accelerometer→xValue()
accelerometer.get_xValue()accelerometer→get_xValue()[accelerometer xValue]accelerometer.get_xValue()accelerometer.get_xValue()accelerometer.get_xValue()accelerometer.get_xValue()accelerometer.get_xValue()accelerometer.get_xValue()accelerometer→get_xValue()accelerometer.get_xValue()accelerometer.get_xValue()accelerometer.get_xValue()accelerometer.get_xValue()YAccelerometer get_xValue

Returns the X component of the acceleration, as a floating point number.

js
function get_xValue()
cpp
double get_xValue()
m
-(double) xValue
pas
double get_xValue(): double
vb
function get_xValue() As Double
cs
double get_xValue()
java
double get_xValue()
uwp
async Task<double> get_xValue()
py
get_xValue()
php
function get_xValue()
ts
async get_xValue(): Promise<number>
es
async get_xValue()
dnp
double get_xValue()
cp
double get_xValue()
cmd
YAccelerometer target get_xValue

Returns :

a floating point number corresponding to the X component of the acceleration, as a floating point number

On failure, throws an exception or returns YAccelerometer.XVALUE_INVALID.

accelerometer→get_yValue()
accelerometer→yValue()
accelerometer.get_yValue()accelerometer→get_yValue()[accelerometer yValue]accelerometer.get_yValue()accelerometer.get_yValue()accelerometer.get_yValue()accelerometer.get_yValue()accelerometer.get_yValue()accelerometer.get_yValue()accelerometer→get_yValue()accelerometer.get_yValue()accelerometer.get_yValue()accelerometer.get_yValue()accelerometer.get_yValue()YAccelerometer get_yValue

Returns the Y component of the acceleration, as a floating point number.

js
function get_yValue()
cpp
double get_yValue()
m
-(double) yValue
pas
double get_yValue(): double
vb
function get_yValue() As Double
cs
double get_yValue()
java
double get_yValue()
uwp
async Task<double> get_yValue()
py
get_yValue()
php
function get_yValue()
ts
async get_yValue(): Promise<number>
es
async get_yValue()
dnp
double get_yValue()
cp
double get_yValue()
cmd
YAccelerometer target get_yValue

Returns :

a floating point number corresponding to the Y component of the acceleration, as a floating point number

On failure, throws an exception or returns YAccelerometer.YVALUE_INVALID.

accelerometer→get_zValue()
accelerometer→zValue()
accelerometer.get_zValue()accelerometer→get_zValue()[accelerometer zValue]accelerometer.get_zValue()accelerometer.get_zValue()accelerometer.get_zValue()accelerometer.get_zValue()accelerometer.get_zValue()accelerometer.get_zValue()accelerometer→get_zValue()accelerometer.get_zValue()accelerometer.get_zValue()accelerometer.get_zValue()accelerometer.get_zValue()YAccelerometer get_zValue

Returns the Z component of the acceleration, as a floating point number.

js
function get_zValue()
cpp
double get_zValue()
m
-(double) zValue
pas
double get_zValue(): double
vb
function get_zValue() As Double
cs
double get_zValue()
java
double get_zValue()
uwp
async Task<double> get_zValue()
py
get_zValue()
php
function get_zValue()
ts
async get_zValue(): Promise<number>
es
async get_zValue()
dnp
double get_zValue()
cp
double get_zValue()
cmd
YAccelerometer target get_zValue

Returns :

a floating point number corresponding to the Z component of the acceleration, as a floating point number

On failure, throws an exception or returns YAccelerometer.ZVALUE_INVALID.

accelerometer→isOnline()accelerometer.isOnline()accelerometer→isOnline()[accelerometer isOnline]accelerometer.isOnline()accelerometer.isOnline()accelerometer.isOnline()accelerometer.isOnline()accelerometer.isOnline()accelerometer→isOnline()accelerometer.isOnline()accelerometer.isOnline()accelerometer.isOnline()accelerometer.isOnline()

Checks if the accelerometer is currently reachable, without raising any error.

js
function isOnline()
cpp
bool isOnline()
m
-(BOOL) isOnline
pas
boolean isOnline(): boolean
vb
function isOnline() As Boolean
cs
bool isOnline()
java
boolean isOnline()
py
isOnline()
php
function isOnline()
ts
async isOnline(): Promise<boolean>
es
async isOnline()
dnp
bool isOnline()
cp
bool isOnline()

If there is a cached value for the accelerometer in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the accelerometer.

Returns :

true if the accelerometer can be reached, and false otherwise

accelerometer→isOnline_async()accelerometer.isOnline_async()

Checks if the accelerometer is currently reachable, without raising any error (asynchronous version).

js
function isOnline_async(callback, context)

If there is a cached value for the accelerometer in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the requested function.

This asynchronous version exists only in Javascript. It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the boolean result
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

accelerometer→isReadOnly()accelerometer→isReadOnly()[accelerometer isReadOnly]accelerometer.isReadOnly()accelerometer.isReadOnly()accelerometer.isReadOnly()accelerometer.isReadOnly()accelerometer.isReadOnly()accelerometer.isReadOnly()accelerometer→isReadOnly()accelerometer.isReadOnly()accelerometer.isReadOnly()accelerometer.isReadOnly()accelerometer.isReadOnly()YAccelerometer isReadOnly

Test if the function is readOnly.

cpp
bool isReadOnly()
m
-(bool) isReadOnly
pas
boolean isReadOnly(): boolean
vb
function isReadOnly() As Boolean
cs
bool isReadOnly()
java
boolean isReadOnly()
uwp
async Task<bool> isReadOnly()
py
isReadOnly()
php
function isReadOnly()
ts
async isReadOnly(): Promise<boolean>
es
async isReadOnly()
dnp
bool isReadOnly()
cp
bool isReadOnly()
cmd
YAccelerometer target isReadOnly

Return true if the function is write protected or that the function is not available.

Returns :

true if the function is readOnly or not online.

accelerometer→isSensorReady()YAccelerometer isSensorReady

Checks if the sensor is currently able to provide an up-to-date measure.

cmd
YAccelerometer target isSensorReady

Returns false if the device is unreachable, or if the sensor does not have a current measure to transmit. No exception is raised if there is an error while trying to contact the device hosting $THEFUNCTION$.

Returns :

true if the sensor can provide an up-to-date measure, and false otherwise

accelerometer→load()accelerometer.load()accelerometer→load()[accelerometer load: ]accelerometer.load()accelerometer.load()accelerometer.load()accelerometer.load()accelerometer.load()accelerometer→load()accelerometer.load()accelerometer.load()

Preloads the accelerometer cache with a specified validity duration.

js
function load(msValidity)
cpp
YRETCODE load(int msValidity)
m
-(YRETCODE) load: (u64) msValidity
pas
YRETCODE load(msValidity: u64): YRETCODE
vb
function load(ByVal msValidity As Long) As YRETCODE
cs
YRETCODE load(ulong msValidity)
java
int load(long msValidity)
py
load(msValidity)
php
function load($msValidity)
ts
async load(msValidity: number): Promise<number>
es
async load(msValidity)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

Parameters :

msValidityan integer corresponding to the validity attributed to the loaded function parameters, in milliseconds

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→loadAttribute()accelerometer.loadAttribute()accelerometer→loadAttribute()[accelerometer loadAttribute: ]accelerometer.loadAttribute()accelerometer.loadAttribute()accelerometer.loadAttribute()accelerometer.loadAttribute()accelerometer.loadAttribute()accelerometer.loadAttribute()accelerometer→loadAttribute()accelerometer.loadAttribute()accelerometer.loadAttribute()accelerometer.loadAttribute()accelerometer.loadAttribute()

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

js
function loadAttribute(attrName)
cpp
string loadAttribute(string attrName)
m
-(NSString*) loadAttribute: (NSString*) attrName
pas
string loadAttribute(attrName: string): string
vb
function loadAttribute(ByVal attrName As String) As String
cs
string loadAttribute(string attrName)
java
String loadAttribute(String attrName)
uwp
async Task<string> loadAttribute(string attrName)
py
loadAttribute(attrName)
php
function loadAttribute($attrName)
ts
async loadAttribute(attrName: string): Promise<string>
es
async loadAttribute(attrName)
dnp
string loadAttribute(string attrName)
cp
string loadAttribute(string attrName)

Parameters :

attrNamethe name of the requested attribute

Returns :

a string with the value of the the attribute

On failure, throws an exception or returns an empty string.

accelerometer→loadCalibrationPoints()accelerometer.loadCalibrationPoints()accelerometer→loadCalibrationPoints()[accelerometer loadCalibrationPoints: ]accelerometer.loadCalibrationPoints()accelerometer.loadCalibrationPoints()accelerometer.loadCalibrationPoints()accelerometer.loadCalibrationPoints()accelerometer.loadCalibrationPoints()accelerometer.loadCalibrationPoints()accelerometer→loadCalibrationPoints()accelerometer.loadCalibrationPoints()accelerometer.loadCalibrationPoints()YAccelerometer loadCalibrationPoints

Retrieves error correction data points previously entered using the method calibrateFromPoints.

js
function loadCalibrationPoints(rawValues, refValues)
cpp
int loadCalibrationPoints(vector<double> rawValues,
  vector<double> refValues)
m
-(int) loadCalibrationPoints: (NSMutableArray*) rawValues
  : (NSMutableArray*) refValues
pas
LongInt loadCalibrationPoints(var rawValues: TDoubleArray,
  var refValues: TDoubleArray): LongInt
vb
procedure loadCalibrationPoints(ByVal rawValues As List(Of)
cs
int loadCalibrationPoints(List<double> rawValues,
  List<double> refValues)
java
int loadCalibrationPoints(ArrayList<Double> rawValues,
  ArrayList<Double> refValues)
uwp
async Task<int> loadCalibrationPoints(List<double> rawValues,
  List<double> refValues)
py
loadCalibrationPoints(rawValues, refValues)
php
function loadCalibrationPoints(&$rawValues, &$refValues)
ts
async loadCalibrationPoints(rawValues: number[], refValues: number[]): Promise<number>
es
async loadCalibrationPoints(rawValues, refValues)
cmd
YAccelerometer target loadCalibrationPoints rawValues refValues

Parameters :

rawValuesarray of floating point numbers, that will be filled by the function with the raw sensor values for the correction points.
refValuesarray of floating point numbers, that will be filled by the function with the desired values for the correction points.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→load_async()accelerometer.load_async()

Preloads the accelerometer cache with a specified validity duration (asynchronous version).

js
function load_async(msValidity, callback, context)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking the JavaScript virtual machine.

Parameters :

msValidityan integer corresponding to the validity of the loaded function parameters, in milliseconds
callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the error code (or YAPI.SUCCESS)
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

accelerometer→muteValueCallbacks()accelerometer.muteValueCallbacks()accelerometer→muteValueCallbacks()[accelerometer muteValueCallbacks]accelerometer.muteValueCallbacks()accelerometer.muteValueCallbacks()accelerometer.muteValueCallbacks()accelerometer.muteValueCallbacks()accelerometer.muteValueCallbacks()accelerometer.muteValueCallbacks()accelerometer→muteValueCallbacks()accelerometer.muteValueCallbacks()accelerometer.muteValueCallbacks()accelerometer.muteValueCallbacks()accelerometer.muteValueCallbacks()YAccelerometer muteValueCallbacks

Disables the propagation of every new advertised value to the parent hub.

js
function muteValueCallbacks()
cpp
int muteValueCallbacks()
m
-(int) muteValueCallbacks
pas
LongInt muteValueCallbacks(): LongInt
vb
function muteValueCallbacks() As Integer
cs
int muteValueCallbacks()
java
int muteValueCallbacks()
uwp
async Task<int> muteValueCallbacks()
py
muteValueCallbacks()
php
function muteValueCallbacks()
ts
async muteValueCallbacks(): Promise<number>
es
async muteValueCallbacks()
dnp
int muteValueCallbacks()
cp
int muteValueCallbacks()
cmd
YAccelerometer target muteValueCallbacks

You can use this function to save bandwidth and CPU on computers with limited resources, or to prevent unwanted invocations of the HTTP callback. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→nextAccelerometer()accelerometer.nextAccelerometer()accelerometer→nextAccelerometer()[accelerometer nextAccelerometer]accelerometer.nextAccelerometer()accelerometer.nextAccelerometer()accelerometer.nextAccelerometer()accelerometer.nextAccelerometer()accelerometer.nextAccelerometer()accelerometer.nextAccelerometer()accelerometer→nextAccelerometer()accelerometer.nextAccelerometer()accelerometer.nextAccelerometer()

Continues the enumeration of accelerometers started using yFirstAccelerometer().

js
function nextAccelerometer()
cpp
YAccelerometer * nextAccelerometer()
m
-(nullable YAccelerometer*) nextAccelerometer
pas
TYAccelerometer nextAccelerometer(): TYAccelerometer
vb
function nextAccelerometer() As YAccelerometer
cs
YAccelerometer nextAccelerometer()
java
YAccelerometer nextAccelerometer()
uwp
YAccelerometer nextAccelerometer()
py
nextAccelerometer()
php
function nextAccelerometer()
ts
nextAccelerometer(): YAccelerometer | null
es
nextAccelerometer()

Caution: You can't make any assumption about the returned accelerometers order. If you want to find a specific an accelerometer, use Accelerometer.findAccelerometer() and a hardwareID or a logical name.

Returns :

a pointer to a YAccelerometer object, corresponding to an accelerometer currently online, or a null pointer if there are no more accelerometers to enumerate.

accelerometer→registerTimedReportCallback()accelerometer.registerTimedReportCallback()accelerometer→registerTimedReportCallback()[accelerometer registerTimedReportCallback: ]accelerometer.registerTimedReportCallback()accelerometer.registerTimedReportCallback()accelerometer.registerTimedReportCallback()accelerometer.registerTimedReportCallback()accelerometer.registerTimedReportCallback()accelerometer.registerTimedReportCallback()accelerometer→registerTimedReportCallback()accelerometer.registerTimedReportCallback()accelerometer.registerTimedReportCallback()

Registers the callback function that is invoked on every periodic timed notification.

js
function registerTimedReportCallback(callback)
cpp
int registerTimedReportCallback(YAccelerometerTimedReportCallback callback)
m
-(int) registerTimedReportCallback: (YAccelerometerTimedReportCallback _Nullable) callback
pas
LongInt registerTimedReportCallback(callback: TYAccelerometerTimedReportCallback): LongInt
vb
function registerTimedReportCallback(ByVal callback As YAccelerometerTimedReportCallback) As Integer
cs
int registerTimedReportCallback(TimedReportCallback callback)
java
int registerTimedReportCallback(TimedReportCallback callback)
uwp
async Task<int> registerTimedReportCallback(TimedReportCallback callback)
py
registerTimedReportCallback(callback)
php
function registerTimedReportCallback($callback)
ts
async registerTimedReportCallback(callback: YAccelerometerTimedReportCallback | null): Promise<number>
es
async registerTimedReportCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and an YMeasure object describing the new advertised value.

accelerometer→registerValueCallback()accelerometer.registerValueCallback()accelerometer→registerValueCallback()[accelerometer registerValueCallback: ]accelerometer.registerValueCallback()accelerometer.registerValueCallback()accelerometer.registerValueCallback()accelerometer.registerValueCallback()accelerometer.registerValueCallback()accelerometer.registerValueCallback()accelerometer→registerValueCallback()accelerometer.registerValueCallback()accelerometer.registerValueCallback()

Registers the callback function that is invoked on every change of advertised value.

js
function registerValueCallback(callback)
cpp
int registerValueCallback(YAccelerometerValueCallback callback)
m
-(int) registerValueCallback: (YAccelerometerValueCallback _Nullable) callback
pas
LongInt registerValueCallback(callback: TYAccelerometerValueCallback): LongInt
vb
function registerValueCallback(ByVal callback As YAccelerometerValueCallback) As Integer
cs
int registerValueCallback(ValueCallback callback)
java
int registerValueCallback(UpdateCallback callback)
uwp
async Task<int> registerValueCallback(ValueCallback callback)
py
registerValueCallback(callback)
php
function registerValueCallback($callback)
ts
async registerValueCallback(callback: YAccelerometerValueCallback | null): Promise<number>
es
async registerValueCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and the character string describing the new advertised value.

accelerometer→set_advMode()
accelerometer→setAdvMode()
accelerometer.set_advMode()accelerometer→set_advMode()[accelerometer setAdvMode: ]accelerometer.set_advMode()accelerometer.set_advMode()accelerometer.set_advMode()accelerometer.set_advMode()accelerometer.set_advMode()accelerometer.set_advMode()accelerometer→set_advMode()accelerometer.set_advMode()accelerometer.set_advMode()accelerometer.set_advMode()accelerometer.set_advMode()YAccelerometer set_advMode

Changes the measuring mode used for the advertised value pushed to the parent hub.

js
function set_advMode(newval)
cpp
int set_advMode(Y_ADVMODE_enum newval)
m
-(int) setAdvMode: (Y_ADVMODE_enum) newval
pas
integer set_advMode(newval: Integer): integer
vb
function set_advMode(ByVal newval As Integer) As Integer
cs
int set_advMode(int newval)
java
int set_advMode(int newval)
uwp
async Task<int> set_advMode(int newval)
py
set_advMode(newval)
php
function set_advMode($newval)
ts
async set_advMode(newval: YSensor_AdvMode): Promise<number>
es
async set_advMode(newval)
dnp
int set_advMode(int newval)
cp
int set_advMode(int newval)
cmd
YAccelerometer target set_advMode newval

Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala value among YAccelerometer.ADVMODE_IMMEDIATE, YAccelerometer.ADVMODE_PERIOD_AVG, YAccelerometer.ADVMODE_PERIOD_MIN and YAccelerometer.ADVMODE_PERIOD_MAX corresponding to the measuring mode used for the advertised value pushed to the parent hub

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→set_bandwidth()
accelerometer→setBandwidth()
accelerometer.set_bandwidth()accelerometer→set_bandwidth()[accelerometer setBandwidth: ]accelerometer.set_bandwidth()accelerometer.set_bandwidth()accelerometer.set_bandwidth()accelerometer.set_bandwidth()accelerometer.set_bandwidth()accelerometer.set_bandwidth()accelerometer→set_bandwidth()accelerometer.set_bandwidth()accelerometer.set_bandwidth()accelerometer.set_bandwidth()accelerometer.set_bandwidth()YAccelerometer set_bandwidth

Changes the measure update frequency, measured in Hz.

js
function set_bandwidth(newval)
cpp
int set_bandwidth(int newval)
m
-(int) setBandwidth: (int) newval
pas
integer set_bandwidth(newval: LongInt): integer
vb
function set_bandwidth(ByVal newval As Integer) As Integer
cs
int set_bandwidth(int newval)
java
int set_bandwidth(int newval)
uwp
async Task<int> set_bandwidth(int newval)
py
set_bandwidth(newval)
php
function set_bandwidth($newval)
ts
async set_bandwidth(newval: number): Promise<number>
es
async set_bandwidth(newval)
dnp
int set_bandwidth(int newval)
cp
int set_bandwidth(int newval)
cmd
YAccelerometer target set_bandwidth newval

When the frequency is lower, the device performs averaging. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvalan integer corresponding to the measure update frequency, measured in Hz

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→set_highestValue()
accelerometer→setHighestValue()
accelerometer.set_highestValue()accelerometer→set_highestValue()[accelerometer setHighestValue: ]accelerometer.set_highestValue()accelerometer.set_highestValue()accelerometer.set_highestValue()accelerometer.set_highestValue()accelerometer.set_highestValue()accelerometer.set_highestValue()accelerometer→set_highestValue()accelerometer.set_highestValue()accelerometer.set_highestValue()accelerometer.set_highestValue()accelerometer.set_highestValue()YAccelerometer set_highestValue

Changes the recorded maximal value observed.

js
function set_highestValue(newval)
cpp
int set_highestValue(double newval)
m
-(int) setHighestValue: (double) newval
pas
integer set_highestValue(newval: double): integer
vb
function set_highestValue(ByVal newval As Double) As Integer
cs
int set_highestValue(double newval)
java
int set_highestValue(double newval)
uwp
async Task<int> set_highestValue(double newval)
py
set_highestValue(newval)
php
function set_highestValue($newval)
ts
async set_highestValue(newval: number): Promise<number>
es
async set_highestValue(newval)
dnp
int set_highestValue(double newval)
cp
int set_highestValue(double newval)
cmd
YAccelerometer target set_highestValue newval

Can be used to reset the value returned by get_lowestValue().

Parameters :

newvala floating point number corresponding to the recorded maximal value observed

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→set_logFrequency()
accelerometer→setLogFrequency()
accelerometer.set_logFrequency()accelerometer→set_logFrequency()[accelerometer setLogFrequency: ]accelerometer.set_logFrequency()accelerometer.set_logFrequency()accelerometer.set_logFrequency()accelerometer.set_logFrequency()accelerometer.set_logFrequency()accelerometer.set_logFrequency()accelerometer→set_logFrequency()accelerometer.set_logFrequency()accelerometer.set_logFrequency()accelerometer.set_logFrequency()accelerometer.set_logFrequency()YAccelerometer set_logFrequency

Changes the datalogger recording frequency for this function.

js
function set_logFrequency(newval)
cpp
int set_logFrequency(string newval)
m
-(int) setLogFrequency: (NSString*) newval
pas
integer set_logFrequency(newval: string): integer
vb
function set_logFrequency(ByVal newval As String) As Integer
cs
int set_logFrequency(string newval)
java
int set_logFrequency(String newval)
uwp
async Task<int> set_logFrequency(string newval)
py
set_logFrequency(newval)
php
function set_logFrequency($newval)
ts
async set_logFrequency(newval: string): Promise<number>
es
async set_logFrequency(newval)
dnp
int set_logFrequency(string newval)
cp
int set_logFrequency(string newval)
cmd
YAccelerometer target set_logFrequency newval

The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (eg. "4/h"). To disable recording for this function, use the value "OFF". Note that setting the datalogger recording frequency to a greater value than the sensor native sampling frequency is useless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the datalogger recording frequency for this function

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→set_logicalName()
accelerometer→setLogicalName()
accelerometer.set_logicalName()accelerometer→set_logicalName()[accelerometer setLogicalName: ]accelerometer.set_logicalName()accelerometer.set_logicalName()accelerometer.set_logicalName()accelerometer.set_logicalName()accelerometer.set_logicalName()accelerometer.set_logicalName()accelerometer→set_logicalName()accelerometer.set_logicalName()accelerometer.set_logicalName()accelerometer.set_logicalName()accelerometer.set_logicalName()YAccelerometer set_logicalName

Changes the logical name of the accelerometer.

js
function set_logicalName(newval)
cpp
int set_logicalName(string newval)
m
-(int) setLogicalName: (NSString*) newval
pas
integer set_logicalName(newval: string): integer
vb
function set_logicalName(ByVal newval As String) As Integer
cs
int set_logicalName(string newval)
java
int set_logicalName(String newval)
uwp
async Task<int> set_logicalName(string newval)
py
set_logicalName(newval)
php
function set_logicalName($newval)
ts
async set_logicalName(newval: string): Promise<number>
es
async set_logicalName(newval)
dnp
int set_logicalName(string newval)
cp
int set_logicalName(string newval)
cmd
YAccelerometer target set_logicalName newval

You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the logical name of the accelerometer.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→set_lowestValue()
accelerometer→setLowestValue()
accelerometer.set_lowestValue()accelerometer→set_lowestValue()[accelerometer setLowestValue: ]accelerometer.set_lowestValue()accelerometer.set_lowestValue()accelerometer.set_lowestValue()accelerometer.set_lowestValue()accelerometer.set_lowestValue()accelerometer.set_lowestValue()accelerometer→set_lowestValue()accelerometer.set_lowestValue()accelerometer.set_lowestValue()accelerometer.set_lowestValue()accelerometer.set_lowestValue()YAccelerometer set_lowestValue

Changes the recorded minimal value observed.

js
function set_lowestValue(newval)
cpp
int set_lowestValue(double newval)
m
-(int) setLowestValue: (double) newval
pas
integer set_lowestValue(newval: double): integer
vb
function set_lowestValue(ByVal newval As Double) As Integer
cs
int set_lowestValue(double newval)
java
int set_lowestValue(double newval)
uwp
async Task<int> set_lowestValue(double newval)
py
set_lowestValue(newval)
php
function set_lowestValue($newval)
ts
async set_lowestValue(newval: number): Promise<number>
es
async set_lowestValue(newval)
dnp
int set_lowestValue(double newval)
cp
int set_lowestValue(double newval)
cmd
YAccelerometer target set_lowestValue newval

Can be used to reset the value returned by get_lowestValue().

Parameters :

newvala floating point number corresponding to the recorded minimal value observed

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→set_reportFrequency()
accelerometer→setReportFrequency()
accelerometer.set_reportFrequency()accelerometer→set_reportFrequency()[accelerometer setReportFrequency: ]accelerometer.set_reportFrequency()accelerometer.set_reportFrequency()accelerometer.set_reportFrequency()accelerometer.set_reportFrequency()accelerometer.set_reportFrequency()accelerometer.set_reportFrequency()accelerometer→set_reportFrequency()accelerometer.set_reportFrequency()accelerometer.set_reportFrequency()accelerometer.set_reportFrequency()accelerometer.set_reportFrequency()YAccelerometer set_reportFrequency

Changes the timed value notification frequency for this function.

js
function set_reportFrequency(newval)
cpp
int set_reportFrequency(string newval)
m
-(int) setReportFrequency: (NSString*) newval
pas
integer set_reportFrequency(newval: string): integer
vb
function set_reportFrequency(ByVal newval As String) As Integer
cs
int set_reportFrequency(string newval)
java
int set_reportFrequency(String newval)
uwp
async Task<int> set_reportFrequency(string newval)
py
set_reportFrequency(newval)
php
function set_reportFrequency($newval)
ts
async set_reportFrequency(newval: string): Promise<number>
es
async set_reportFrequency(newval)
dnp
int set_reportFrequency(string newval)
cp
int set_reportFrequency(string newval)
cmd
YAccelerometer target set_reportFrequency newval

The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (e.g. "4/h"). To disable timed value notifications for this function, use the value "OFF". Note that setting the timed value notification frequency to a greater value than the sensor native sampling frequency is unless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the timed value notification frequency for this function

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→set_resolution()
accelerometer→setResolution()
accelerometer.set_resolution()accelerometer→set_resolution()[accelerometer setResolution: ]accelerometer.set_resolution()accelerometer.set_resolution()accelerometer.set_resolution()accelerometer.set_resolution()accelerometer.set_resolution()accelerometer.set_resolution()accelerometer→set_resolution()accelerometer.set_resolution()accelerometer.set_resolution()accelerometer.set_resolution()accelerometer.set_resolution()YAccelerometer set_resolution

Changes the resolution of the measured physical values.

js
function set_resolution(newval)
cpp
int set_resolution(double newval)
m
-(int) setResolution: (double) newval
pas
integer set_resolution(newval: double): integer
vb
function set_resolution(ByVal newval As Double) As Integer
cs
int set_resolution(double newval)
java
int set_resolution(double newval)
uwp
async Task<int> set_resolution(double newval)
py
set_resolution(newval)
php
function set_resolution($newval)
ts
async set_resolution(newval: number): Promise<number>
es
async set_resolution(newval)
dnp
int set_resolution(double newval)
cp
int set_resolution(double newval)
cmd
YAccelerometer target set_resolution newval

The resolution corresponds to the numerical precision when displaying value. It does not change the precision of the measure itself. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala floating point number corresponding to the resolution of the measured physical values

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→set_userData()
accelerometer→setUserData()
accelerometer.set_userData()accelerometer→set_userData()[accelerometer setUserData: ]accelerometer.set_userData()accelerometer.set_userData()accelerometer.set_userData()accelerometer.set_userData()accelerometer.set_userData()accelerometer→set_userData()accelerometer.set_userData()accelerometer.set_userData()

Stores a user context provided as argument in the userData attribute of the function.

js
function set_userData(data)
cpp
void set_userData(void * data)
m
-(void) setUserData: (id) data
pas
set_userData(data: Tobject)
vb
procedure set_userData(ByVal data As Object)
cs
void set_userData(object data)
java
void set_userData(Object data)
py
set_userData(data)
php
function set_userData($data)
ts
async set_userData(data: object|null): Promise<void>
es
async set_userData(data)

This attribute is never touched by the API, and is at disposal of the caller to store a context.

Parameters :

dataany kind of object to be stored

accelerometer→startDataLogger()accelerometer.startDataLogger()accelerometer→startDataLogger()[accelerometer startDataLogger]accelerometer.startDataLogger()accelerometer.startDataLogger()accelerometer.startDataLogger()accelerometer.startDataLogger()accelerometer.startDataLogger()accelerometer.startDataLogger()accelerometer→startDataLogger()accelerometer.startDataLogger()accelerometer.startDataLogger()accelerometer.startDataLogger()accelerometer.startDataLogger()YAccelerometer startDataLogger

Starts the data logger on the device.

js
function startDataLogger()
cpp
int startDataLogger()
m
-(int) startDataLogger
pas
LongInt startDataLogger(): LongInt
vb
function startDataLogger() As Integer
cs
int startDataLogger()
java
int startDataLogger()
uwp
async Task<int> startDataLogger()
py
startDataLogger()
php
function startDataLogger()
ts
async startDataLogger(): Promise<number>
es
async startDataLogger()
dnp
int startDataLogger()
cp
int startDataLogger()
cmd
YAccelerometer target startDataLogger

Note that the data logger will only save the measures on this sensor if the logFrequency is not set to "OFF".

Returns :

YAPI.SUCCESS if the call succeeds.

accelerometer→stopDataLogger()accelerometer.stopDataLogger()accelerometer→stopDataLogger()[accelerometer stopDataLogger]accelerometer.stopDataLogger()accelerometer.stopDataLogger()accelerometer.stopDataLogger()accelerometer.stopDataLogger()accelerometer.stopDataLogger()accelerometer.stopDataLogger()accelerometer→stopDataLogger()accelerometer.stopDataLogger()accelerometer.stopDataLogger()accelerometer.stopDataLogger()accelerometer.stopDataLogger()YAccelerometer stopDataLogger

Stops the datalogger on the device.

js
function stopDataLogger()
cpp
int stopDataLogger()
m
-(int) stopDataLogger
pas
LongInt stopDataLogger(): LongInt
vb
function stopDataLogger() As Integer
cs
int stopDataLogger()
java
int stopDataLogger()
uwp
async Task<int> stopDataLogger()
py
stopDataLogger()
php
function stopDataLogger()
ts
async stopDataLogger(): Promise<number>
es
async stopDataLogger()
dnp
int stopDataLogger()
cp
int stopDataLogger()
cmd
YAccelerometer target stopDataLogger

Returns :

YAPI.SUCCESS if the call succeeds.

accelerometer→unmuteValueCallbacks()accelerometer.unmuteValueCallbacks()accelerometer→unmuteValueCallbacks()[accelerometer unmuteValueCallbacks]accelerometer.unmuteValueCallbacks()accelerometer.unmuteValueCallbacks()accelerometer.unmuteValueCallbacks()accelerometer.unmuteValueCallbacks()accelerometer.unmuteValueCallbacks()accelerometer.unmuteValueCallbacks()accelerometer→unmuteValueCallbacks()accelerometer.unmuteValueCallbacks()accelerometer.unmuteValueCallbacks()accelerometer.unmuteValueCallbacks()accelerometer.unmuteValueCallbacks()YAccelerometer unmuteValueCallbacks

Re-enables the propagation of every new advertised value to the parent hub.

js
function unmuteValueCallbacks()
cpp
int unmuteValueCallbacks()
m
-(int) unmuteValueCallbacks
pas
LongInt unmuteValueCallbacks(): LongInt
vb
function unmuteValueCallbacks() As Integer
cs
int unmuteValueCallbacks()
java
int unmuteValueCallbacks()
uwp
async Task<int> unmuteValueCallbacks()
py
unmuteValueCallbacks()
php
function unmuteValueCallbacks()
ts
async unmuteValueCallbacks(): Promise<number>
es
async unmuteValueCallbacks()
dnp
int unmuteValueCallbacks()
cp
int unmuteValueCallbacks()
cmd
YAccelerometer target unmuteValueCallbacks

This function reverts the effect of a previous call to muteValueCallbacks(). Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

accelerometer→wait_async()accelerometer.wait_async()accelerometer.wait_async()accelerometer.wait_async()

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

js
function wait_async(callback, context)
ts
wait_async(callback: Function, context: object)
es
wait_async(callback, context)

The callback function can therefore freely issue synchronous or asynchronous commands, without risking to block the JavaScript VM.

Parameters :

callbackcallback function that is invoked when all pending commands on the module are completed. The callback function receives two arguments: the caller-specific context object and the receiving function object.
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing.

24.4. Class YMagnetometer

Magnetometer control interface, available for instance in the Yocto-3D-V2

The YSensor class is the parent class for all Yoctopuce sensor types. It can be used to read the current value and unit of any sensor, read the min/max value, configure autonomous recording frequency and access recorded data. It also provide a function to register a callback invoked each time the observed value changes, or at a predefined interval. Using this class rather than a specific subclass makes it possible to create generic applications that work with any Yoctopuce sensor, even those that do not yet exist. Note: The YAnButton class is the only analog input which does not inherit from YSensor.

In order to use the functions described here, you should include:

es
in HTML: <script src="../../lib/yocto_magnetometer.js"></script>
in node.js: require('yoctolib-es2017/yocto_magnetometer.js');
js
<script type='text/javascript' src='yocto_magnetometer.js'></script>
cpp
#include "yocto_magnetometer.h"
m
#import "yocto_magnetometer.h"
pas
uses yocto_magnetometer;
vb
yocto_magnetometer.vb
cs
yocto_magnetometer.cs
java
import com.yoctopuce.YoctoAPI.YMagnetometer;
uwp
import com.yoctopuce.YoctoAPI.YMagnetometer;
py
from yocto_magnetometer import *
php
require_once('yocto_magnetometer.php');
ts
in HTML: import { YMagnetometer } from '../../dist/esm/yocto_magnetometer.js';
in Node.js: import { YMagnetometer } from 'yoctolib-cjs/yocto_magnetometer.js';
dnp
import YoctoProxyAPI.YMagnetometerProxy
cp
#include "yocto_magnetometer_proxy.h"
vi
YMagnetometer.vi
ml
import YoctoProxyAPI.YMagnetometerProxy
Global functions
YMagnetometer.FindMagnetometer(func)

Retrieves a magnetometer for a given identifier.

YMagnetometer.FindMagnetometerInContext(yctx, func)

Retrieves a magnetometer for a given identifier in a YAPI context.

YMagnetometer.FirstMagnetometer()

Starts the enumeration of magnetometers currently accessible.

YMagnetometer.FirstMagnetometerInContext(yctx)

Starts the enumeration of magnetometers currently accessible.

YMagnetometer.GetSimilarFunctions()

Enumerates all functions of type Magnetometer available on the devices currently reachable by the library, and returns their unique hardware ID.

YMagnetometer properties
magnetometer→AdvMode [writable]

Measuring mode used for the advertised value pushed to the parent hub.

magnetometer→AdvertisedValue [read-only]

Short string representing the current state of the function.

magnetometer→Bandwidth [writable]

Measure update frequency, measured in Hz.

magnetometer→FriendlyName [read-only]

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

magnetometer→FunctionId [read-only]

Hardware identifier of the sensor, without reference to the module.

magnetometer→HardwareId [read-only]

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

magnetometer→IsOnline [read-only]

Checks if the function is currently reachable.

magnetometer→LogFrequency [writable]

Datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

magnetometer→LogicalName [writable]

Logical name of the function.

magnetometer→ReportFrequency [writable]

Timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

magnetometer→Resolution [writable]

Resolution of the measured values.

magnetometer→SerialNumber [read-only]

Serial number of the module, as set by the factory.

YMagnetometer methods
magnetometer→calibrateFromPoints(rawValues, refValues)

Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.

magnetometer→clearCache()

Invalidates the cache.

magnetometer→describe()

Returns a short text that describes unambiguously the instance of the magnetometer in the form TYPE(NAME)=SERIAL.FUNCTIONID.

magnetometer→get_advMode()

Returns the measuring mode used for the advertised value pushed to the parent hub.

magnetometer→get_advertisedValue()

Returns the current value of the magnetometer (no more than 6 characters).

magnetometer→get_bandwidth()

Returns the measure update frequency, measured in Hz.

magnetometer→get_currentRawValue()

Returns the uncalibrated, unrounded raw value returned by the sensor, in mT, as a floating point number.

magnetometer→get_currentValue()

Returns the current value of the magnetic field, in mT, as a floating point number.

magnetometer→get_dataLogger()

Returns the YDatalogger object of the device hosting the sensor.

magnetometer→get_errorMessage()

Returns the error message of the latest error with the magnetometer.

magnetometer→get_errorType()

Returns the numerical error code of the latest error with the magnetometer.

magnetometer→get_friendlyName()

Returns a global identifier of the magnetometer in the format MODULE_NAME.FUNCTION_NAME.

magnetometer→get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

magnetometer→get_functionId()

Returns the hardware identifier of the magnetometer, without reference to the module.

magnetometer→get_hardwareId()

Returns the unique hardware identifier of the magnetometer in the form SERIAL.FUNCTIONID.

magnetometer→get_highestValue()

Returns the maximal value observed for the magnetic field since the device was started.

magnetometer→get_logFrequency()

Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

magnetometer→get_logicalName()

Returns the logical name of the magnetometer.

magnetometer→get_lowestValue()

Returns the minimal value observed for the magnetic field since the device was started.

magnetometer→get_module()

Gets the YModule object for the device on which the function is located.

magnetometer→get_module_async(callback, context)

Gets the YModule object for the device on which the function is located (asynchronous version).

magnetometer→get_recordedData(startTime, endTime)

Retrieves a YDataSet object holding historical data for this sensor, for a specified time interval.

magnetometer→get_reportFrequency()

Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

magnetometer→get_resolution()

Returns the resolution of the measured values.

magnetometer→get_sensorState()

Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.

magnetometer→get_serialNumber()

Returns the serial number of the module, as set by the factory.

magnetometer→get_unit()

Returns the measuring unit for the magnetic field.

magnetometer→get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

magnetometer→get_xValue()

Returns the X component of the magnetic field, as a floating point number.

magnetometer→get_yValue()

Returns the Y component of the magnetic field, as a floating point number.

magnetometer→get_zValue()

Returns the Z component of the magnetic field, as a floating point number.

magnetometer→isOnline()

Checks if the magnetometer is currently reachable, without raising any error.

magnetometer→isOnline_async(callback, context)

Checks if the magnetometer is currently reachable, without raising any error (asynchronous version).

magnetometer→isReadOnly()

Test if the function is readOnly.

magnetometer→isSensorReady()

Checks if the sensor is currently able to provide an up-to-date measure.

magnetometer→load(msValidity)

Preloads the magnetometer cache with a specified validity duration.

magnetometer→loadAttribute(attrName)

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

magnetometer→loadCalibrationPoints(rawValues, refValues)

Retrieves error correction data points previously entered using the method calibrateFromPoints.

magnetometer→load_async(msValidity, callback, context)

Preloads the magnetometer cache with a specified validity duration (asynchronous version).

magnetometer→muteValueCallbacks()

Disables the propagation of every new advertised value to the parent hub.

magnetometer→nextMagnetometer()

Continues the enumeration of magnetometers started using yFirstMagnetometer().

magnetometer→registerTimedReportCallback(callback)

Registers the callback function that is invoked on every periodic timed notification.

magnetometer→registerValueCallback(callback)

Registers the callback function that is invoked on every change of advertised value.

magnetometer→set_advMode(newval)

Changes the measuring mode used for the advertised value pushed to the parent hub.

magnetometer→set_bandwidth(newval)

Changes the measure update frequency, measured in Hz.

magnetometer→set_highestValue(newval)

Changes the recorded maximal value observed.

magnetometer→set_logFrequency(newval)

Changes the datalogger recording frequency for this function.

magnetometer→set_logicalName(newval)

Changes the logical name of the magnetometer.

magnetometer→set_lowestValue(newval)

Changes the recorded minimal value observed.

magnetometer→set_reportFrequency(newval)

Changes the timed value notification frequency for this function.

magnetometer→set_resolution(newval)

Changes the resolution of the measured physical values.

magnetometer→set_userData(data)

Stores a user context provided as argument in the userData attribute of the function.

magnetometer→startDataLogger()

Starts the data logger on the device.

magnetometer→stopDataLogger()

Stops the datalogger on the device.

magnetometer→unmuteValueCallbacks()

Re-enables the propagation of every new advertised value to the parent hub.

magnetometer→wait_async(callback, context)

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

YMagnetometer.FindMagnetometer()
YMagnetometer.FindMagnetometer()
yFindMagnetometer()YMagnetometer::FindMagnetometer()[YMagnetometer FindMagnetometer: ]yFindMagnetometer()YMagnetometer.FindMagnetometer()YMagnetometer.FindMagnetometer()YMagnetometer.FindMagnetometer()YMagnetometer.FindMagnetometer()YMagnetometer.FindMagnetometer()YMagnetometer::FindMagnetometer()YMagnetometer.FindMagnetometer()YMagnetometer.FindMagnetometer()YMagnetometer.FindMagnetometer()YMagnetometer.FindMagnetometer()

Retrieves a magnetometer for a given identifier.

js
function yFindMagnetometer(func)
cpp
YMagnetometer* FindMagnetometer(string func)
m
+(YMagnetometer*) FindMagnetometer: (NSString*) func
pas
TYMagnetometer yFindMagnetometer(func: string): TYMagnetometer
vb
function FindMagnetometer(ByVal func As String) As YMagnetometer
cs
static YMagnetometer FindMagnetometer(string func)
java
static YMagnetometer FindMagnetometer(String func)
uwp
static YMagnetometer FindMagnetometer(string func)
py
FindMagnetometer(func)
php
function FindMagnetometer($func)
ts
static FindMagnetometer(func: string): YMagnetometer
es
static FindMagnetometer(func)
dnp
static YMagnetometerProxy FindMagnetometer(string func)
cp
static YMagnetometerProxy * FindMagnetometer(string func)

The identifier can be specified using several formats:

This function does not require that the magnetometer is online at the time it is invoked. The returned object is nevertheless valid. Use the method YMagnetometer.isOnline() to test if the magnetometer is indeed online at a given time. In case of ambiguity when looking for a magnetometer by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

If a call to this object's is_online() method returns FALSE although you are certain that the matching device is plugged, make sure that you did call registerHub() at application initialization time.

Parameters :

funca string that uniquely characterizes the magnetometer, for instance Y3DMK002.magnetometer.

Returns :

a YMagnetometer object allowing you to drive the magnetometer.

YMagnetometer.FindMagnetometerInContext()
YMagnetometer.FindMagnetometerInContext()
YMagnetometer.FindMagnetometerInContext()YMagnetometer.FindMagnetometerInContext()YMagnetometer.FindMagnetometerInContext()YMagnetometer.FindMagnetometerInContext()

Retrieves a magnetometer for a given identifier in a YAPI context.

java
static YMagnetometer FindMagnetometerInContext(YAPIContext yctx,
  String func)
uwp
static YMagnetometer FindMagnetometerInContext(YAPIContext yctx,
  string func)
ts
static FindMagnetometerInContext(yctx: YAPIContext, func: string): YMagnetometer
es
static FindMagnetometerInContext(yctx, func)

The identifier can be specified using several formats:

This function does not require that the magnetometer is online at the time it is invoked. The returned object is nevertheless valid. Use the method YMagnetometer.isOnline() to test if the magnetometer is indeed online at a given time. In case of ambiguity when looking for a magnetometer by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

Parameters :

yctxa YAPI context
funca string that uniquely characterizes the magnetometer, for instance Y3DMK002.magnetometer.

Returns :

a YMagnetometer object allowing you to drive the magnetometer.

YMagnetometer.FirstMagnetometer()
YMagnetometer.FirstMagnetometer()
yFirstMagnetometer()YMagnetometer::FirstMagnetometer()[YMagnetometer FirstMagnetometer]yFirstMagnetometer()YMagnetometer.FirstMagnetometer()YMagnetometer.FirstMagnetometer()YMagnetometer.FirstMagnetometer()YMagnetometer.FirstMagnetometer()YMagnetometer.FirstMagnetometer()YMagnetometer::FirstMagnetometer()YMagnetometer.FirstMagnetometer()YMagnetometer.FirstMagnetometer()

Starts the enumeration of magnetometers currently accessible.

js
function yFirstMagnetometer()
cpp
YMagnetometer * FirstMagnetometer()
m
+(YMagnetometer*) FirstMagnetometer
pas
TYMagnetometer yFirstMagnetometer(): TYMagnetometer
vb
function FirstMagnetometer() As YMagnetometer
cs
static YMagnetometer FirstMagnetometer()
java
static YMagnetometer FirstMagnetometer()
uwp
static YMagnetometer FirstMagnetometer()
py
FirstMagnetometer()
php
function FirstMagnetometer()
ts
static FirstMagnetometer(): YMagnetometer | null
es
static FirstMagnetometer()

Use the method YMagnetometer.nextMagnetometer() to iterate on next magnetometers.

Returns :

a pointer to a YMagnetometer object, corresponding to the first magnetometer currently online, or a null pointer if there are none.

YMagnetometer.FirstMagnetometerInContext()
YMagnetometer.FirstMagnetometerInContext()
YMagnetometer.FirstMagnetometerInContext()YMagnetometer.FirstMagnetometerInContext()YMagnetometer.FirstMagnetometerInContext()YMagnetometer.FirstMagnetometerInContext()

Starts the enumeration of magnetometers currently accessible.

java
static YMagnetometer FirstMagnetometerInContext(YAPIContext yctx)
uwp
static YMagnetometer FirstMagnetometerInContext(YAPIContext yctx)
ts
static FirstMagnetometerInContext(yctx: YAPIContext): YMagnetometer | null
es
static FirstMagnetometerInContext(yctx)

Use the method YMagnetometer.nextMagnetometer() to iterate on next magnetometers.

Parameters :

yctxa YAPI context.

Returns :

a pointer to a YMagnetometer object, corresponding to the first magnetometer currently online, or a null pointer if there are none.

YMagnetometer.GetSimilarFunctions()
YMagnetometer.GetSimilarFunctions()
YMagnetometer.GetSimilarFunctions()YMagnetometer.GetSimilarFunctions()

Enumerates all functions of type Magnetometer available on the devices currently reachable by the library, and returns their unique hardware ID.

dnp
static new string[] GetSimilarFunctions()
cp
static vector<string> GetSimilarFunctions()

Each of these IDs can be provided as argument to the method YMagnetometer.FindMagnetometer to obtain an object that can control the corresponding device.

Returns :

an array of strings, each string containing the unique hardwareId of a device function currently connected.

magnetometer→AdvModemagnetometer.AdvMode

Measuring mode used for the advertised value pushed to the parent hub.

dnp
int AdvMode

Writable. Remember to call the saveToFlash() method of the module if the modification must be kept.

magnetometer→AdvertisedValuemagnetometer.AdvertisedValue

Short string representing the current state of the function.

dnp
string AdvertisedValue

magnetometer→Bandwidthmagnetometer.Bandwidth

Measure update frequency, measured in Hz.

dnp
int Bandwidth

Writable. When the frequency is lower, the device performs averaging. Remember to call the saveToFlash() method of the module if the modification must be kept.

magnetometer→FriendlyNamemagnetometer.FriendlyName

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

dnp
string FriendlyName

The returned string uses the logical names of the module and of the function if they are defined, otherwise the serial number of the module and the hardware identifier of the function (for example: MyCustomName.relay1)

magnetometer→FunctionIdmagnetometer.FunctionId

Hardware identifier of the sensor, without reference to the module.

dnp
string FunctionId

For example relay1

magnetometer→HardwareIdmagnetometer.HardwareId

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

dnp
string HardwareId

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the function (for example RELAYLO1-123456.relay1).

magnetometer→IsOnlinemagnetometer.IsOnline

Checks if the function is currently reachable.

dnp
bool IsOnline

If there is a cached value for the function in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the function.

magnetometer→LogFrequencymagnetometer.LogFrequency

Datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

dnp
string LogFrequency

Writable. Changes the datalogger recording frequency for this function. The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (eg. "4/h"). To disable recording for this function, use the value "OFF". Note that setting the datalogger recording frequency to a greater value than the sensor native sampling frequency is useless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

magnetometer→LogicalNamemagnetometer.LogicalName

Logical name of the function.

dnp
string LogicalName

Writable. You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

magnetometer→ReportFrequencymagnetometer.ReportFrequency

Timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

dnp
string ReportFrequency

Writable. Changes the timed value notification frequency for this function. The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (e.g. "4/h"). To disable timed value notifications for this function, use the value "OFF". Note that setting the timed value notification frequency to a greater value than the sensor native sampling frequency is unless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

magnetometer→Resolutionmagnetometer.Resolution

Resolution of the measured values.

dnp
double Resolution

The resolution corresponds to the numerical precision of the measures, which is not always the same as the actual precision of the sensor. Remember to call the saveToFlash() method of the module if the modification must be kept.

Writable. Changes the resolution of the measured physical values. The resolution corresponds to the numerical precision when displaying value. It does not change the precision of the measure itself. Remember to call the saveToFlash() method of the module if the modification must be kept.

magnetometer→SerialNumbermagnetometer.SerialNumber

Serial number of the module, as set by the factory.

dnp
string SerialNumber

magnetometer→calibrateFromPoints()magnetometer.calibrateFromPoints()magnetometer→calibrateFromPoints()[magnetometer calibrateFromPoints: ]magnetometer.calibrateFromPoints()magnetometer.calibrateFromPoints()magnetometer.calibrateFromPoints()magnetometer.calibrateFromPoints()magnetometer.calibrateFromPoints()magnetometer.calibrateFromPoints()magnetometer→calibrateFromPoints()magnetometer.calibrateFromPoints()magnetometer.calibrateFromPoints()magnetometer.calibrateFromPoints()magnetometer.calibrateFromPoints()YMagnetometer calibrateFromPoints

Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.

js
function calibrateFromPoints(rawValues, refValues)
cpp
int calibrateFromPoints(vector<double> rawValues,
  vector<double> refValues)
m
-(int) calibrateFromPoints: (NSMutableArray*) rawValues
  : (NSMutableArray*) refValues
pas
LongInt calibrateFromPoints(rawValues: TDoubleArray,
  refValues: TDoubleArray): LongInt
vb
procedure calibrateFromPoints(ByVal rawValues As List(Of)
cs
int calibrateFromPoints(List<double> rawValues,
  List<double> refValues)
java
int calibrateFromPoints(ArrayList<Double> rawValues,
  ArrayList<Double> refValues)
uwp
async Task<int> calibrateFromPoints(List<double> rawValues,
  List<double> refValues)
py
calibrateFromPoints(rawValues, refValues)
php
function calibrateFromPoints($rawValues, $refValues)
ts
async calibrateFromPoints(rawValues: number[], refValues: number[]): Promise<number>
es
async calibrateFromPoints(rawValues, refValues)
dnp
int calibrateFromPoints(double[] rawValues,
  double[] refValues)
cp
int calibrateFromPoints(vector<double> rawValues,
  vector<double> refValues)
cmd
YMagnetometer target calibrateFromPoints rawValues refValues

It is possible to configure up to five correction points. Correction points must be provided in ascending order, and be in the range of the sensor. The device will automatically perform a linear interpolation of the error correction between specified points. Remember to call the saveToFlash() method of the module if the modification must be kept.

For more information on advanced capabilities to refine the calibration of sensors, please contact support@yoctopuce.com.

Parameters :

rawValuesarray of floating point numbers, corresponding to the raw values returned by the sensor for the correction points.
refValuesarray of floating point numbers, corresponding to the corrected values for the correction points.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→clearCache()magnetometer.clearCache()magnetometer→clearCache()[magnetometer clearCache]magnetometer.clearCache()magnetometer.clearCache()magnetometer.clearCache()magnetometer.clearCache()magnetometer.clearCache()magnetometer→clearCache()magnetometer.clearCache()magnetometer.clearCache()

Invalidates the cache.

js
function clearCache()
cpp
void clearCache()
m
-(void) clearCache
pas
clearCache()
vb
procedure clearCache()
cs
void clearCache()
java
void clearCache()
py
clearCache()
php
function clearCache()
ts
async clearCache(): Promise<void>
es
async clearCache()

Invalidates the cache of the magnetometer attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.

magnetometer→describe()magnetometer.describe()magnetometer→describe()[magnetometer describe]magnetometer.describe()magnetometer.describe()magnetometer.describe()magnetometer.describe()magnetometer.describe()magnetometer→describe()magnetometer.describe()magnetometer.describe()

Returns a short text that describes unambiguously the instance of the magnetometer in the form TYPE(NAME)=SERIAL.FUNCTIONID.

js
function describe()
cpp
string describe()
m
-(NSString*) describe
pas
string describe(): string
vb
function describe() As String
cs
string describe()
java
String describe()
py
describe()
php
function describe()
ts
async describe(): Promise<string>
es
async describe()

More precisely, TYPE is the type of the function, NAME it the name used for the first access to the function, SERIAL is the serial number of the module if the module is connected or "unresolved", and FUNCTIONID is the hardware identifier of the function if the module is connected. For example, this method returns Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1 if the module is already connected or Relay(BadCustomeName.relay1)=unresolved if the module has not yet been connected. This method does not trigger any USB or TCP transaction and can therefore be used in a debugger.

Returns :

a string that describes the magnetometer (ex: Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1)

magnetometer→get_advMode()
magnetometer→advMode()
magnetometer.get_advMode()magnetometer→get_advMode()[magnetometer advMode]magnetometer.get_advMode()magnetometer.get_advMode()magnetometer.get_advMode()magnetometer.get_advMode()magnetometer.get_advMode()magnetometer.get_advMode()magnetometer→get_advMode()magnetometer.get_advMode()magnetometer.get_advMode()magnetometer.get_advMode()magnetometer.get_advMode()YMagnetometer get_advMode

Returns the measuring mode used for the advertised value pushed to the parent hub.

js
function get_advMode()
cpp
Y_ADVMODE_enum get_advMode()
m
-(Y_ADVMODE_enum) advMode
pas
Integer get_advMode(): Integer
vb
function get_advMode() As Integer
cs
int get_advMode()
java
int get_advMode()
uwp
async Task<int> get_advMode()
py
get_advMode()
php
function get_advMode()
ts
async get_advMode(): Promise<YSensor_AdvMode>
es
async get_advMode()
dnp
int get_advMode()
cp
int get_advMode()
cmd
YMagnetometer target get_advMode

Returns :

a value among YMagnetometer.ADVMODE_IMMEDIATE, YMagnetometer.ADVMODE_PERIOD_AVG, YMagnetometer.ADVMODE_PERIOD_MIN and YMagnetometer.ADVMODE_PERIOD_MAX corresponding to the measuring mode used for the advertised value pushed to the parent hub

On failure, throws an exception or returns YMagnetometer.ADVMODE_INVALID.

magnetometer→get_advertisedValue()
magnetometer→advertisedValue()
magnetometer.get_advertisedValue()magnetometer→get_advertisedValue()[magnetometer advertisedValue]magnetometer.get_advertisedValue()magnetometer.get_advertisedValue()magnetometer.get_advertisedValue()magnetometer.get_advertisedValue()magnetometer.get_advertisedValue()magnetometer.get_advertisedValue()magnetometer→get_advertisedValue()magnetometer.get_advertisedValue()magnetometer.get_advertisedValue()magnetometer.get_advertisedValue()magnetometer.get_advertisedValue()YMagnetometer get_advertisedValue

Returns the current value of the magnetometer (no more than 6 characters).

js
function get_advertisedValue()
cpp
string get_advertisedValue()
m
-(NSString*) advertisedValue
pas
string get_advertisedValue(): string
vb
function get_advertisedValue() As String
cs
string get_advertisedValue()
java
String get_advertisedValue()
uwp
async Task<string> get_advertisedValue()
py
get_advertisedValue()
php
function get_advertisedValue()
ts
async get_advertisedValue(): Promise<string>
es
async get_advertisedValue()
dnp
string get_advertisedValue()
cp
string get_advertisedValue()
cmd
YMagnetometer target get_advertisedValue

Returns :

a string corresponding to the current value of the magnetometer (no more than 6 characters).

On failure, throws an exception or returns YMagnetometer.ADVERTISEDVALUE_INVALID.

magnetometer→get_bandwidth()
magnetometer→bandwidth()
magnetometer.get_bandwidth()magnetometer→get_bandwidth()[magnetometer bandwidth]magnetometer.get_bandwidth()magnetometer.get_bandwidth()magnetometer.get_bandwidth()magnetometer.get_bandwidth()magnetometer.get_bandwidth()magnetometer.get_bandwidth()magnetometer→get_bandwidth()magnetometer.get_bandwidth()magnetometer.get_bandwidth()magnetometer.get_bandwidth()magnetometer.get_bandwidth()YMagnetometer get_bandwidth

Returns the measure update frequency, measured in Hz.

js
function get_bandwidth()
cpp
int get_bandwidth()
m
-(int) bandwidth
pas
LongInt get_bandwidth(): LongInt
vb
function get_bandwidth() As Integer
cs
int get_bandwidth()
java
int get_bandwidth()
uwp
async Task<int> get_bandwidth()
py
get_bandwidth()
php
function get_bandwidth()
ts
async get_bandwidth(): Promise<number>
es
async get_bandwidth()
dnp
int get_bandwidth()
cp
int get_bandwidth()
cmd
YMagnetometer target get_bandwidth

Returns :

an integer corresponding to the measure update frequency, measured in Hz

On failure, throws an exception or returns YMagnetometer.BANDWIDTH_INVALID.

magnetometer→get_currentRawValue()
magnetometer→currentRawValue()
magnetometer.get_currentRawValue()magnetometer→get_currentRawValue()[magnetometer currentRawValue]magnetometer.get_currentRawValue()magnetometer.get_currentRawValue()magnetometer.get_currentRawValue()magnetometer.get_currentRawValue()magnetometer.get_currentRawValue()magnetometer.get_currentRawValue()magnetometer→get_currentRawValue()magnetometer.get_currentRawValue()magnetometer.get_currentRawValue()magnetometer.get_currentRawValue()magnetometer.get_currentRawValue()YMagnetometer get_currentRawValue

Returns the uncalibrated, unrounded raw value returned by the sensor, in mT, as a floating point number.

js
function get_currentRawValue()
cpp
double get_currentRawValue()
m
-(double) currentRawValue
pas
double get_currentRawValue(): double
vb
function get_currentRawValue() As Double
cs
double get_currentRawValue()
java
double get_currentRawValue()
uwp
async Task<double> get_currentRawValue()
py
get_currentRawValue()
php
function get_currentRawValue()
ts
async get_currentRawValue(): Promise<number>
es
async get_currentRawValue()
dnp
double get_currentRawValue()
cp
double get_currentRawValue()
cmd
YMagnetometer target get_currentRawValue

Returns :

a floating point number corresponding to the uncalibrated, unrounded raw value returned by the sensor, in mT, as a floating point number

On failure, throws an exception or returns YMagnetometer.CURRENTRAWVALUE_INVALID.

magnetometer→get_currentValue()
magnetometer→currentValue()
magnetometer.get_currentValue()magnetometer→get_currentValue()[magnetometer currentValue]magnetometer.get_currentValue()magnetometer.get_currentValue()magnetometer.get_currentValue()magnetometer.get_currentValue()magnetometer.get_currentValue()magnetometer.get_currentValue()magnetometer→get_currentValue()magnetometer.get_currentValue()magnetometer.get_currentValue()magnetometer.get_currentValue()magnetometer.get_currentValue()YMagnetometer get_currentValue

Returns the current value of the magnetic field, in mT, as a floating point number.

js
function get_currentValue()
cpp
double get_currentValue()
m
-(double) currentValue
pas
double get_currentValue(): double
vb
function get_currentValue() As Double
cs
double get_currentValue()
java
double get_currentValue()
uwp
async Task<double> get_currentValue()
py
get_currentValue()
php
function get_currentValue()
ts
async get_currentValue(): Promise<number>
es
async get_currentValue()
dnp
double get_currentValue()
cp
double get_currentValue()
cmd
YMagnetometer target get_currentValue

Note that a get_currentValue() call will *not* start a measure in the device, it will just return the last measure that occurred in the device. Indeed, internally, each Yoctopuce devices is continuously making measurements at a hardware specific frequency.

If continuously calling get_currentValue() leads you to performances issues, then you might consider to switch to callback programming model. Check the "advanced programming" chapter in in your device user manual for more information.

Returns :

a floating point number corresponding to the current value of the magnetic field, in mT, as a floating point number

On failure, throws an exception or returns YMagnetometer.CURRENTVALUE_INVALID.

magnetometer→get_dataLogger()
magnetometer→dataLogger()
magnetometer.get_dataLogger()magnetometer→get_dataLogger()[magnetometer dataLogger]magnetometer.get_dataLogger()magnetometer.get_dataLogger()magnetometer.get_dataLogger()magnetometer.get_dataLogger()magnetometer.get_dataLogger()magnetometer.get_dataLogger()magnetometer→get_dataLogger()magnetometer.get_dataLogger()magnetometer.get_dataLogger()magnetometer.get_dataLogger()magnetometer.get_dataLogger()

Returns the YDatalogger object of the device hosting the sensor.

js
function get_dataLogger()
cpp
YDataLogger* get_dataLogger()
m
-(YDataLogger*) dataLogger
pas
TYDataLogger get_dataLogger(): TYDataLogger
vb
function get_dataLogger() As YDataLogger
cs
YDataLogger get_dataLogger()
java
YDataLogger get_dataLogger()
uwp
async Task<YDataLogger> get_dataLogger()
py
get_dataLogger()
php
function get_dataLogger()
ts
async get_dataLogger(): Promise<YDataLogger | null>
es
async get_dataLogger()
dnp
YDataLoggerProxy get_dataLogger()
cp
YDataLoggerProxy* get_dataLogger()

This method returns an object that can control global parameters of the data logger. The returned object should not be freed.

Returns :

an YDatalogger object, or null on error.

magnetometer→get_errorMessage()
magnetometer→errorMessage()
magnetometer.get_errorMessage()magnetometer→get_errorMessage()[magnetometer errorMessage]magnetometer.get_errorMessage()magnetometer.get_errorMessage()magnetometer.get_errorMessage()magnetometer.get_errorMessage()magnetometer.get_errorMessage()magnetometer→get_errorMessage()magnetometer.get_errorMessage()magnetometer.get_errorMessage()

Returns the error message of the latest error with the magnetometer.

js
function get_errorMessage()
cpp
string get_errorMessage()
m
-(NSString*) errorMessage
pas
string get_errorMessage(): string
vb
function get_errorMessage() As String
cs
string get_errorMessage()
java
String get_errorMessage()
py
get_errorMessage()
php
function get_errorMessage()
ts
get_errorMessage(): string
es
get_errorMessage()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a string corresponding to the latest error message that occured while using the magnetometer object

magnetometer→get_errorType()
magnetometer→errorType()
magnetometer.get_errorType()magnetometer→get_errorType()[magnetometer errorType]magnetometer.get_errorType()magnetometer.get_errorType()magnetometer.get_errorType()magnetometer.get_errorType()magnetometer.get_errorType()magnetometer→get_errorType()magnetometer.get_errorType()magnetometer.get_errorType()

Returns the numerical error code of the latest error with the magnetometer.

js
function get_errorType()
cpp
YRETCODE get_errorType()
m
-(YRETCODE) errorType
pas
YRETCODE get_errorType(): YRETCODE
vb
function get_errorType() As YRETCODE
cs
YRETCODE get_errorType()
java
int get_errorType()
py
get_errorType()
php
function get_errorType()
ts
get_errorType(): number
es
get_errorType()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a number corresponding to the code of the latest error that occurred while using the magnetometer object

magnetometer→get_friendlyName()
magnetometer→friendlyName()
magnetometer.get_friendlyName()magnetometer→get_friendlyName()[magnetometer friendlyName]magnetometer.get_friendlyName()magnetometer.get_friendlyName()magnetometer.get_friendlyName()magnetometer→get_friendlyName()magnetometer.get_friendlyName()magnetometer.get_friendlyName()magnetometer.get_friendlyName()magnetometer.get_friendlyName()

Returns a global identifier of the magnetometer in the format MODULE_NAME.FUNCTION_NAME.

js
function get_friendlyName()
cpp
string get_friendlyName()
m
-(NSString*) friendlyName
cs
string get_friendlyName()
java
String get_friendlyName()
py
get_friendlyName()
php
function get_friendlyName()
ts
async get_friendlyName(): Promise<string>
es
async get_friendlyName()
dnp
string get_friendlyName()
cp
string get_friendlyName()

The returned string uses the logical names of the module and of the magnetometer if they are defined, otherwise the serial number of the module and the hardware identifier of the magnetometer (for example: MyCustomName.relay1)

Returns :

a string that uniquely identifies the magnetometer using logical names (ex: MyCustomName.relay1)

On failure, throws an exception or returns YMagnetometer.FRIENDLYNAME_INVALID.

magnetometer→get_functionDescriptor()
magnetometer→functionDescriptor()
magnetometer.get_functionDescriptor()magnetometer→get_functionDescriptor()[magnetometer functionDescriptor]magnetometer.get_functionDescriptor()magnetometer.get_functionDescriptor()magnetometer.get_functionDescriptor()magnetometer.get_functionDescriptor()magnetometer.get_functionDescriptor()magnetometer→get_functionDescriptor()magnetometer.get_functionDescriptor()magnetometer.get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

js
function get_functionDescriptor()
cpp
YFUN_DESCR get_functionDescriptor()
m
-(YFUN_DESCR) functionDescriptor
pas
YFUN_DESCR get_functionDescriptor(): YFUN_DESCR
vb
function get_functionDescriptor() As YFUN_DESCR
cs
YFUN_DESCR get_functionDescriptor()
java
String get_functionDescriptor()
py
get_functionDescriptor()
php
function get_functionDescriptor()
ts
async get_functionDescriptor(): Promise<string>
es
async get_functionDescriptor()

This identifier can be used to test if two instances of YFunction reference the same physical function on the same physical device.

Returns :

an identifier of type YFUN_DESCR.

If the function has never been contacted, the returned value is Y$CLASSNAME$.FUNCTIONDESCRIPTOR_INVALID.

magnetometer→get_functionId()
magnetometer→functionId()
magnetometer.get_functionId()magnetometer→get_functionId()[magnetometer functionId]magnetometer.get_functionId()magnetometer.get_functionId()magnetometer.get_functionId()magnetometer.get_functionId()magnetometer→get_functionId()magnetometer.get_functionId()magnetometer.get_functionId()magnetometer.get_functionId()magnetometer.get_functionId()

Returns the hardware identifier of the magnetometer, without reference to the module.

js
function get_functionId()
cpp
string get_functionId()
m
-(NSString*) functionId
vb
function get_functionId() As String
cs
string get_functionId()
java
String get_functionId()
py
get_functionId()
php
function get_functionId()
ts
async get_functionId(): Promise<string>
es
async get_functionId()
dnp
string get_functionId()
cp
string get_functionId()

For example relay1

Returns :

a string that identifies the magnetometer (ex: relay1)

On failure, throws an exception or returns YMagnetometer.FUNCTIONID_INVALID.

magnetometer→get_hardwareId()
magnetometer→hardwareId()
magnetometer.get_hardwareId()magnetometer→get_hardwareId()[magnetometer hardwareId]magnetometer.get_hardwareId()magnetometer.get_hardwareId()magnetometer.get_hardwareId()magnetometer.get_hardwareId()magnetometer→get_hardwareId()magnetometer.get_hardwareId()magnetometer.get_hardwareId()magnetometer.get_hardwareId()magnetometer.get_hardwareId()

Returns the unique hardware identifier of the magnetometer in the form SERIAL.FUNCTIONID.

js
function get_hardwareId()
cpp
string get_hardwareId()
m
-(NSString*) hardwareId
vb
function get_hardwareId() As String
cs
string get_hardwareId()
java
String get_hardwareId()
py
get_hardwareId()
php
function get_hardwareId()
ts
async get_hardwareId(): Promise<string>
es
async get_hardwareId()
dnp
string get_hardwareId()
cp
string get_hardwareId()

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the magnetometer (for example RELAYLO1-123456.relay1).

Returns :

a string that uniquely identifies the magnetometer (ex: RELAYLO1-123456.relay1)

On failure, throws an exception or returns YMagnetometer.HARDWAREID_INVALID.

magnetometer→get_highestValue()
magnetometer→highestValue()
magnetometer.get_highestValue()magnetometer→get_highestValue()[magnetometer highestValue]magnetometer.get_highestValue()magnetometer.get_highestValue()magnetometer.get_highestValue()magnetometer.get_highestValue()magnetometer.get_highestValue()magnetometer.get_highestValue()magnetometer→get_highestValue()magnetometer.get_highestValue()magnetometer.get_highestValue()magnetometer.get_highestValue()magnetometer.get_highestValue()YMagnetometer get_highestValue

Returns the maximal value observed for the magnetic field since the device was started.

js
function get_highestValue()
cpp
double get_highestValue()
m
-(double) highestValue
pas
double get_highestValue(): double
vb
function get_highestValue() As Double
cs
double get_highestValue()
java
double get_highestValue()
uwp
async Task<double> get_highestValue()
py
get_highestValue()
php
function get_highestValue()
ts
async get_highestValue(): Promise<number>
es
async get_highestValue()
dnp
double get_highestValue()
cp
double get_highestValue()
cmd
YMagnetometer target get_highestValue

Can be reset to an arbitrary value thanks to set_highestValue().

Returns :

a floating point number corresponding to the maximal value observed for the magnetic field since the device was started

On failure, throws an exception or returns YMagnetometer.HIGHESTVALUE_INVALID.

magnetometer→get_logFrequency()
magnetometer→logFrequency()
magnetometer.get_logFrequency()magnetometer→get_logFrequency()[magnetometer logFrequency]magnetometer.get_logFrequency()magnetometer.get_logFrequency()magnetometer.get_logFrequency()magnetometer.get_logFrequency()magnetometer.get_logFrequency()magnetometer.get_logFrequency()magnetometer→get_logFrequency()magnetometer.get_logFrequency()magnetometer.get_logFrequency()magnetometer.get_logFrequency()magnetometer.get_logFrequency()YMagnetometer get_logFrequency

Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

js
function get_logFrequency()
cpp
string get_logFrequency()
m
-(NSString*) logFrequency
pas
string get_logFrequency(): string
vb
function get_logFrequency() As String
cs
string get_logFrequency()
java
String get_logFrequency()
uwp
async Task<string> get_logFrequency()
py
get_logFrequency()
php
function get_logFrequency()
ts
async get_logFrequency(): Promise<string>
es
async get_logFrequency()
dnp
string get_logFrequency()
cp
string get_logFrequency()
cmd
YMagnetometer target get_logFrequency

Returns :

a string corresponding to the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory

On failure, throws an exception or returns YMagnetometer.LOGFREQUENCY_INVALID.

magnetometer→get_logicalName()
magnetometer→logicalName()
magnetometer.get_logicalName()magnetometer→get_logicalName()[magnetometer logicalName]magnetometer.get_logicalName()magnetometer.get_logicalName()magnetometer.get_logicalName()magnetometer.get_logicalName()magnetometer.get_logicalName()magnetometer.get_logicalName()magnetometer→get_logicalName()magnetometer.get_logicalName()magnetometer.get_logicalName()magnetometer.get_logicalName()magnetometer.get_logicalName()YMagnetometer get_logicalName

Returns the logical name of the magnetometer.

js
function get_logicalName()
cpp
string get_logicalName()
m
-(NSString*) logicalName
pas
string get_logicalName(): string
vb
function get_logicalName() As String
cs
string get_logicalName()
java
String get_logicalName()
uwp
async Task<string> get_logicalName()
py
get_logicalName()
php
function get_logicalName()
ts
async get_logicalName(): Promise<string>
es
async get_logicalName()
dnp
string get_logicalName()
cp
string get_logicalName()
cmd
YMagnetometer target get_logicalName

Returns :

a string corresponding to the logical name of the magnetometer.

On failure, throws an exception or returns YMagnetometer.LOGICALNAME_INVALID.

magnetometer→get_lowestValue()
magnetometer→lowestValue()
magnetometer.get_lowestValue()magnetometer→get_lowestValue()[magnetometer lowestValue]magnetometer.get_lowestValue()magnetometer.get_lowestValue()magnetometer.get_lowestValue()magnetometer.get_lowestValue()magnetometer.get_lowestValue()magnetometer.get_lowestValue()magnetometer→get_lowestValue()magnetometer.get_lowestValue()magnetometer.get_lowestValue()magnetometer.get_lowestValue()magnetometer.get_lowestValue()YMagnetometer get_lowestValue

Returns the minimal value observed for the magnetic field since the device was started.

js
function get_lowestValue()
cpp
double get_lowestValue()
m
-(double) lowestValue
pas
double get_lowestValue(): double
vb
function get_lowestValue() As Double
cs
double get_lowestValue()
java
double get_lowestValue()
uwp
async Task<double> get_lowestValue()
py
get_lowestValue()
php
function get_lowestValue()
ts
async get_lowestValue(): Promise<number>
es
async get_lowestValue()
dnp
double get_lowestValue()
cp
double get_lowestValue()
cmd
YMagnetometer target get_lowestValue

Can be reset to an arbitrary value thanks to set_lowestValue().

Returns :

a floating point number corresponding to the minimal value observed for the magnetic field since the device was started

On failure, throws an exception or returns YMagnetometer.LOWESTVALUE_INVALID.

magnetometer→get_module()
magnetometer→module()
magnetometer.get_module()magnetometer→get_module()[magnetometer module]magnetometer.get_module()magnetometer.get_module()magnetometer.get_module()magnetometer.get_module()magnetometer.get_module()magnetometer→get_module()magnetometer.get_module()magnetometer.get_module()magnetometer.get_module()magnetometer.get_module()

Gets the YModule object for the device on which the function is located.

js
function get_module()
cpp
YModule * get_module()
m
-(YModule*) module
pas
TYModule get_module(): TYModule
vb
function get_module() As YModule
cs
YModule get_module()
java
YModule get_module()
py
get_module()
php
function get_module()
ts
async get_module(): Promise<YModule>
es
async get_module()
dnp
YModuleProxy get_module()
cp
YModuleProxy * get_module()

If the function cannot be located on any module, the returned instance of YModule is not shown as on-line.

Returns :

an instance of YModule

magnetometer→get_module_async()
magnetometer→module_async()
magnetometer.get_module_async()

Gets the YModule object for the device on which the function is located (asynchronous version).

js
function get_module_async(callback, context)

If the function cannot be located on any module, the returned YModule object does not show as on-line.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking Firefox JavaScript VM that does not implement context switching during blocking I/O calls. See the documentation section on asynchronous JavasSript calls for more details.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the requested YModule object
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

magnetometer→get_recordedData()
magnetometer→recordedData()
magnetometer.get_recordedData()magnetometer→get_recordedData()[magnetometer recordedData: ]magnetometer.get_recordedData()magnetometer.get_recordedData()magnetometer.get_recordedData()magnetometer.get_recordedData()magnetometer.get_recordedData()magnetometer.get_recordedData()magnetometer→get_recordedData()magnetometer.get_recordedData()magnetometer.get_recordedData()magnetometer.get_recordedData()magnetometer.get_recordedData()YMagnetometer get_recordedData

Retrieves a YDataSet object holding historical data for this sensor, for a specified time interval.

js
function get_recordedData(startTime, endTime)
cpp
YDataSet get_recordedData(double startTime, double endTime)
m
-(YDataSet*) recordedData: (double) startTime
  : (double) endTime
pas
TYDataSet get_recordedData(startTime: double, endTime: double): TYDataSet
vb
function get_recordedData(ByVal startTime As Double,
  ByVal endTime As Double) As YDataSet
cs
YDataSet get_recordedData(double startTime, double endTime)
java
YDataSet get_recordedData(double startTime, double endTime)
uwp
async Task<YDataSet> get_recordedData(double startTime,
  double endTime)
py
get_recordedData(startTime, endTime)
php
function get_recordedData($startTime, $endTime)
ts
async get_recordedData(startTime: number, endTime: number): Promise<YDataSet>
es
async get_recordedData(startTime, endTime)
dnp
YDataSetProxy get_recordedData(double startTime,
  double endTime)
cp
YDataSetProxy* get_recordedData(double startTime,
  double endTime)
cmd
YMagnetometer target get_recordedData startTime endTime

The measures will be retrieved from the data logger, which must have been turned on at the desired time. See the documentation of the YDataSet class for information on how to get an overview of the recorded data, and how to load progressively a large set of measures from the data logger.

This function only works if the device uses a recent firmware, as YDataSet objects are not supported by firmwares older than version 13000.

Parameters :

startTimethe start of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without initial limit.
endTimethe end of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without ending limit.

Returns :

an instance of YDataSet, providing access to historical data. Past measures can be loaded progressively using methods from the YDataSet object.

magnetometer→get_reportFrequency()
magnetometer→reportFrequency()
magnetometer.get_reportFrequency()magnetometer→get_reportFrequency()[magnetometer reportFrequency]magnetometer.get_reportFrequency()magnetometer.get_reportFrequency()magnetometer.get_reportFrequency()magnetometer.get_reportFrequency()magnetometer.get_reportFrequency()magnetometer.get_reportFrequency()magnetometer→get_reportFrequency()magnetometer.get_reportFrequency()magnetometer.get_reportFrequency()magnetometer.get_reportFrequency()magnetometer.get_reportFrequency()YMagnetometer get_reportFrequency

Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

js
function get_reportFrequency()
cpp
string get_reportFrequency()
m
-(NSString*) reportFrequency
pas
string get_reportFrequency(): string
vb
function get_reportFrequency() As String
cs
string get_reportFrequency()
java
String get_reportFrequency()
uwp
async Task<string> get_reportFrequency()
py
get_reportFrequency()
php
function get_reportFrequency()
ts
async get_reportFrequency(): Promise<string>
es
async get_reportFrequency()
dnp
string get_reportFrequency()
cp
string get_reportFrequency()
cmd
YMagnetometer target get_reportFrequency

Returns :

a string corresponding to the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function

On failure, throws an exception or returns YMagnetometer.REPORTFREQUENCY_INVALID.

magnetometer→get_resolution()
magnetometer→resolution()
magnetometer.get_resolution()magnetometer→get_resolution()[magnetometer resolution]magnetometer.get_resolution()magnetometer.get_resolution()magnetometer.get_resolution()magnetometer.get_resolution()magnetometer.get_resolution()magnetometer.get_resolution()magnetometer→get_resolution()magnetometer.get_resolution()magnetometer.get_resolution()magnetometer.get_resolution()magnetometer.get_resolution()YMagnetometer get_resolution

Returns the resolution of the measured values.

js
function get_resolution()
cpp
double get_resolution()
m
-(double) resolution
pas
double get_resolution(): double
vb
function get_resolution() As Double
cs
double get_resolution()
java
double get_resolution()
uwp
async Task<double> get_resolution()
py
get_resolution()
php
function get_resolution()
ts
async get_resolution(): Promise<number>
es
async get_resolution()
dnp
double get_resolution()
cp
double get_resolution()
cmd
YMagnetometer target get_resolution

The resolution corresponds to the numerical precision of the measures, which is not always the same as the actual precision of the sensor. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

a floating point number corresponding to the resolution of the measured values

On failure, throws an exception or returns YMagnetometer.RESOLUTION_INVALID.

magnetometer→get_sensorState()
magnetometer→sensorState()
magnetometer.get_sensorState()magnetometer→get_sensorState()[magnetometer sensorState]magnetometer.get_sensorState()magnetometer.get_sensorState()magnetometer.get_sensorState()magnetometer.get_sensorState()magnetometer.get_sensorState()magnetometer.get_sensorState()magnetometer→get_sensorState()magnetometer.get_sensorState()magnetometer.get_sensorState()magnetometer.get_sensorState()magnetometer.get_sensorState()YMagnetometer get_sensorState

Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.

js
function get_sensorState()
cpp
int get_sensorState()
m
-(int) sensorState
pas
LongInt get_sensorState(): LongInt
vb
function get_sensorState() As Integer
cs
int get_sensorState()
java
int get_sensorState()
uwp
async Task<int> get_sensorState()
py
get_sensorState()
php
function get_sensorState()
ts
async get_sensorState(): Promise<number>
es
async get_sensorState()
dnp
int get_sensorState()
cp
int get_sensorState()
cmd
YMagnetometer target get_sensorState

Returns :

an integer corresponding to the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now

On failure, throws an exception or returns YMagnetometer.SENSORSTATE_INVALID.

magnetometer→get_serialNumber()
magnetometer→serialNumber()
magnetometer.get_serialNumber()magnetometer→get_serialNumber()[magnetometer serialNumber]magnetometer.get_serialNumber()magnetometer.get_serialNumber()magnetometer.get_serialNumber()magnetometer.get_serialNumber()magnetometer.get_serialNumber()magnetometer.get_serialNumber()magnetometer→get_serialNumber()magnetometer.get_serialNumber()magnetometer.get_serialNumber()magnetometer.get_serialNumber()magnetometer.get_serialNumber()YMagnetometer get_serialNumber

Returns the serial number of the module, as set by the factory.

js
function get_serialNumber()
cpp
string get_serialNumber()
m
-(NSString*) serialNumber
pas
string get_serialNumber(): string
vb
function get_serialNumber() As String
cs
string get_serialNumber()
java
String get_serialNumber()
uwp
async Task<string> get_serialNumber()
py
get_serialNumber()
php
function get_serialNumber()
ts
async get_serialNumber(): Promise<string>
es
async get_serialNumber()
dnp
string get_serialNumber()
cp
string get_serialNumber()
cmd
YMagnetometer target get_serialNumber

Returns :

a string corresponding to the serial number of the module, as set by the factory.

On failure, throws an exception or returns YFunction.SERIALNUMBER_INVALID.

magnetometer→get_unit()
magnetometer→unit()
magnetometer.get_unit()magnetometer→get_unit()[magnetometer unit]magnetometer.get_unit()magnetometer.get_unit()magnetometer.get_unit()magnetometer.get_unit()magnetometer.get_unit()magnetometer.get_unit()magnetometer→get_unit()magnetometer.get_unit()magnetometer.get_unit()magnetometer.get_unit()magnetometer.get_unit()YMagnetometer get_unit

Returns the measuring unit for the magnetic field.

js
function get_unit()
cpp
string get_unit()
m
-(NSString*) unit
pas
string get_unit(): string
vb
function get_unit() As String
cs
string get_unit()
java
String get_unit()
uwp
async Task<string> get_unit()
py
get_unit()
php
function get_unit()
ts
async get_unit(): Promise<string>
es
async get_unit()
dnp
string get_unit()
cp
string get_unit()
cmd
YMagnetometer target get_unit

Returns :

a string corresponding to the measuring unit for the magnetic field

On failure, throws an exception or returns YMagnetometer.UNIT_INVALID.

magnetometer→get_userData()
magnetometer→userData()
magnetometer.get_userData()magnetometer→get_userData()[magnetometer userData]magnetometer.get_userData()magnetometer.get_userData()magnetometer.get_userData()magnetometer.get_userData()magnetometer.get_userData()magnetometer→get_userData()magnetometer.get_userData()magnetometer.get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

js
function get_userData()
cpp
void * get_userData()
m
-(id) userData
pas
Tobject get_userData(): Tobject
vb
function get_userData() As Object
cs
object get_userData()
java
Object get_userData()
py
get_userData()
php
function get_userData()
ts
async get_userData(): Promise<object|null>
es
async get_userData()

This attribute is never touched directly by the API, and is at disposal of the caller to store a context.

Returns :

the object stored previously by the caller.

magnetometer→get_xValue()
magnetometer→xValue()
magnetometer.get_xValue()magnetometer→get_xValue()[magnetometer xValue]magnetometer.get_xValue()magnetometer.get_xValue()magnetometer.get_xValue()magnetometer.get_xValue()magnetometer.get_xValue()magnetometer.get_xValue()magnetometer→get_xValue()magnetometer.get_xValue()magnetometer.get_xValue()magnetometer.get_xValue()magnetometer.get_xValue()YMagnetometer get_xValue

Returns the X component of the magnetic field, as a floating point number.

js
function get_xValue()
cpp
double get_xValue()
m
-(double) xValue
pas
double get_xValue(): double
vb
function get_xValue() As Double
cs
double get_xValue()
java
double get_xValue()
uwp
async Task<double> get_xValue()
py
get_xValue()
php
function get_xValue()
ts
async get_xValue(): Promise<number>
es
async get_xValue()
dnp
double get_xValue()
cp
double get_xValue()
cmd
YMagnetometer target get_xValue

Returns :

a floating point number corresponding to the X component of the magnetic field, as a floating point number

On failure, throws an exception or returns YMagnetometer.XVALUE_INVALID.

magnetometer→get_yValue()
magnetometer→yValue()
magnetometer.get_yValue()magnetometer→get_yValue()[magnetometer yValue]magnetometer.get_yValue()magnetometer.get_yValue()magnetometer.get_yValue()magnetometer.get_yValue()magnetometer.get_yValue()magnetometer.get_yValue()magnetometer→get_yValue()magnetometer.get_yValue()magnetometer.get_yValue()magnetometer.get_yValue()magnetometer.get_yValue()YMagnetometer get_yValue

Returns the Y component of the magnetic field, as a floating point number.

js
function get_yValue()
cpp
double get_yValue()
m
-(double) yValue
pas
double get_yValue(): double
vb
function get_yValue() As Double
cs
double get_yValue()
java
double get_yValue()
uwp
async Task<double> get_yValue()
py
get_yValue()
php
function get_yValue()
ts
async get_yValue(): Promise<number>
es
async get_yValue()
dnp
double get_yValue()
cp
double get_yValue()
cmd
YMagnetometer target get_yValue

Returns :

a floating point number corresponding to the Y component of the magnetic field, as a floating point number

On failure, throws an exception or returns YMagnetometer.YVALUE_INVALID.

magnetometer→get_zValue()
magnetometer→zValue()
magnetometer.get_zValue()magnetometer→get_zValue()[magnetometer zValue]magnetometer.get_zValue()magnetometer.get_zValue()magnetometer.get_zValue()magnetometer.get_zValue()magnetometer.get_zValue()magnetometer.get_zValue()magnetometer→get_zValue()magnetometer.get_zValue()magnetometer.get_zValue()magnetometer.get_zValue()magnetometer.get_zValue()YMagnetometer get_zValue

Returns the Z component of the magnetic field, as a floating point number.

js
function get_zValue()
cpp
double get_zValue()
m
-(double) zValue
pas
double get_zValue(): double
vb
function get_zValue() As Double
cs
double get_zValue()
java
double get_zValue()
uwp
async Task<double> get_zValue()
py
get_zValue()
php
function get_zValue()
ts
async get_zValue(): Promise<number>
es
async get_zValue()
dnp
double get_zValue()
cp
double get_zValue()
cmd
YMagnetometer target get_zValue

Returns :

a floating point number corresponding to the Z component of the magnetic field, as a floating point number

On failure, throws an exception or returns YMagnetometer.ZVALUE_INVALID.

magnetometer→isOnline()magnetometer.isOnline()magnetometer→isOnline()[magnetometer isOnline]magnetometer.isOnline()magnetometer.isOnline()magnetometer.isOnline()magnetometer.isOnline()magnetometer.isOnline()magnetometer→isOnline()magnetometer.isOnline()magnetometer.isOnline()magnetometer.isOnline()magnetometer.isOnline()

Checks if the magnetometer is currently reachable, without raising any error.

js
function isOnline()
cpp
bool isOnline()
m
-(BOOL) isOnline
pas
boolean isOnline(): boolean
vb
function isOnline() As Boolean
cs
bool isOnline()
java
boolean isOnline()
py
isOnline()
php
function isOnline()
ts
async isOnline(): Promise<boolean>
es
async isOnline()
dnp
bool isOnline()
cp
bool isOnline()

If there is a cached value for the magnetometer in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the magnetometer.

Returns :

true if the magnetometer can be reached, and false otherwise

magnetometer→isOnline_async()magnetometer.isOnline_async()

Checks if the magnetometer is currently reachable, without raising any error (asynchronous version).

js
function isOnline_async(callback, context)

If there is a cached value for the magnetometer in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the requested function.

This asynchronous version exists only in Javascript. It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the boolean result
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

magnetometer→isReadOnly()magnetometer→isReadOnly()[magnetometer isReadOnly]magnetometer.isReadOnly()magnetometer.isReadOnly()magnetometer.isReadOnly()magnetometer.isReadOnly()magnetometer.isReadOnly()magnetometer.isReadOnly()magnetometer→isReadOnly()magnetometer.isReadOnly()magnetometer.isReadOnly()magnetometer.isReadOnly()magnetometer.isReadOnly()YMagnetometer isReadOnly

Test if the function is readOnly.

cpp
bool isReadOnly()
m
-(bool) isReadOnly
pas
boolean isReadOnly(): boolean
vb
function isReadOnly() As Boolean
cs
bool isReadOnly()
java
boolean isReadOnly()
uwp
async Task<bool> isReadOnly()
py
isReadOnly()
php
function isReadOnly()
ts
async isReadOnly(): Promise<boolean>
es
async isReadOnly()
dnp
bool isReadOnly()
cp
bool isReadOnly()
cmd
YMagnetometer target isReadOnly

Return true if the function is write protected or that the function is not available.

Returns :

true if the function is readOnly or not online.

magnetometer→isSensorReady()YMagnetometer isSensorReady

Checks if the sensor is currently able to provide an up-to-date measure.

cmd
YMagnetometer target isSensorReady

Returns false if the device is unreachable, or if the sensor does not have a current measure to transmit. No exception is raised if there is an error while trying to contact the device hosting $THEFUNCTION$.

Returns :

true if the sensor can provide an up-to-date measure, and false otherwise

magnetometer→load()magnetometer.load()magnetometer→load()[magnetometer load: ]magnetometer.load()magnetometer.load()magnetometer.load()magnetometer.load()magnetometer.load()magnetometer→load()magnetometer.load()magnetometer.load()

Preloads the magnetometer cache with a specified validity duration.

js
function load(msValidity)
cpp
YRETCODE load(int msValidity)
m
-(YRETCODE) load: (u64) msValidity
pas
YRETCODE load(msValidity: u64): YRETCODE
vb
function load(ByVal msValidity As Long) As YRETCODE
cs
YRETCODE load(ulong msValidity)
java
int load(long msValidity)
py
load(msValidity)
php
function load($msValidity)
ts
async load(msValidity: number): Promise<number>
es
async load(msValidity)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

Parameters :

msValidityan integer corresponding to the validity attributed to the loaded function parameters, in milliseconds

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→loadAttribute()magnetometer.loadAttribute()magnetometer→loadAttribute()[magnetometer loadAttribute: ]magnetometer.loadAttribute()magnetometer.loadAttribute()magnetometer.loadAttribute()magnetometer.loadAttribute()magnetometer.loadAttribute()magnetometer.loadAttribute()magnetometer→loadAttribute()magnetometer.loadAttribute()magnetometer.loadAttribute()magnetometer.loadAttribute()magnetometer.loadAttribute()

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

js
function loadAttribute(attrName)
cpp
string loadAttribute(string attrName)
m
-(NSString*) loadAttribute: (NSString*) attrName
pas
string loadAttribute(attrName: string): string
vb
function loadAttribute(ByVal attrName As String) As String
cs
string loadAttribute(string attrName)
java
String loadAttribute(String attrName)
uwp
async Task<string> loadAttribute(string attrName)
py
loadAttribute(attrName)
php
function loadAttribute($attrName)
ts
async loadAttribute(attrName: string): Promise<string>
es
async loadAttribute(attrName)
dnp
string loadAttribute(string attrName)
cp
string loadAttribute(string attrName)

Parameters :

attrNamethe name of the requested attribute

Returns :

a string with the value of the the attribute

On failure, throws an exception or returns an empty string.

magnetometer→loadCalibrationPoints()magnetometer.loadCalibrationPoints()magnetometer→loadCalibrationPoints()[magnetometer loadCalibrationPoints: ]magnetometer.loadCalibrationPoints()magnetometer.loadCalibrationPoints()magnetometer.loadCalibrationPoints()magnetometer.loadCalibrationPoints()magnetometer.loadCalibrationPoints()magnetometer.loadCalibrationPoints()magnetometer→loadCalibrationPoints()magnetometer.loadCalibrationPoints()magnetometer.loadCalibrationPoints()YMagnetometer loadCalibrationPoints

Retrieves error correction data points previously entered using the method calibrateFromPoints.

js
function loadCalibrationPoints(rawValues, refValues)
cpp
int loadCalibrationPoints(vector<double> rawValues,
  vector<double> refValues)
m
-(int) loadCalibrationPoints: (NSMutableArray*) rawValues
  : (NSMutableArray*) refValues
pas
LongInt loadCalibrationPoints(var rawValues: TDoubleArray,
  var refValues: TDoubleArray): LongInt
vb
procedure loadCalibrationPoints(ByVal rawValues As List(Of)
cs
int loadCalibrationPoints(List<double> rawValues,
  List<double> refValues)
java
int loadCalibrationPoints(ArrayList<Double> rawValues,
  ArrayList<Double> refValues)
uwp
async Task<int> loadCalibrationPoints(List<double> rawValues,
  List<double> refValues)
py
loadCalibrationPoints(rawValues, refValues)
php
function loadCalibrationPoints(&$rawValues, &$refValues)
ts
async loadCalibrationPoints(rawValues: number[], refValues: number[]): Promise<number>
es
async loadCalibrationPoints(rawValues, refValues)
cmd
YMagnetometer target loadCalibrationPoints rawValues refValues

Parameters :

rawValuesarray of floating point numbers, that will be filled by the function with the raw sensor values for the correction points.
refValuesarray of floating point numbers, that will be filled by the function with the desired values for the correction points.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→load_async()magnetometer.load_async()

Preloads the magnetometer cache with a specified validity duration (asynchronous version).

js
function load_async(msValidity, callback, context)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking the JavaScript virtual machine.

Parameters :

msValidityan integer corresponding to the validity of the loaded function parameters, in milliseconds
callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the error code (or YAPI.SUCCESS)
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

magnetometer→muteValueCallbacks()magnetometer.muteValueCallbacks()magnetometer→muteValueCallbacks()[magnetometer muteValueCallbacks]magnetometer.muteValueCallbacks()magnetometer.muteValueCallbacks()magnetometer.muteValueCallbacks()magnetometer.muteValueCallbacks()magnetometer.muteValueCallbacks()magnetometer.muteValueCallbacks()magnetometer→muteValueCallbacks()magnetometer.muteValueCallbacks()magnetometer.muteValueCallbacks()magnetometer.muteValueCallbacks()magnetometer.muteValueCallbacks()YMagnetometer muteValueCallbacks

Disables the propagation of every new advertised value to the parent hub.

js
function muteValueCallbacks()
cpp
int muteValueCallbacks()
m
-(int) muteValueCallbacks
pas
LongInt muteValueCallbacks(): LongInt
vb
function muteValueCallbacks() As Integer
cs
int muteValueCallbacks()
java
int muteValueCallbacks()
uwp
async Task<int> muteValueCallbacks()
py
muteValueCallbacks()
php
function muteValueCallbacks()
ts
async muteValueCallbacks(): Promise<number>
es
async muteValueCallbacks()
dnp
int muteValueCallbacks()
cp
int muteValueCallbacks()
cmd
YMagnetometer target muteValueCallbacks

You can use this function to save bandwidth and CPU on computers with limited resources, or to prevent unwanted invocations of the HTTP callback. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→nextMagnetometer()magnetometer.nextMagnetometer()magnetometer→nextMagnetometer()[magnetometer nextMagnetometer]magnetometer.nextMagnetometer()magnetometer.nextMagnetometer()magnetometer.nextMagnetometer()magnetometer.nextMagnetometer()magnetometer.nextMagnetometer()magnetometer.nextMagnetometer()magnetometer→nextMagnetometer()magnetometer.nextMagnetometer()magnetometer.nextMagnetometer()

Continues the enumeration of magnetometers started using yFirstMagnetometer().

js
function nextMagnetometer()
cpp
YMagnetometer * nextMagnetometer()
m
-(nullable YMagnetometer*) nextMagnetometer
pas
TYMagnetometer nextMagnetometer(): TYMagnetometer
vb
function nextMagnetometer() As YMagnetometer
cs
YMagnetometer nextMagnetometer()
java
YMagnetometer nextMagnetometer()
uwp
YMagnetometer nextMagnetometer()
py
nextMagnetometer()
php
function nextMagnetometer()
ts
nextMagnetometer(): YMagnetometer | null
es
nextMagnetometer()

Caution: You can't make any assumption about the returned magnetometers order. If you want to find a specific a magnetometer, use Magnetometer.findMagnetometer() and a hardwareID or a logical name.

Returns :

a pointer to a YMagnetometer object, corresponding to a magnetometer currently online, or a null pointer if there are no more magnetometers to enumerate.

magnetometer→registerTimedReportCallback()magnetometer.registerTimedReportCallback()magnetometer→registerTimedReportCallback()[magnetometer registerTimedReportCallback: ]magnetometer.registerTimedReportCallback()magnetometer.registerTimedReportCallback()magnetometer.registerTimedReportCallback()magnetometer.registerTimedReportCallback()magnetometer.registerTimedReportCallback()magnetometer.registerTimedReportCallback()magnetometer→registerTimedReportCallback()magnetometer.registerTimedReportCallback()magnetometer.registerTimedReportCallback()

Registers the callback function that is invoked on every periodic timed notification.

js
function registerTimedReportCallback(callback)
cpp
int registerTimedReportCallback(YMagnetometerTimedReportCallback callback)
m
-(int) registerTimedReportCallback: (YMagnetometerTimedReportCallback _Nullable) callback
pas
LongInt registerTimedReportCallback(callback: TYMagnetometerTimedReportCallback): LongInt
vb
function registerTimedReportCallback(ByVal callback As YMagnetometerTimedReportCallback) As Integer
cs
int registerTimedReportCallback(TimedReportCallback callback)
java
int registerTimedReportCallback(TimedReportCallback callback)
uwp
async Task<int> registerTimedReportCallback(TimedReportCallback callback)
py
registerTimedReportCallback(callback)
php
function registerTimedReportCallback($callback)
ts
async registerTimedReportCallback(callback: YMagnetometerTimedReportCallback | null): Promise<number>
es
async registerTimedReportCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and an YMeasure object describing the new advertised value.

magnetometer→registerValueCallback()magnetometer.registerValueCallback()magnetometer→registerValueCallback()[magnetometer registerValueCallback: ]magnetometer.registerValueCallback()magnetometer.registerValueCallback()magnetometer.registerValueCallback()magnetometer.registerValueCallback()magnetometer.registerValueCallback()magnetometer.registerValueCallback()magnetometer→registerValueCallback()magnetometer.registerValueCallback()magnetometer.registerValueCallback()

Registers the callback function that is invoked on every change of advertised value.

js
function registerValueCallback(callback)
cpp
int registerValueCallback(YMagnetometerValueCallback callback)
m
-(int) registerValueCallback: (YMagnetometerValueCallback _Nullable) callback
pas
LongInt registerValueCallback(callback: TYMagnetometerValueCallback): LongInt
vb
function registerValueCallback(ByVal callback As YMagnetometerValueCallback) As Integer
cs
int registerValueCallback(ValueCallback callback)
java
int registerValueCallback(UpdateCallback callback)
uwp
async Task<int> registerValueCallback(ValueCallback callback)
py
registerValueCallback(callback)
php
function registerValueCallback($callback)
ts
async registerValueCallback(callback: YMagnetometerValueCallback | null): Promise<number>
es
async registerValueCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and the character string describing the new advertised value.

magnetometer→set_advMode()
magnetometer→setAdvMode()
magnetometer.set_advMode()magnetometer→set_advMode()[magnetometer setAdvMode: ]magnetometer.set_advMode()magnetometer.set_advMode()magnetometer.set_advMode()magnetometer.set_advMode()magnetometer.set_advMode()magnetometer.set_advMode()magnetometer→set_advMode()magnetometer.set_advMode()magnetometer.set_advMode()magnetometer.set_advMode()magnetometer.set_advMode()YMagnetometer set_advMode

Changes the measuring mode used for the advertised value pushed to the parent hub.

js
function set_advMode(newval)
cpp
int set_advMode(Y_ADVMODE_enum newval)
m
-(int) setAdvMode: (Y_ADVMODE_enum) newval
pas
integer set_advMode(newval: Integer): integer
vb
function set_advMode(ByVal newval As Integer) As Integer
cs
int set_advMode(int newval)
java
int set_advMode(int newval)
uwp
async Task<int> set_advMode(int newval)
py
set_advMode(newval)
php
function set_advMode($newval)
ts
async set_advMode(newval: YSensor_AdvMode): Promise<number>
es
async set_advMode(newval)
dnp
int set_advMode(int newval)
cp
int set_advMode(int newval)
cmd
YMagnetometer target set_advMode newval

Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala value among YMagnetometer.ADVMODE_IMMEDIATE, YMagnetometer.ADVMODE_PERIOD_AVG, YMagnetometer.ADVMODE_PERIOD_MIN and YMagnetometer.ADVMODE_PERIOD_MAX corresponding to the measuring mode used for the advertised value pushed to the parent hub

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→set_bandwidth()
magnetometer→setBandwidth()
magnetometer.set_bandwidth()magnetometer→set_bandwidth()[magnetometer setBandwidth: ]magnetometer.set_bandwidth()magnetometer.set_bandwidth()magnetometer.set_bandwidth()magnetometer.set_bandwidth()magnetometer.set_bandwidth()magnetometer.set_bandwidth()magnetometer→set_bandwidth()magnetometer.set_bandwidth()magnetometer.set_bandwidth()magnetometer.set_bandwidth()magnetometer.set_bandwidth()YMagnetometer set_bandwidth

Changes the measure update frequency, measured in Hz.

js
function set_bandwidth(newval)
cpp
int set_bandwidth(int newval)
m
-(int) setBandwidth: (int) newval
pas
integer set_bandwidth(newval: LongInt): integer
vb
function set_bandwidth(ByVal newval As Integer) As Integer
cs
int set_bandwidth(int newval)
java
int set_bandwidth(int newval)
uwp
async Task<int> set_bandwidth(int newval)
py
set_bandwidth(newval)
php
function set_bandwidth($newval)
ts
async set_bandwidth(newval: number): Promise<number>
es
async set_bandwidth(newval)
dnp
int set_bandwidth(int newval)
cp
int set_bandwidth(int newval)
cmd
YMagnetometer target set_bandwidth newval

When the frequency is lower, the device performs averaging. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvalan integer corresponding to the measure update frequency, measured in Hz

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→set_highestValue()
magnetometer→setHighestValue()
magnetometer.set_highestValue()magnetometer→set_highestValue()[magnetometer setHighestValue: ]magnetometer.set_highestValue()magnetometer.set_highestValue()magnetometer.set_highestValue()magnetometer.set_highestValue()magnetometer.set_highestValue()magnetometer.set_highestValue()magnetometer→set_highestValue()magnetometer.set_highestValue()magnetometer.set_highestValue()magnetometer.set_highestValue()magnetometer.set_highestValue()YMagnetometer set_highestValue

Changes the recorded maximal value observed.

js
function set_highestValue(newval)
cpp
int set_highestValue(double newval)
m
-(int) setHighestValue: (double) newval
pas
integer set_highestValue(newval: double): integer
vb
function set_highestValue(ByVal newval As Double) As Integer
cs
int set_highestValue(double newval)
java
int set_highestValue(double newval)
uwp
async Task<int> set_highestValue(double newval)
py
set_highestValue(newval)
php
function set_highestValue($newval)
ts
async set_highestValue(newval: number): Promise<number>
es
async set_highestValue(newval)
dnp
int set_highestValue(double newval)
cp
int set_highestValue(double newval)
cmd
YMagnetometer target set_highestValue newval

Can be used to reset the value returned by get_lowestValue().

Parameters :

newvala floating point number corresponding to the recorded maximal value observed

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→set_logFrequency()
magnetometer→setLogFrequency()
magnetometer.set_logFrequency()magnetometer→set_logFrequency()[magnetometer setLogFrequency: ]magnetometer.set_logFrequency()magnetometer.set_logFrequency()magnetometer.set_logFrequency()magnetometer.set_logFrequency()magnetometer.set_logFrequency()magnetometer.set_logFrequency()magnetometer→set_logFrequency()magnetometer.set_logFrequency()magnetometer.set_logFrequency()magnetometer.set_logFrequency()magnetometer.set_logFrequency()YMagnetometer set_logFrequency

Changes the datalogger recording frequency for this function.

js
function set_logFrequency(newval)
cpp
int set_logFrequency(string newval)
m
-(int) setLogFrequency: (NSString*) newval
pas
integer set_logFrequency(newval: string): integer
vb
function set_logFrequency(ByVal newval As String) As Integer
cs
int set_logFrequency(string newval)
java
int set_logFrequency(String newval)
uwp
async Task<int> set_logFrequency(string newval)
py
set_logFrequency(newval)
php
function set_logFrequency($newval)
ts
async set_logFrequency(newval: string): Promise<number>
es
async set_logFrequency(newval)
dnp
int set_logFrequency(string newval)
cp
int set_logFrequency(string newval)
cmd
YMagnetometer target set_logFrequency newval

The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (eg. "4/h"). To disable recording for this function, use the value "OFF". Note that setting the datalogger recording frequency to a greater value than the sensor native sampling frequency is useless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the datalogger recording frequency for this function

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→set_logicalName()
magnetometer→setLogicalName()
magnetometer.set_logicalName()magnetometer→set_logicalName()[magnetometer setLogicalName: ]magnetometer.set_logicalName()magnetometer.set_logicalName()magnetometer.set_logicalName()magnetometer.set_logicalName()magnetometer.set_logicalName()magnetometer.set_logicalName()magnetometer→set_logicalName()magnetometer.set_logicalName()magnetometer.set_logicalName()magnetometer.set_logicalName()magnetometer.set_logicalName()YMagnetometer set_logicalName

Changes the logical name of the magnetometer.

js
function set_logicalName(newval)
cpp
int set_logicalName(string newval)
m
-(int) setLogicalName: (NSString*) newval
pas
integer set_logicalName(newval: string): integer
vb
function set_logicalName(ByVal newval As String) As Integer
cs
int set_logicalName(string newval)
java
int set_logicalName(String newval)
uwp
async Task<int> set_logicalName(string newval)
py
set_logicalName(newval)
php
function set_logicalName($newval)
ts
async set_logicalName(newval: string): Promise<number>
es
async set_logicalName(newval)
dnp
int set_logicalName(string newval)
cp
int set_logicalName(string newval)
cmd
YMagnetometer target set_logicalName newval

You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the logical name of the magnetometer.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→set_lowestValue()
magnetometer→setLowestValue()
magnetometer.set_lowestValue()magnetometer→set_lowestValue()[magnetometer setLowestValue: ]magnetometer.set_lowestValue()magnetometer.set_lowestValue()magnetometer.set_lowestValue()magnetometer.set_lowestValue()magnetometer.set_lowestValue()magnetometer.set_lowestValue()magnetometer→set_lowestValue()magnetometer.set_lowestValue()magnetometer.set_lowestValue()magnetometer.set_lowestValue()magnetometer.set_lowestValue()YMagnetometer set_lowestValue

Changes the recorded minimal value observed.

js
function set_lowestValue(newval)
cpp
int set_lowestValue(double newval)
m
-(int) setLowestValue: (double) newval
pas
integer set_lowestValue(newval: double): integer
vb
function set_lowestValue(ByVal newval As Double) As Integer
cs
int set_lowestValue(double newval)
java
int set_lowestValue(double newval)
uwp
async Task<int> set_lowestValue(double newval)
py
set_lowestValue(newval)
php
function set_lowestValue($newval)
ts
async set_lowestValue(newval: number): Promise<number>
es
async set_lowestValue(newval)
dnp
int set_lowestValue(double newval)
cp
int set_lowestValue(double newval)
cmd
YMagnetometer target set_lowestValue newval

Can be used to reset the value returned by get_lowestValue().

Parameters :

newvala floating point number corresponding to the recorded minimal value observed

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→set_reportFrequency()
magnetometer→setReportFrequency()
magnetometer.set_reportFrequency()magnetometer→set_reportFrequency()[magnetometer setReportFrequency: ]magnetometer.set_reportFrequency()magnetometer.set_reportFrequency()magnetometer.set_reportFrequency()magnetometer.set_reportFrequency()magnetometer.set_reportFrequency()magnetometer.set_reportFrequency()magnetometer→set_reportFrequency()magnetometer.set_reportFrequency()magnetometer.set_reportFrequency()magnetometer.set_reportFrequency()magnetometer.set_reportFrequency()YMagnetometer set_reportFrequency

Changes the timed value notification frequency for this function.

js
function set_reportFrequency(newval)
cpp
int set_reportFrequency(string newval)
m
-(int) setReportFrequency: (NSString*) newval
pas
integer set_reportFrequency(newval: string): integer
vb
function set_reportFrequency(ByVal newval As String) As Integer
cs
int set_reportFrequency(string newval)
java
int set_reportFrequency(String newval)
uwp
async Task<int> set_reportFrequency(string newval)
py
set_reportFrequency(newval)
php
function set_reportFrequency($newval)
ts
async set_reportFrequency(newval: string): Promise<number>
es
async set_reportFrequency(newval)
dnp
int set_reportFrequency(string newval)
cp
int set_reportFrequency(string newval)
cmd
YMagnetometer target set_reportFrequency newval

The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (e.g. "4/h"). To disable timed value notifications for this function, use the value "OFF". Note that setting the timed value notification frequency to a greater value than the sensor native sampling frequency is unless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the timed value notification frequency for this function

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→set_resolution()
magnetometer→setResolution()
magnetometer.set_resolution()magnetometer→set_resolution()[magnetometer setResolution: ]magnetometer.set_resolution()magnetometer.set_resolution()magnetometer.set_resolution()magnetometer.set_resolution()magnetometer.set_resolution()magnetometer.set_resolution()magnetometer→set_resolution()magnetometer.set_resolution()magnetometer.set_resolution()magnetometer.set_resolution()magnetometer.set_resolution()YMagnetometer set_resolution

Changes the resolution of the measured physical values.

js
function set_resolution(newval)
cpp
int set_resolution(double newval)
m
-(int) setResolution: (double) newval
pas
integer set_resolution(newval: double): integer
vb
function set_resolution(ByVal newval As Double) As Integer
cs
int set_resolution(double newval)
java
int set_resolution(double newval)
uwp
async Task<int> set_resolution(double newval)
py
set_resolution(newval)
php
function set_resolution($newval)
ts
async set_resolution(newval: number): Promise<number>
es
async set_resolution(newval)
dnp
int set_resolution(double newval)
cp
int set_resolution(double newval)
cmd
YMagnetometer target set_resolution newval

The resolution corresponds to the numerical precision when displaying value. It does not change the precision of the measure itself. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala floating point number corresponding to the resolution of the measured physical values

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→set_userData()
magnetometer→setUserData()
magnetometer.set_userData()magnetometer→set_userData()[magnetometer setUserData: ]magnetometer.set_userData()magnetometer.set_userData()magnetometer.set_userData()magnetometer.set_userData()magnetometer.set_userData()magnetometer→set_userData()magnetometer.set_userData()magnetometer.set_userData()

Stores a user context provided as argument in the userData attribute of the function.

js
function set_userData(data)
cpp
void set_userData(void * data)
m
-(void) setUserData: (id) data
pas
set_userData(data: Tobject)
vb
procedure set_userData(ByVal data As Object)
cs
void set_userData(object data)
java
void set_userData(Object data)
py
set_userData(data)
php
function set_userData($data)
ts
async set_userData(data: object|null): Promise<void>
es
async set_userData(data)

This attribute is never touched by the API, and is at disposal of the caller to store a context.

Parameters :

dataany kind of object to be stored

magnetometer→startDataLogger()magnetometer.startDataLogger()magnetometer→startDataLogger()[magnetometer startDataLogger]magnetometer.startDataLogger()magnetometer.startDataLogger()magnetometer.startDataLogger()magnetometer.startDataLogger()magnetometer.startDataLogger()magnetometer.startDataLogger()magnetometer→startDataLogger()magnetometer.startDataLogger()magnetometer.startDataLogger()magnetometer.startDataLogger()magnetometer.startDataLogger()YMagnetometer startDataLogger

Starts the data logger on the device.

js
function startDataLogger()
cpp
int startDataLogger()
m
-(int) startDataLogger
pas
LongInt startDataLogger(): LongInt
vb
function startDataLogger() As Integer
cs
int startDataLogger()
java
int startDataLogger()
uwp
async Task<int> startDataLogger()
py
startDataLogger()
php
function startDataLogger()
ts
async startDataLogger(): Promise<number>
es
async startDataLogger()
dnp
int startDataLogger()
cp
int startDataLogger()
cmd
YMagnetometer target startDataLogger

Note that the data logger will only save the measures on this sensor if the logFrequency is not set to "OFF".

Returns :

YAPI.SUCCESS if the call succeeds.

magnetometer→stopDataLogger()magnetometer.stopDataLogger()magnetometer→stopDataLogger()[magnetometer stopDataLogger]magnetometer.stopDataLogger()magnetometer.stopDataLogger()magnetometer.stopDataLogger()magnetometer.stopDataLogger()magnetometer.stopDataLogger()magnetometer.stopDataLogger()magnetometer→stopDataLogger()magnetometer.stopDataLogger()magnetometer.stopDataLogger()magnetometer.stopDataLogger()magnetometer.stopDataLogger()YMagnetometer stopDataLogger

Stops the datalogger on the device.

js
function stopDataLogger()
cpp
int stopDataLogger()
m
-(int) stopDataLogger
pas
LongInt stopDataLogger(): LongInt
vb
function stopDataLogger() As Integer
cs
int stopDataLogger()
java
int stopDataLogger()
uwp
async Task<int> stopDataLogger()
py
stopDataLogger()
php
function stopDataLogger()
ts
async stopDataLogger(): Promise<number>
es
async stopDataLogger()
dnp
int stopDataLogger()
cp
int stopDataLogger()
cmd
YMagnetometer target stopDataLogger

Returns :

YAPI.SUCCESS if the call succeeds.

magnetometer→unmuteValueCallbacks()magnetometer.unmuteValueCallbacks()magnetometer→unmuteValueCallbacks()[magnetometer unmuteValueCallbacks]magnetometer.unmuteValueCallbacks()magnetometer.unmuteValueCallbacks()magnetometer.unmuteValueCallbacks()magnetometer.unmuteValueCallbacks()magnetometer.unmuteValueCallbacks()magnetometer.unmuteValueCallbacks()magnetometer→unmuteValueCallbacks()magnetometer.unmuteValueCallbacks()magnetometer.unmuteValueCallbacks()magnetometer.unmuteValueCallbacks()magnetometer.unmuteValueCallbacks()YMagnetometer unmuteValueCallbacks

Re-enables the propagation of every new advertised value to the parent hub.

js
function unmuteValueCallbacks()
cpp
int unmuteValueCallbacks()
m
-(int) unmuteValueCallbacks
pas
LongInt unmuteValueCallbacks(): LongInt
vb
function unmuteValueCallbacks() As Integer
cs
int unmuteValueCallbacks()
java
int unmuteValueCallbacks()
uwp
async Task<int> unmuteValueCallbacks()
py
unmuteValueCallbacks()
php
function unmuteValueCallbacks()
ts
async unmuteValueCallbacks(): Promise<number>
es
async unmuteValueCallbacks()
dnp
int unmuteValueCallbacks()
cp
int unmuteValueCallbacks()
cmd
YMagnetometer target unmuteValueCallbacks

This function reverts the effect of a previous call to muteValueCallbacks(). Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

magnetometer→wait_async()magnetometer.wait_async()magnetometer.wait_async()magnetometer.wait_async()

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

js
function wait_async(callback, context)
ts
wait_async(callback: Function, context: object)
es
wait_async(callback, context)

The callback function can therefore freely issue synchronous or asynchronous commands, without risking to block the JavaScript VM.

Parameters :

callbackcallback function that is invoked when all pending commands on the module are completed. The callback function receives two arguments: the caller-specific context object and the receiving function object.
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing.

24.5. Class YRefFrame

3D reference frame configuration interface, available for instance in the Yocto-3D-V2 or the Yocto-Inclinometer

The YRefFrame class is used to setup the base orientation of the Yoctopuce inertial sensors. Thanks to this, orientation functions relative to the earth surface plane can use the proper reference frame. For some devices, the class also implements a tridimensional sensor calibration process, which can compensate for local variations of standard gravity and improve the precision of the tilt sensors.

In order to use the functions described here, you should include:

es
in HTML: <script src="../../lib/yocto_refframe.js"></script>
in node.js: require('yoctolib-es2017/yocto_refframe.js');
js
<script type='text/javascript' src='yocto_refframe.js'></script>
cpp
#include "yocto_refframe.h"
m
#import "yocto_refframe.h"
pas
uses yocto_refframe;
vb
yocto_refframe.vb
cs
yocto_refframe.cs
java
import com.yoctopuce.YoctoAPI.YRefFrame;
uwp
import com.yoctopuce.YoctoAPI.YRefFrame;
py
from yocto_refframe import *
php
require_once('yocto_refframe.php');
ts
in HTML: import { YRefFrame } from '../../dist/esm/yocto_refframe.js';
in Node.js: import { YRefFrame } from 'yoctolib-cjs/yocto_refframe.js';
dnp
import YoctoProxyAPI.YRefFrameProxy
cp
#include "yocto_refframe_proxy.h"
vi
YRefFrame.vi
ml
import YoctoProxyAPI.YRefFrameProxy
Global functions
YRefFrame.FindRefFrame(func)

Retrieves a reference frame for a given identifier.

YRefFrame.FindRefFrameInContext(yctx, func)

Retrieves a reference frame for a given identifier in a YAPI context.

YRefFrame.FirstRefFrame()

Starts the enumeration of reference frames currently accessible.

YRefFrame.FirstRefFrameInContext(yctx)

Starts the enumeration of reference frames currently accessible.

YRefFrame.GetSimilarFunctions()

Enumerates all functions of type RefFrame available on the devices currently reachable by the library, and returns their unique hardware ID.

YRefFrame properties
refframe→AdvertisedValue [read-only]

Short string representing the current state of the function.

refframe→Bearing [writable]

Reference bearing used by the compass.

refframe→FriendlyName [read-only]

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

refframe→FunctionId [read-only]

Hardware identifier of the reference frame, without reference to the module.

refframe→FusionMode [writable]

Sensor fusion mode.

refframe→HardwareId [read-only]

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

refframe→IsOnline [read-only]

Checks if the function is currently reachable.

refframe→LogicalName [writable]

Logical name of the function.

refframe→SerialNumber [read-only]

Serial number of the module, as set by the factory.

YRefFrame methods
refframe→cancel3DCalibration()

Aborts the sensors tridimensional calibration process et restores normal settings.

refframe→clearCache()

Invalidates the cache.

refframe→describe()

Returns a short text that describes unambiguously the instance of the reference frame in the form TYPE(NAME)=SERIAL.FUNCTIONID.

refframe→get_3DCalibrationHint()

Returns instructions to proceed to the tridimensional calibration initiated with method start3DCalibration.

refframe→get_3DCalibrationLogMsg()

Returns the latest log message from the calibration process.

refframe→get_3DCalibrationProgress()

Returns the global process indicator for the tridimensional calibration initiated with method start3DCalibration.

refframe→get_3DCalibrationStage()

Returns index of the current stage of the calibration initiated with method start3DCalibration.

refframe→get_3DCalibrationStageProgress()

Returns the process indicator for the current stage of the calibration initiated with method start3DCalibration.

refframe→get_advertisedValue()

Returns the current value of the reference frame (no more than 6 characters).

refframe→get_bearing()

Returns the reference bearing used by the compass.

refframe→get_calibrationState()

Returns the 3D sensor calibration state (Yocto-3D-V2 only).

refframe→get_errorMessage()

Returns the error message of the latest error with the reference frame.

refframe→get_errorType()

Returns the numerical error code of the latest error with the reference frame.

refframe→get_friendlyName()

Returns a global identifier of the reference frame in the format MODULE_NAME.FUNCTION_NAME.

refframe→get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

refframe→get_functionId()

Returns the hardware identifier of the reference frame, without reference to the module.

refframe→get_fusionMode()

Returns the sensor fusion mode.

refframe→get_hardwareId()

Returns the unique hardware identifier of the reference frame in the form SERIAL.FUNCTIONID.

refframe→get_logicalName()

Returns the logical name of the reference frame.

refframe→get_measureQuality()

Returns estimated quality of the orientation (Yocto-3D-V2 only).

refframe→get_module()

Gets the YModule object for the device on which the function is located.

refframe→get_module_async(callback, context)

Gets the YModule object for the device on which the function is located (asynchronous version).

refframe→get_mountOrientation()

Returns the installation orientation of the device, as configured in order to define the reference frame for the compass and the pitch/roll tilt sensors.

refframe→get_mountPosition()

Returns the installation position of the device, as configured in order to define the reference frame for the compass and the pitch/roll tilt sensors.

refframe→get_serialNumber()

Returns the serial number of the module, as set by the factory.

refframe→get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

refframe→isOnline()

Checks if the reference frame is currently reachable, without raising any error.

refframe→isOnline_async(callback, context)

Checks if the reference frame is currently reachable, without raising any error (asynchronous version).

refframe→isReadOnly()

Test if the function is readOnly.

refframe→load(msValidity)

Preloads the reference frame cache with a specified validity duration.

refframe→loadAttribute(attrName)

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

refframe→load_async(msValidity, callback, context)

Preloads the reference frame cache with a specified validity duration (asynchronous version).

refframe→more3DCalibration()

Continues the sensors tridimensional calibration process previously initiated using method start3DCalibration.

refframe→muteValueCallbacks()

Disables the propagation of every new advertised value to the parent hub.

refframe→nextRefFrame()

Continues the enumeration of reference frames started using yFirstRefFrame().

refframe→registerValueCallback(callback)

Registers the callback function that is invoked on every change of advertised value.

refframe→save3DCalibration()

Applies the sensors tridimensional calibration parameters that have just been computed.

refframe→set_bearing(newval)

Changes the reference bearing used by the compass.

refframe→set_fusionMode(newval)

Change the sensor fusion mode.

refframe→set_logicalName(newval)

Changes the logical name of the reference frame.

refframe→set_mountPosition(position, orientation)

Changes the compass and tilt sensor frame of reference.

refframe→set_userData(data)

Stores a user context provided as argument in the userData attribute of the function.

refframe→start3DCalibration()

Initiates the sensors tridimensional calibration process.

refframe→unmuteValueCallbacks()

Re-enables the propagation of every new advertised value to the parent hub.

refframe→wait_async(callback, context)

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

YRefFrame.FindRefFrame()
YRefFrame.FindRefFrame()
yFindRefFrame()YRefFrame::FindRefFrame()[YRefFrame FindRefFrame: ]yFindRefFrame()YRefFrame.FindRefFrame()YRefFrame.FindRefFrame()YRefFrame.FindRefFrame()YRefFrame.FindRefFrame()YRefFrame.FindRefFrame()YRefFrame::FindRefFrame()YRefFrame.FindRefFrame()YRefFrame.FindRefFrame()YRefFrame.FindRefFrame()YRefFrame.FindRefFrame()

Retrieves a reference frame for a given identifier.

js
function yFindRefFrame(func)
cpp
YRefFrame* FindRefFrame(string func)
m
+(YRefFrame*) FindRefFrame: (NSString*) func
pas
TYRefFrame yFindRefFrame(func: string): TYRefFrame
vb
function FindRefFrame(ByVal func As String) As YRefFrame
cs
static YRefFrame FindRefFrame(string func)
java
static YRefFrame FindRefFrame(String func)
uwp
static YRefFrame FindRefFrame(string func)
py
FindRefFrame(func)
php
function FindRefFrame($func)
ts
static FindRefFrame(func: string): YRefFrame
es
static FindRefFrame(func)
dnp
static YRefFrameProxy FindRefFrame(string func)
cp
static YRefFrameProxy * FindRefFrame(string func)

The identifier can be specified using several formats:

This function does not require that the reference frame is online at the time it is invoked. The returned object is nevertheless valid. Use the method YRefFrame.isOnline() to test if the reference frame is indeed online at a given time. In case of ambiguity when looking for a reference frame by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

If a call to this object's is_online() method returns FALSE although you are certain that the matching device is plugged, make sure that you did call registerHub() at application initialization time.

Parameters :

funca string that uniquely characterizes the reference frame, for instance Y3DMK002.refFrame.

Returns :

a YRefFrame object allowing you to drive the reference frame.

YRefFrame.FindRefFrameInContext()
YRefFrame.FindRefFrameInContext()
YRefFrame.FindRefFrameInContext()YRefFrame.FindRefFrameInContext()YRefFrame.FindRefFrameInContext()YRefFrame.FindRefFrameInContext()

Retrieves a reference frame for a given identifier in a YAPI context.

java
static YRefFrame FindRefFrameInContext(YAPIContext yctx, String func)
uwp
static YRefFrame FindRefFrameInContext(YAPIContext yctx, string func)
ts
static FindRefFrameInContext(yctx: YAPIContext, func: string): YRefFrame
es
static FindRefFrameInContext(yctx, func)

The identifier can be specified using several formats:

This function does not require that the reference frame is online at the time it is invoked. The returned object is nevertheless valid. Use the method YRefFrame.isOnline() to test if the reference frame is indeed online at a given time. In case of ambiguity when looking for a reference frame by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

Parameters :

yctxa YAPI context
funca string that uniquely characterizes the reference frame, for instance Y3DMK002.refFrame.

Returns :

a YRefFrame object allowing you to drive the reference frame.

YRefFrame.FirstRefFrame()
YRefFrame.FirstRefFrame()
yFirstRefFrame()YRefFrame::FirstRefFrame()[YRefFrame FirstRefFrame]yFirstRefFrame()YRefFrame.FirstRefFrame()YRefFrame.FirstRefFrame()YRefFrame.FirstRefFrame()YRefFrame.FirstRefFrame()YRefFrame.FirstRefFrame()YRefFrame::FirstRefFrame()YRefFrame.FirstRefFrame()YRefFrame.FirstRefFrame()

Starts the enumeration of reference frames currently accessible.

js
function yFirstRefFrame()
cpp
YRefFrame * FirstRefFrame()
m
+(YRefFrame*) FirstRefFrame
pas
TYRefFrame yFirstRefFrame(): TYRefFrame
vb
function FirstRefFrame() As YRefFrame
cs
static YRefFrame FirstRefFrame()
java
static YRefFrame FirstRefFrame()
uwp
static YRefFrame FirstRefFrame()
py
FirstRefFrame()
php
function FirstRefFrame()
ts
static FirstRefFrame(): YRefFrame | null
es
static FirstRefFrame()

Use the method YRefFrame.nextRefFrame() to iterate on next reference frames.

Returns :

a pointer to a YRefFrame object, corresponding to the first reference frame currently online, or a null pointer if there are none.

YRefFrame.FirstRefFrameInContext()
YRefFrame.FirstRefFrameInContext()
YRefFrame.FirstRefFrameInContext()YRefFrame.FirstRefFrameInContext()YRefFrame.FirstRefFrameInContext()YRefFrame.FirstRefFrameInContext()

Starts the enumeration of reference frames currently accessible.

java
static YRefFrame FirstRefFrameInContext(YAPIContext yctx)
uwp
static YRefFrame FirstRefFrameInContext(YAPIContext yctx)
ts
static FirstRefFrameInContext(yctx: YAPIContext): YRefFrame | null
es
static FirstRefFrameInContext(yctx)

Use the method YRefFrame.nextRefFrame() to iterate on next reference frames.

Parameters :

yctxa YAPI context.

Returns :

a pointer to a YRefFrame object, corresponding to the first reference frame currently online, or a null pointer if there are none.

YRefFrame.GetSimilarFunctions()
YRefFrame.GetSimilarFunctions()
YRefFrame.GetSimilarFunctions()YRefFrame.GetSimilarFunctions()

Enumerates all functions of type RefFrame available on the devices currently reachable by the library, and returns their unique hardware ID.

dnp
static new string[] GetSimilarFunctions()
cp
static vector<string> GetSimilarFunctions()

Each of these IDs can be provided as argument to the method YRefFrame.FindRefFrame to obtain an object that can control the corresponding device.

Returns :

an array of strings, each string containing the unique hardwareId of a device function currently connected.

refframe→AdvertisedValuerefframe.AdvertisedValue

Short string representing the current state of the function.

dnp
string AdvertisedValue

refframe→Bearingrefframe.Bearing

Reference bearing used by the compass.

dnp
double Bearing

The relative bearing indicated by the compass is the difference between the measured magnetic heading and the reference bearing indicated here.

Writable. The relative bearing indicated by the compass is the difference between the measured magnetic heading and the reference bearing indicated here.

For instance, if you setup as reference bearing the value of the earth magnetic declination, the compass will provide the orientation relative to the geographic North.

Similarly, when the sensor is not mounted along the standard directions because it has an additional yaw angle, you can set this angle in the reference bearing so that the compass provides the expected natural direction.

Remember to call the saveToFlash() method of the module if the modification must be kept.

refframe→FriendlyNamerefframe.FriendlyName

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

dnp
string FriendlyName

The returned string uses the logical names of the module and of the function if they are defined, otherwise the serial number of the module and the hardware identifier of the function (for example: MyCustomName.relay1)

refframe→FunctionIdrefframe.FunctionId

Hardware identifier of the reference frame, without reference to the module.

dnp
string FunctionId

For example relay1

refframe→FusionModerefframe.FusionMode

Sensor fusion mode.

dnp
int FusionMode

Note that available sensor fusion modes depend on the sensor type.

Writable. Change the sensor fusion mode. Note that available sensor fusion modes depend on the sensor type. Remember to call the matching module saveToFlash() method to save the setting permanently.

refframe→HardwareIdrefframe.HardwareId

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

dnp
string HardwareId

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the function (for example RELAYLO1-123456.relay1).

refframe→IsOnlinerefframe.IsOnline

Checks if the function is currently reachable.

dnp
bool IsOnline

If there is a cached value for the function in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the function.

refframe→LogicalNamerefframe.LogicalName

Logical name of the function.

dnp
string LogicalName

Writable. You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

refframe→SerialNumberrefframe.SerialNumber

Serial number of the module, as set by the factory.

dnp
string SerialNumber

refframe→cancel3DCalibration()refframe.cancel3DCalibration()refframe→cancel3DCalibration()[refframe cancel3DCalibration]refframe.cancel3DCalibration()refframe.cancel3DCalibration()refframe.cancel3DCalibration()refframe.cancel3DCalibration()refframe.cancel3DCalibration()refframe.cancel3DCalibration()refframe→cancel3DCalibration()refframe.cancel3DCalibration()refframe.cancel3DCalibration()refframe.cancel3DCalibration()refframe.cancel3DCalibration()YRefFrame cancel3DCalibration

Aborts the sensors tridimensional calibration process et restores normal settings.

js
function cancel3DCalibration()
cpp
int cancel3DCalibration()
m
-(int) cancel3DCalibration
pas
LongInt cancel3DCalibration(): LongInt
vb
function cancel3DCalibration() As Integer
cs
int cancel3DCalibration()
java
int cancel3DCalibration()
uwp
async Task<int> cancel3DCalibration()
py
cancel3DCalibration()
php
function cancel3DCalibration()
ts
async cancel3DCalibration(): Promise<number>
es
async cancel3DCalibration()
dnp
int cancel3DCalibration()
cp
int cancel3DCalibration()
cmd
YRefFrame target cancel3DCalibration

On failure, throws an exception or returns a negative error code.

refframe→clearCache()refframe.clearCache()refframe→clearCache()[refframe clearCache]refframe.clearCache()refframe.clearCache()refframe.clearCache()refframe.clearCache()refframe.clearCache()refframe→clearCache()refframe.clearCache()refframe.clearCache()

Invalidates the cache.

js
function clearCache()
cpp
void clearCache()
m
-(void) clearCache
pas
clearCache()
vb
procedure clearCache()
cs
void clearCache()
java
void clearCache()
py
clearCache()
php
function clearCache()
ts
async clearCache(): Promise<void>
es
async clearCache()

Invalidates the cache of the reference frame attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.

refframe→describe()refframe.describe()refframe→describe()[refframe describe]refframe.describe()refframe.describe()refframe.describe()refframe.describe()refframe.describe()refframe→describe()refframe.describe()refframe.describe()

Returns a short text that describes unambiguously the instance of the reference frame in the form TYPE(NAME)=SERIAL.FUNCTIONID.

js
function describe()
cpp
string describe()
m
-(NSString*) describe
pas
string describe(): string
vb
function describe() As String
cs
string describe()
java
String describe()
py
describe()
php
function describe()
ts
async describe(): Promise<string>
es
async describe()

More precisely, TYPE is the type of the function, NAME it the name used for the first access to the function, SERIAL is the serial number of the module if the module is connected or "unresolved", and FUNCTIONID is the hardware identifier of the function if the module is connected. For example, this method returns Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1 if the module is already connected or Relay(BadCustomeName.relay1)=unresolved if the module has not yet been connected. This method does not trigger any USB or TCP transaction and can therefore be used in a debugger.

Returns :

a string that describes the reference frame (ex: Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1)

refframe→get_3DCalibrationHint()
refframe→3DCalibrationHint()
refframe.get_3DCalibrationHint()refframe→get_3DCalibrationHint()[refframe 3DCalibrationHint]refframe.get_3DCalibrationHint()refframe.get_3DCalibrationHint()refframe.get_3DCalibrationHint()refframe.get_3DCalibrationHint()refframe.get_3DCalibrationHint()refframe.get_3DCalibrationHint()refframe→get_3DCalibrationHint()refframe.get_3DCalibrationHint()refframe.get_3DCalibrationHint()refframe.get_3DCalibrationHint()refframe.get_3DCalibrationHint()YRefFrame get_3DCalibrationHint

Returns instructions to proceed to the tridimensional calibration initiated with method start3DCalibration.

js
function get_3DCalibrationHint()
cpp
string get_3DCalibrationHint()
m
-(NSString*) 3DCalibrationHint
pas
string get_3DCalibrationHint(): string
vb
function get_3DCalibrationHint() As String
cs
string get_3DCalibrationHint()
java
String get_3DCalibrationHint()
uwp
async Task<string> get_3DCalibrationHint()
py
get_3DCalibrationHint()
php
function get_3DCalibrationHint()
ts
async get_3DCalibrationHint(): Promise<string>
es
async get_3DCalibrationHint()
dnp
string get_3DCalibrationHint()
cp
string get_3DCalibrationHint()
cmd
YRefFrame target get_3DCalibrationHint

Returns :

a character string.

refframe→get_3DCalibrationLogMsg()
refframe→3DCalibrationLogMsg()
refframe.get_3DCalibrationLogMsg()refframe→get_3DCalibrationLogMsg()[refframe 3DCalibrationLogMsg]refframe.get_3DCalibrationLogMsg()refframe.get_3DCalibrationLogMsg()refframe.get_3DCalibrationLogMsg()refframe.get_3DCalibrationLogMsg()refframe.get_3DCalibrationLogMsg()refframe.get_3DCalibrationLogMsg()refframe→get_3DCalibrationLogMsg()refframe.get_3DCalibrationLogMsg()refframe.get_3DCalibrationLogMsg()refframe.get_3DCalibrationLogMsg()refframe.get_3DCalibrationLogMsg()YRefFrame get_3DCalibrationLogMsg

Returns the latest log message from the calibration process.

js
function get_3DCalibrationLogMsg()
cpp
string get_3DCalibrationLogMsg()
m
-(NSString*) 3DCalibrationLogMsg
pas
string get_3DCalibrationLogMsg(): string
vb
function get_3DCalibrationLogMsg() As String
cs
string get_3DCalibrationLogMsg()
java
String get_3DCalibrationLogMsg()
uwp
async Task<string> get_3DCalibrationLogMsg()
py
get_3DCalibrationLogMsg()
php
function get_3DCalibrationLogMsg()
ts
async get_3DCalibrationLogMsg(): Promise<string>
es
async get_3DCalibrationLogMsg()
dnp
string get_3DCalibrationLogMsg()
cp
string get_3DCalibrationLogMsg()
cmd
YRefFrame target get_3DCalibrationLogMsg

When no new message is available, returns an empty string.

Returns :

a character string.

refframe→get_3DCalibrationProgress()
refframe→3DCalibrationProgress()
refframe.get_3DCalibrationProgress()refframe→get_3DCalibrationProgress()[refframe 3DCalibrationProgress]refframe.get_3DCalibrationProgress()refframe.get_3DCalibrationProgress()refframe.get_3DCalibrationProgress()refframe.get_3DCalibrationProgress()refframe.get_3DCalibrationProgress()refframe.get_3DCalibrationProgress()refframe→get_3DCalibrationProgress()refframe.get_3DCalibrationProgress()refframe.get_3DCalibrationProgress()refframe.get_3DCalibrationProgress()refframe.get_3DCalibrationProgress()YRefFrame get_3DCalibrationProgress

Returns the global process indicator for the tridimensional calibration initiated with method start3DCalibration.

js
function get_3DCalibrationProgress()
cpp
int get_3DCalibrationProgress()
m
-(int) 3DCalibrationProgress
pas
LongInt get_3DCalibrationProgress(): LongInt
vb
function get_3DCalibrationProgress() As Integer
cs
int get_3DCalibrationProgress()
java
int get_3DCalibrationProgress()
uwp
async Task<int> get_3DCalibrationProgress()
py
get_3DCalibrationProgress()
php
function get_3DCalibrationProgress()
ts
async get_3DCalibrationProgress(): Promise<number>
es
async get_3DCalibrationProgress()
dnp
int get_3DCalibrationProgress()
cp
int get_3DCalibrationProgress()
cmd
YRefFrame target get_3DCalibrationProgress

Returns :

an integer between 0 (not started) and 100 (stage completed).

refframe→get_3DCalibrationStage()
refframe→3DCalibrationStage()
refframe.get_3DCalibrationStage()refframe→get_3DCalibrationStage()[refframe 3DCalibrationStage]refframe.get_3DCalibrationStage()refframe.get_3DCalibrationStage()refframe.get_3DCalibrationStage()refframe.get_3DCalibrationStage()refframe.get_3DCalibrationStage()refframe.get_3DCalibrationStage()refframe→get_3DCalibrationStage()refframe.get_3DCalibrationStage()refframe.get_3DCalibrationStage()refframe.get_3DCalibrationStage()refframe.get_3DCalibrationStage()YRefFrame get_3DCalibrationStage

Returns index of the current stage of the calibration initiated with method start3DCalibration.

js
function get_3DCalibrationStage()
cpp
int get_3DCalibrationStage()
m
-(int) 3DCalibrationStage
pas
LongInt get_3DCalibrationStage(): LongInt
vb
function get_3DCalibrationStage() As Integer
cs
int get_3DCalibrationStage()
java
int get_3DCalibrationStage()
uwp
async Task<int> get_3DCalibrationStage()
py
get_3DCalibrationStage()
php
function get_3DCalibrationStage()
ts
async get_3DCalibrationStage(): Promise<number>
es
async get_3DCalibrationStage()
dnp
int get_3DCalibrationStage()
cp
int get_3DCalibrationStage()
cmd
YRefFrame target get_3DCalibrationStage

Returns :

an integer, growing each time a calibration stage is completed.

refframe→get_3DCalibrationStageProgress()
refframe→3DCalibrationStageProgress()
refframe.get_3DCalibrationStageProgress()refframe→get_3DCalibrationStageProgress()[refframe 3DCalibrationStageProgress]refframe.get_3DCalibrationStageProgress()refframe.get_3DCalibrationStageProgress()refframe.get_3DCalibrationStageProgress()refframe.get_3DCalibrationStageProgress()refframe.get_3DCalibrationStageProgress()refframe.get_3DCalibrationStageProgress()refframe→get_3DCalibrationStageProgress()refframe.get_3DCalibrationStageProgress()refframe.get_3DCalibrationStageProgress()refframe.get_3DCalibrationStageProgress()refframe.get_3DCalibrationStageProgress()YRefFrame get_3DCalibrationStageProgress

Returns the process indicator for the current stage of the calibration initiated with method start3DCalibration.

js
function get_3DCalibrationStageProgress()
cpp
int get_3DCalibrationStageProgress()
m
-(int) 3DCalibrationStageProgress
pas
LongInt get_3DCalibrationStageProgress(): LongInt
vb
function get_3DCalibrationStageProgress() As Integer
cs
int get_3DCalibrationStageProgress()
java
int get_3DCalibrationStageProgress()
uwp
async Task<int> get_3DCalibrationStageProgress()
py
get_3DCalibrationStageProgress()
php
function get_3DCalibrationStageProgress()
ts
async get_3DCalibrationStageProgress(): Promise<number>
es
async get_3DCalibrationStageProgress()
dnp
int get_3DCalibrationStageProgress()
cp
int get_3DCalibrationStageProgress()
cmd
YRefFrame target get_3DCalibrationStageProgress

Returns :

an integer between 0 (not started) and 100 (stage completed).

refframe→get_advertisedValue()
refframe→advertisedValue()
refframe.get_advertisedValue()refframe→get_advertisedValue()[refframe advertisedValue]refframe.get_advertisedValue()refframe.get_advertisedValue()refframe.get_advertisedValue()refframe.get_advertisedValue()refframe.get_advertisedValue()refframe.get_advertisedValue()refframe→get_advertisedValue()refframe.get_advertisedValue()refframe.get_advertisedValue()refframe.get_advertisedValue()refframe.get_advertisedValue()YRefFrame get_advertisedValue

Returns the current value of the reference frame (no more than 6 characters).

js
function get_advertisedValue()
cpp
string get_advertisedValue()
m
-(NSString*) advertisedValue
pas
string get_advertisedValue(): string
vb
function get_advertisedValue() As String
cs
string get_advertisedValue()
java
String get_advertisedValue()
uwp
async Task<string> get_advertisedValue()
py
get_advertisedValue()
php
function get_advertisedValue()
ts
async get_advertisedValue(): Promise<string>
es
async get_advertisedValue()
dnp
string get_advertisedValue()
cp
string get_advertisedValue()
cmd
YRefFrame target get_advertisedValue

Returns :

a string corresponding to the current value of the reference frame (no more than 6 characters).

On failure, throws an exception or returns YRefFrame.ADVERTISEDVALUE_INVALID.

refframe→get_bearing()
refframe→bearing()
refframe.get_bearing()refframe→get_bearing()[refframe bearing]refframe.get_bearing()refframe.get_bearing()refframe.get_bearing()refframe.get_bearing()refframe.get_bearing()refframe.get_bearing()refframe→get_bearing()refframe.get_bearing()refframe.get_bearing()refframe.get_bearing()refframe.get_bearing()YRefFrame get_bearing

Returns the reference bearing used by the compass.

js
function get_bearing()
cpp
double get_bearing()
m
-(double) bearing
pas
double get_bearing(): double
vb
function get_bearing() As Double
cs
double get_bearing()
java
double get_bearing()
uwp
async Task<double> get_bearing()
py
get_bearing()
php
function get_bearing()
ts
async get_bearing(): Promise<number>
es
async get_bearing()
dnp
double get_bearing()
cp
double get_bearing()
cmd
YRefFrame target get_bearing

The relative bearing indicated by the compass is the difference between the measured magnetic heading and the reference bearing indicated here.

Returns :

a floating point number corresponding to the reference bearing used by the compass

On failure, throws an exception or returns YRefFrame.BEARING_INVALID.

refframe→get_calibrationState()
refframe→calibrationState()
refframe.get_calibrationState()refframe→get_calibrationState()[refframe calibrationState]refframe.get_calibrationState()refframe.get_calibrationState()refframe.get_calibrationState()refframe.get_calibrationState()refframe.get_calibrationState()refframe.get_calibrationState()refframe→get_calibrationState()refframe.get_calibrationState()refframe.get_calibrationState()refframe.get_calibrationState()refframe.get_calibrationState()YRefFrame get_calibrationState

Returns the 3D sensor calibration state (Yocto-3D-V2 only).

js
function get_calibrationState()
cpp
int get_calibrationState()
m
-(int) calibrationState
pas
LongInt get_calibrationState(): LongInt
vb
function get_calibrationState() As Integer
cs
int get_calibrationState()
java
int get_calibrationState()
uwp
async Task<int> get_calibrationState()
py
get_calibrationState()
php
function get_calibrationState()
ts
async get_calibrationState(): Promise<number>
es
async get_calibrationState()
dnp
int get_calibrationState()
cp
int get_calibrationState()
cmd
YRefFrame target get_calibrationState

This function returns an integer representing the calibration state of the 3 inertial sensors of the BNO055 chip, found in the Yocto-3D-V2. Hundredths show the calibration state of the accelerometer, tenths show the calibration state of the magnetometer while units show the calibration state of the gyroscope. For each sensor, the value 0 means no calibration and the value 3 means full calibration.

Returns :

an integer representing the calibration state of Yocto-3D-V2: 333 when fully calibrated, 0 when not calibrated at all.

On failure, throws an exception or returns a negative error code. For the Yocto-3D (V1), this function always return -3 (unsupported function).

refframe→get_errorMessage()
refframe→errorMessage()
refframe.get_errorMessage()refframe→get_errorMessage()[refframe errorMessage]refframe.get_errorMessage()refframe.get_errorMessage()refframe.get_errorMessage()refframe.get_errorMessage()refframe.get_errorMessage()refframe→get_errorMessage()refframe.get_errorMessage()refframe.get_errorMessage()

Returns the error message of the latest error with the reference frame.

js
function get_errorMessage()
cpp
string get_errorMessage()
m
-(NSString*) errorMessage
pas
string get_errorMessage(): string
vb
function get_errorMessage() As String
cs
string get_errorMessage()
java
String get_errorMessage()
py
get_errorMessage()
php
function get_errorMessage()
ts
get_errorMessage(): string
es
get_errorMessage()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a string corresponding to the latest error message that occured while using the reference frame object

refframe→get_errorType()
refframe→errorType()
refframe.get_errorType()refframe→get_errorType()[refframe errorType]refframe.get_errorType()refframe.get_errorType()refframe.get_errorType()refframe.get_errorType()refframe.get_errorType()refframe→get_errorType()refframe.get_errorType()refframe.get_errorType()

Returns the numerical error code of the latest error with the reference frame.

js
function get_errorType()
cpp
YRETCODE get_errorType()
m
-(YRETCODE) errorType
pas
YRETCODE get_errorType(): YRETCODE
vb
function get_errorType() As YRETCODE
cs
YRETCODE get_errorType()
java
int get_errorType()
py
get_errorType()
php
function get_errorType()
ts
get_errorType(): number
es
get_errorType()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a number corresponding to the code of the latest error that occurred while using the reference frame object

refframe→get_friendlyName()
refframe→friendlyName()
refframe.get_friendlyName()refframe→get_friendlyName()[refframe friendlyName]refframe.get_friendlyName()refframe.get_friendlyName()refframe.get_friendlyName()refframe→get_friendlyName()refframe.get_friendlyName()refframe.get_friendlyName()refframe.get_friendlyName()refframe.get_friendlyName()

Returns a global identifier of the reference frame in the format MODULE_NAME.FUNCTION_NAME.

js
function get_friendlyName()
cpp
string get_friendlyName()
m
-(NSString*) friendlyName
cs
string get_friendlyName()
java
String get_friendlyName()
py
get_friendlyName()
php
function get_friendlyName()
ts
async get_friendlyName(): Promise<string>
es
async get_friendlyName()
dnp
string get_friendlyName()
cp
string get_friendlyName()

The returned string uses the logical names of the module and of the reference frame if they are defined, otherwise the serial number of the module and the hardware identifier of the reference frame (for example: MyCustomName.relay1)

Returns :

a string that uniquely identifies the reference frame using logical names (ex: MyCustomName.relay1)

On failure, throws an exception or returns YRefFrame.FRIENDLYNAME_INVALID.

refframe→get_functionDescriptor()
refframe→functionDescriptor()
refframe.get_functionDescriptor()refframe→get_functionDescriptor()[refframe functionDescriptor]refframe.get_functionDescriptor()refframe.get_functionDescriptor()refframe.get_functionDescriptor()refframe.get_functionDescriptor()refframe.get_functionDescriptor()refframe→get_functionDescriptor()refframe.get_functionDescriptor()refframe.get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

js
function get_functionDescriptor()
cpp
YFUN_DESCR get_functionDescriptor()
m
-(YFUN_DESCR) functionDescriptor
pas
YFUN_DESCR get_functionDescriptor(): YFUN_DESCR
vb
function get_functionDescriptor() As YFUN_DESCR
cs
YFUN_DESCR get_functionDescriptor()
java
String get_functionDescriptor()
py
get_functionDescriptor()
php
function get_functionDescriptor()
ts
async get_functionDescriptor(): Promise<string>
es
async get_functionDescriptor()

This identifier can be used to test if two instances of YFunction reference the same physical function on the same physical device.

Returns :

an identifier of type YFUN_DESCR.

If the function has never been contacted, the returned value is Y$CLASSNAME$.FUNCTIONDESCRIPTOR_INVALID.

refframe→get_functionId()
refframe→functionId()
refframe.get_functionId()refframe→get_functionId()[refframe functionId]refframe.get_functionId()refframe.get_functionId()refframe.get_functionId()refframe.get_functionId()refframe→get_functionId()refframe.get_functionId()refframe.get_functionId()refframe.get_functionId()refframe.get_functionId()

Returns the hardware identifier of the reference frame, without reference to the module.

js
function get_functionId()
cpp
string get_functionId()
m
-(NSString*) functionId
vb
function get_functionId() As String
cs
string get_functionId()
java
String get_functionId()
py
get_functionId()
php
function get_functionId()
ts
async get_functionId(): Promise<string>
es
async get_functionId()
dnp
string get_functionId()
cp
string get_functionId()

For example relay1

Returns :

a string that identifies the reference frame (ex: relay1)

On failure, throws an exception or returns YRefFrame.FUNCTIONID_INVALID.

refframe→get_fusionMode()
refframe→fusionMode()
refframe.get_fusionMode()refframe→get_fusionMode()[refframe fusionMode]refframe.get_fusionMode()refframe.get_fusionMode()refframe.get_fusionMode()refframe.get_fusionMode()refframe.get_fusionMode()refframe.get_fusionMode()refframe→get_fusionMode()refframe.get_fusionMode()refframe.get_fusionMode()refframe.get_fusionMode()refframe.get_fusionMode()YRefFrame get_fusionMode

Returns the sensor fusion mode.

js
function get_fusionMode()
cpp
Y_FUSIONMODE_enum get_fusionMode()
m
-(Y_FUSIONMODE_enum) fusionMode
pas
Integer get_fusionMode(): Integer
vb
function get_fusionMode() As Integer
cs
int get_fusionMode()
java
int get_fusionMode()
uwp
async Task<int> get_fusionMode()
py
get_fusionMode()
php
function get_fusionMode()
ts
async get_fusionMode(): Promise<YRefFrame_FusionMode>
es
async get_fusionMode()
dnp
int get_fusionMode()
cp
int get_fusionMode()
cmd
YRefFrame target get_fusionMode

Note that available sensor fusion modes depend on the sensor type.

Returns :

a value among YRefFrame.FUSIONMODE_NDOF, YRefFrame.FUSIONMODE_NDOF_FMC_OFF, YRefFrame.FUSIONMODE_M4G, YRefFrame.FUSIONMODE_COMPASS, YRefFrame.FUSIONMODE_IMU, YRefFrame.FUSIONMODE_INCLIN_90DEG_1G8, YRefFrame.FUSIONMODE_INCLIN_90DEG_3G6 and YRefFrame.FUSIONMODE_INCLIN_10DEG corresponding to the sensor fusion mode

On failure, throws an exception or returns YRefFrame.FUSIONMODE_INVALID.

refframe→get_hardwareId()
refframe→hardwareId()
refframe.get_hardwareId()refframe→get_hardwareId()[refframe hardwareId]refframe.get_hardwareId()refframe.get_hardwareId()refframe.get_hardwareId()refframe.get_hardwareId()refframe→get_hardwareId()refframe.get_hardwareId()refframe.get_hardwareId()refframe.get_hardwareId()refframe.get_hardwareId()

Returns the unique hardware identifier of the reference frame in the form SERIAL.FUNCTIONID.

js
function get_hardwareId()
cpp
string get_hardwareId()
m
-(NSString*) hardwareId
vb
function get_hardwareId() As String
cs
string get_hardwareId()
java
String get_hardwareId()
py
get_hardwareId()
php
function get_hardwareId()
ts
async get_hardwareId(): Promise<string>
es
async get_hardwareId()
dnp
string get_hardwareId()
cp
string get_hardwareId()

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the reference frame (for example RELAYLO1-123456.relay1).

Returns :

a string that uniquely identifies the reference frame (ex: RELAYLO1-123456.relay1)

On failure, throws an exception or returns YRefFrame.HARDWAREID_INVALID.

refframe→get_logicalName()
refframe→logicalName()
refframe.get_logicalName()refframe→get_logicalName()[refframe logicalName]refframe.get_logicalName()refframe.get_logicalName()refframe.get_logicalName()refframe.get_logicalName()refframe.get_logicalName()refframe.get_logicalName()refframe→get_logicalName()refframe.get_logicalName()refframe.get_logicalName()refframe.get_logicalName()refframe.get_logicalName()YRefFrame get_logicalName

Returns the logical name of the reference frame.

js
function get_logicalName()
cpp
string get_logicalName()
m
-(NSString*) logicalName
pas
string get_logicalName(): string
vb
function get_logicalName() As String
cs
string get_logicalName()
java
String get_logicalName()
uwp
async Task<string> get_logicalName()
py
get_logicalName()
php
function get_logicalName()
ts
async get_logicalName(): Promise<string>
es
async get_logicalName()
dnp
string get_logicalName()
cp
string get_logicalName()
cmd
YRefFrame target get_logicalName

Returns :

a string corresponding to the logical name of the reference frame.

On failure, throws an exception or returns YRefFrame.LOGICALNAME_INVALID.

refframe→get_measureQuality()
refframe→measureQuality()
refframe.get_measureQuality()refframe→get_measureQuality()[refframe measureQuality]refframe.get_measureQuality()refframe.get_measureQuality()refframe.get_measureQuality()refframe.get_measureQuality()refframe.get_measureQuality()refframe.get_measureQuality()refframe→get_measureQuality()refframe.get_measureQuality()refframe.get_measureQuality()refframe.get_measureQuality()refframe.get_measureQuality()YRefFrame get_measureQuality

Returns estimated quality of the orientation (Yocto-3D-V2 only).

js
function get_measureQuality()
cpp
int get_measureQuality()
m
-(int) measureQuality
pas
LongInt get_measureQuality(): LongInt
vb
function get_measureQuality() As Integer
cs
int get_measureQuality()
java
int get_measureQuality()
uwp
async Task<int> get_measureQuality()
py
get_measureQuality()
php
function get_measureQuality()
ts
async get_measureQuality(): Promise<number>
es
async get_measureQuality()
dnp
int get_measureQuality()
cp
int get_measureQuality()
cmd
YRefFrame target get_measureQuality

This function returns an integer between 0 and 3 representing the degree of confidence of the position estimate. When the value is 3, the estimation is reliable. Below 3, one should expect sudden corrections, in particular for heading (compass function). The most frequent causes for values below 3 are magnetic interferences, and accelerations or rotations beyond the sensor range.

Returns :

an integer between 0 and 3 (3 when the measure is reliable)

On failure, throws an exception or returns a negative error code. For the Yocto-3D (V1), this function always return -3 (unsupported function).

refframe→get_module()
refframe→module()
refframe.get_module()refframe→get_module()[refframe module]refframe.get_module()refframe.get_module()refframe.get_module()refframe.get_module()refframe.get_module()refframe→get_module()refframe.get_module()refframe.get_module()refframe.get_module()refframe.get_module()

Gets the YModule object for the device on which the function is located.

js
function get_module()
cpp
YModule * get_module()
m
-(YModule*) module
pas
TYModule get_module(): TYModule
vb
function get_module() As YModule
cs
YModule get_module()
java
YModule get_module()
py
get_module()
php
function get_module()
ts
async get_module(): Promise<YModule>
es
async get_module()
dnp
YModuleProxy get_module()
cp
YModuleProxy * get_module()

If the function cannot be located on any module, the returned instance of YModule is not shown as on-line.

Returns :

an instance of YModule

refframe→get_module_async()
refframe→module_async()
refframe.get_module_async()

Gets the YModule object for the device on which the function is located (asynchronous version).

js
function get_module_async(callback, context)

If the function cannot be located on any module, the returned YModule object does not show as on-line.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking Firefox JavaScript VM that does not implement context switching during blocking I/O calls. See the documentation section on asynchronous JavasSript calls for more details.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the requested YModule object
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

refframe→get_mountOrientation()
refframe→mountOrientation()
refframe.get_mountOrientation()refframe→get_mountOrientation()[refframe mountOrientation]refframe.get_mountOrientation()refframe.get_mountOrientation()refframe.get_mountOrientation()refframe.get_mountOrientation()refframe.get_mountOrientation()refframe.get_mountOrientation()refframe→get_mountOrientation()refframe.get_mountOrientation()refframe.get_mountOrientation()refframe.get_mountOrientation()refframe.get_mountOrientation()YRefFrame get_mountOrientation

Returns the installation orientation of the device, as configured in order to define the reference frame for the compass and the pitch/roll tilt sensors.

js
function get_mountOrientation()
cpp
Y_MOUNTORIENTATION get_mountOrientation()
m
-(Y_MOUNTORIENTATION) mountOrientation
pas
TYMOUNTORIENTATION get_mountOrientation(): TYMOUNTORIENTATION
vb
function get_mountOrientation() As Y_MOUNTORIENTATION
cs
MOUNTORIENTATION get_mountOrientation()
java
MOUNTORIENTATION get_mountOrientation()
uwp
async Task<MOUNTORIENTATION> get_mountOrientation()
py
get_mountOrientation()
php
function get_mountOrientation()
ts
async get_mountOrientation(): Promise<YRefFrame_MountOrientation>
es
async get_mountOrientation()
dnp
int get_mountOrientation()
cp
int get_mountOrientation()
cmd
YRefFrame target get_mountOrientation

Returns :

a value among the enumeration YRefFrame.MOUNTORIENTATION (YRefFrame.MOUNTORIENTATION_TWELVE, YRefFrame.MOUNTORIENTATION_THREE, YRefFrame.MOUNTORIENTATION_SIX, YRefFrame.MOUNTORIENTATION_NINE) corresponding to the orientation of the "X" arrow on the device, as on a clock dial seen from an observer in the center of the box. On the bottom face, the 12H orientation points to the front, while on the top face, the 12H orientation points to the rear.

On failure, throws an exception or returns Y_MOUNTORIENTATION_INVALID.

refframe→get_mountPosition()
refframe→mountPosition()
refframe.get_mountPosition()refframe→get_mountPosition()[refframe mountPosition]refframe.get_mountPosition()refframe.get_mountPosition()refframe.get_mountPosition()refframe.get_mountPosition()refframe.get_mountPosition()refframe.get_mountPosition()refframe→get_mountPosition()refframe.get_mountPosition()refframe.get_mountPosition()refframe.get_mountPosition()refframe.get_mountPosition()YRefFrame get_mountPosition

Returns the installation position of the device, as configured in order to define the reference frame for the compass and the pitch/roll tilt sensors.

js
function get_mountPosition()
cpp
Y_MOUNTPOSITION get_mountPosition()
m
-(Y_MOUNTPOSITION) mountPosition
pas
TYMOUNTPOSITION get_mountPosition(): TYMOUNTPOSITION
vb
function get_mountPosition() As Y_MOUNTPOSITION
cs
MOUNTPOSITION get_mountPosition()
java
MOUNTPOSITION get_mountPosition()
uwp
async Task<MOUNTPOSITION> get_mountPosition()
py
get_mountPosition()
php
function get_mountPosition()
ts
async get_mountPosition(): Promise<YRefFrame_MountPosition>
es
async get_mountPosition()
dnp
int get_mountPosition()
cp
int get_mountPosition()
cmd
YRefFrame target get_mountPosition

Returns :

a value among the YRefFrame.MOUNTPOSITION enumeration (YRefFrame.MOUNTPOSITION_BOTTOM, YRefFrame.MOUNTPOSITION_TOP, YRefFrame.MOUNTPOSITION_FRONT, YRefFrame.MOUNTPOSITION_RIGHT, YRefFrame.MOUNTPOSITION_REAR, YRefFrame.MOUNTPOSITION_LEFT), corresponding to the installation in a box, on one of the six faces.

On failure, throws an exception or returns Y_MOUNTPOSITION_INVALID.

refframe→get_serialNumber()
refframe→serialNumber()
refframe.get_serialNumber()refframe→get_serialNumber()[refframe serialNumber]refframe.get_serialNumber()refframe.get_serialNumber()refframe.get_serialNumber()refframe.get_serialNumber()refframe.get_serialNumber()refframe.get_serialNumber()refframe→get_serialNumber()refframe.get_serialNumber()refframe.get_serialNumber()refframe.get_serialNumber()refframe.get_serialNumber()YRefFrame get_serialNumber

Returns the serial number of the module, as set by the factory.

js
function get_serialNumber()
cpp
string get_serialNumber()
m
-(NSString*) serialNumber
pas
string get_serialNumber(): string
vb
function get_serialNumber() As String
cs
string get_serialNumber()
java
String get_serialNumber()
uwp
async Task<string> get_serialNumber()
py
get_serialNumber()
php
function get_serialNumber()
ts
async get_serialNumber(): Promise<string>
es
async get_serialNumber()
dnp
string get_serialNumber()
cp
string get_serialNumber()
cmd
YRefFrame target get_serialNumber

Returns :

a string corresponding to the serial number of the module, as set by the factory.

On failure, throws an exception or returns YFunction.SERIALNUMBER_INVALID.

refframe→get_userData()
refframe→userData()
refframe.get_userData()refframe→get_userData()[refframe userData]refframe.get_userData()refframe.get_userData()refframe.get_userData()refframe.get_userData()refframe.get_userData()refframe→get_userData()refframe.get_userData()refframe.get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

js
function get_userData()
cpp
void * get_userData()
m
-(id) userData
pas
Tobject get_userData(): Tobject
vb
function get_userData() As Object
cs
object get_userData()
java
Object get_userData()
py
get_userData()
php
function get_userData()
ts
async get_userData(): Promise<object|null>
es
async get_userData()

This attribute is never touched directly by the API, and is at disposal of the caller to store a context.

Returns :

the object stored previously by the caller.

refframe→isOnline()refframe.isOnline()refframe→isOnline()[refframe isOnline]refframe.isOnline()refframe.isOnline()refframe.isOnline()refframe.isOnline()refframe.isOnline()refframe→isOnline()refframe.isOnline()refframe.isOnline()refframe.isOnline()refframe.isOnline()

Checks if the reference frame is currently reachable, without raising any error.

js
function isOnline()
cpp
bool isOnline()
m
-(BOOL) isOnline
pas
boolean isOnline(): boolean
vb
function isOnline() As Boolean
cs
bool isOnline()
java
boolean isOnline()
py
isOnline()
php
function isOnline()
ts
async isOnline(): Promise<boolean>
es
async isOnline()
dnp
bool isOnline()
cp
bool isOnline()

If there is a cached value for the reference frame in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the reference frame.

Returns :

true if the reference frame can be reached, and false otherwise

refframe→isOnline_async()refframe.isOnline_async()

Checks if the reference frame is currently reachable, without raising any error (asynchronous version).

js
function isOnline_async(callback, context)

If there is a cached value for the reference frame in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the requested function.

This asynchronous version exists only in Javascript. It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the boolean result
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

refframe→isReadOnly()refframe→isReadOnly()[refframe isReadOnly]refframe.isReadOnly()refframe.isReadOnly()refframe.isReadOnly()refframe.isReadOnly()refframe.isReadOnly()refframe.isReadOnly()refframe→isReadOnly()refframe.isReadOnly()refframe.isReadOnly()refframe.isReadOnly()refframe.isReadOnly()YRefFrame isReadOnly

Test if the function is readOnly.

cpp
bool isReadOnly()
m
-(bool) isReadOnly
pas
boolean isReadOnly(): boolean
vb
function isReadOnly() As Boolean
cs
bool isReadOnly()
java
boolean isReadOnly()
uwp
async Task<bool> isReadOnly()
py
isReadOnly()
php
function isReadOnly()
ts
async isReadOnly(): Promise<boolean>
es
async isReadOnly()
dnp
bool isReadOnly()
cp
bool isReadOnly()
cmd
YRefFrame target isReadOnly

Return true if the function is write protected or that the function is not available.

Returns :

true if the function is readOnly or not online.

refframe→load()refframe.load()refframe→load()[refframe load: ]refframe.load()refframe.load()refframe.load()refframe.load()refframe.load()refframe→load()refframe.load()refframe.load()

Preloads the reference frame cache with a specified validity duration.

js
function load(msValidity)
cpp
YRETCODE load(int msValidity)
m
-(YRETCODE) load: (u64) msValidity
pas
YRETCODE load(msValidity: u64): YRETCODE
vb
function load(ByVal msValidity As Long) As YRETCODE
cs
YRETCODE load(ulong msValidity)
java
int load(long msValidity)
py
load(msValidity)
php
function load($msValidity)
ts
async load(msValidity: number): Promise<number>
es
async load(msValidity)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

Parameters :

msValidityan integer corresponding to the validity attributed to the loaded function parameters, in milliseconds

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

refframe→loadAttribute()refframe.loadAttribute()refframe→loadAttribute()[refframe loadAttribute: ]refframe.loadAttribute()refframe.loadAttribute()refframe.loadAttribute()refframe.loadAttribute()refframe.loadAttribute()refframe.loadAttribute()refframe→loadAttribute()refframe.loadAttribute()refframe.loadAttribute()refframe.loadAttribute()refframe.loadAttribute()

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

js
function loadAttribute(attrName)
cpp
string loadAttribute(string attrName)
m
-(NSString*) loadAttribute: (NSString*) attrName
pas
string loadAttribute(attrName: string): string
vb
function loadAttribute(ByVal attrName As String) As String
cs
string loadAttribute(string attrName)
java
String loadAttribute(String attrName)
uwp
async Task<string> loadAttribute(string attrName)
py
loadAttribute(attrName)
php
function loadAttribute($attrName)
ts
async loadAttribute(attrName: string): Promise<string>
es
async loadAttribute(attrName)
dnp
string loadAttribute(string attrName)
cp
string loadAttribute(string attrName)

Parameters :

attrNamethe name of the requested attribute

Returns :

a string with the value of the the attribute

On failure, throws an exception or returns an empty string.

refframe→load_async()refframe.load_async()

Preloads the reference frame cache with a specified validity duration (asynchronous version).

js
function load_async(msValidity, callback, context)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking the JavaScript virtual machine.

Parameters :

msValidityan integer corresponding to the validity of the loaded function parameters, in milliseconds
callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the error code (or YAPI.SUCCESS)
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

refframe→more3DCalibration()refframe.more3DCalibration()refframe→more3DCalibration()[refframe more3DCalibration]refframe.more3DCalibration()refframe.more3DCalibration()refframe.more3DCalibration()refframe.more3DCalibration()refframe.more3DCalibration()refframe.more3DCalibration()refframe→more3DCalibration()refframe.more3DCalibration()refframe.more3DCalibration()refframe.more3DCalibration()refframe.more3DCalibration()YRefFrame more3DCalibration

Continues the sensors tridimensional calibration process previously initiated using method start3DCalibration.

js
function more3DCalibration()
cpp
int more3DCalibration()
m
-(int) more3DCalibration
pas
LongInt more3DCalibration(): LongInt
vb
function more3DCalibration() As Integer
cs
int more3DCalibration()
java
int more3DCalibration()
uwp
async Task<int> more3DCalibration()
py
more3DCalibration()
php
function more3DCalibration()
ts
async more3DCalibration(): Promise<number>
es
async more3DCalibration()
dnp
int more3DCalibration()
cp
int more3DCalibration()
cmd
YRefFrame target more3DCalibration

This method should be called approximately 5 times per second, while positioning the device according to the instructions provided by method get_3DCalibrationHint. Note that the instructions change during the calibration process.

On failure, throws an exception or returns a negative error code.

refframe→muteValueCallbacks()refframe.muteValueCallbacks()refframe→muteValueCallbacks()[refframe muteValueCallbacks]refframe.muteValueCallbacks()refframe.muteValueCallbacks()refframe.muteValueCallbacks()refframe.muteValueCallbacks()refframe.muteValueCallbacks()refframe.muteValueCallbacks()refframe→muteValueCallbacks()refframe.muteValueCallbacks()refframe.muteValueCallbacks()refframe.muteValueCallbacks()refframe.muteValueCallbacks()YRefFrame muteValueCallbacks

Disables the propagation of every new advertised value to the parent hub.

js
function muteValueCallbacks()
cpp
int muteValueCallbacks()
m
-(int) muteValueCallbacks
pas
LongInt muteValueCallbacks(): LongInt
vb
function muteValueCallbacks() As Integer
cs
int muteValueCallbacks()
java
int muteValueCallbacks()
uwp
async Task<int> muteValueCallbacks()
py
muteValueCallbacks()
php
function muteValueCallbacks()
ts
async muteValueCallbacks(): Promise<number>
es
async muteValueCallbacks()
dnp
int muteValueCallbacks()
cp
int muteValueCallbacks()
cmd
YRefFrame target muteValueCallbacks

You can use this function to save bandwidth and CPU on computers with limited resources, or to prevent unwanted invocations of the HTTP callback. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

refframe→nextRefFrame()refframe.nextRefFrame()refframe→nextRefFrame()[refframe nextRefFrame]refframe.nextRefFrame()refframe.nextRefFrame()refframe.nextRefFrame()refframe.nextRefFrame()refframe.nextRefFrame()refframe.nextRefFrame()refframe→nextRefFrame()refframe.nextRefFrame()refframe.nextRefFrame()

Continues the enumeration of reference frames started using yFirstRefFrame().

js
function nextRefFrame()
cpp
YRefFrame * nextRefFrame()
m
-(nullable YRefFrame*) nextRefFrame
pas
TYRefFrame nextRefFrame(): TYRefFrame
vb
function nextRefFrame() As YRefFrame
cs
YRefFrame nextRefFrame()
java
YRefFrame nextRefFrame()
uwp
YRefFrame nextRefFrame()
py
nextRefFrame()
php
function nextRefFrame()
ts
nextRefFrame(): YRefFrame | null
es
nextRefFrame()

Caution: You can't make any assumption about the returned reference frames order. If you want to find a specific a reference frame, use RefFrame.findRefFrame() and a hardwareID or a logical name.

Returns :

a pointer to a YRefFrame object, corresponding to a reference frame currently online, or a null pointer if there are no more reference frames to enumerate.

refframe→registerValueCallback()refframe.registerValueCallback()refframe→registerValueCallback()[refframe registerValueCallback: ]refframe.registerValueCallback()refframe.registerValueCallback()refframe.registerValueCallback()refframe.registerValueCallback()refframe.registerValueCallback()refframe.registerValueCallback()refframe→registerValueCallback()refframe.registerValueCallback()refframe.registerValueCallback()

Registers the callback function that is invoked on every change of advertised value.

js
function registerValueCallback(callback)
cpp
int registerValueCallback(YRefFrameValueCallback callback)
m
-(int) registerValueCallback: (YRefFrameValueCallback _Nullable) callback
pas
LongInt registerValueCallback(callback: TYRefFrameValueCallback): LongInt
vb
function registerValueCallback(ByVal callback As YRefFrameValueCallback) As Integer
cs
int registerValueCallback(ValueCallback callback)
java
int registerValueCallback(UpdateCallback callback)
uwp
async Task<int> registerValueCallback(ValueCallback callback)
py
registerValueCallback(callback)
php
function registerValueCallback($callback)
ts
async registerValueCallback(callback: YRefFrameValueCallback | null): Promise<number>
es
async registerValueCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and the character string describing the new advertised value.

refframe→save3DCalibration()refframe.save3DCalibration()refframe→save3DCalibration()[refframe save3DCalibration]refframe.save3DCalibration()refframe.save3DCalibration()refframe.save3DCalibration()refframe.save3DCalibration()refframe.save3DCalibration()refframe.save3DCalibration()refframe→save3DCalibration()refframe.save3DCalibration()refframe.save3DCalibration()refframe.save3DCalibration()refframe.save3DCalibration()YRefFrame save3DCalibration

Applies the sensors tridimensional calibration parameters that have just been computed.

js
function save3DCalibration()
cpp
int save3DCalibration()
m
-(int) save3DCalibration
pas
LongInt save3DCalibration(): LongInt
vb
function save3DCalibration() As Integer
cs
int save3DCalibration()
java
int save3DCalibration()
uwp
async Task<int> save3DCalibration()
py
save3DCalibration()
php
function save3DCalibration()
ts
async save3DCalibration(): Promise<number>
es
async save3DCalibration()
dnp
int save3DCalibration()
cp
int save3DCalibration()
cmd
YRefFrame target save3DCalibration

Remember to call the saveToFlash() method of the module if the changes must be kept when the device is restarted.

On failure, throws an exception or returns a negative error code.

refframe→set_bearing()
refframe→setBearing()
refframe.set_bearing()refframe→set_bearing()[refframe setBearing: ]refframe.set_bearing()refframe.set_bearing()refframe.set_bearing()refframe.set_bearing()refframe.set_bearing()refframe.set_bearing()refframe→set_bearing()refframe.set_bearing()refframe.set_bearing()refframe.set_bearing()refframe.set_bearing()YRefFrame set_bearing

Changes the reference bearing used by the compass.

js
function set_bearing(newval)
cpp
int set_bearing(double newval)
m
-(int) setBearing: (double) newval
pas
integer set_bearing(newval: double): integer
vb
function set_bearing(ByVal newval As Double) As Integer
cs
int set_bearing(double newval)
java
int set_bearing(double newval)
uwp
async Task<int> set_bearing(double newval)
py
set_bearing(newval)
php
function set_bearing($newval)
ts
async set_bearing(newval: number): Promise<number>
es
async set_bearing(newval)
dnp
int set_bearing(double newval)
cp
int set_bearing(double newval)
cmd
YRefFrame target set_bearing newval

The relative bearing indicated by the compass is the difference between the measured magnetic heading and the reference bearing indicated here.

For instance, if you setup as reference bearing the value of the earth magnetic declination, the compass will provide the orientation relative to the geographic North.

Similarly, when the sensor is not mounted along the standard directions because it has an additional yaw angle, you can set this angle in the reference bearing so that the compass provides the expected natural direction.

Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala floating point number corresponding to the reference bearing used by the compass

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

refframe→set_fusionMode()
refframe→setFusionMode()
refframe.set_fusionMode()refframe→set_fusionMode()[refframe setFusionMode: ]refframe.set_fusionMode()refframe.set_fusionMode()refframe.set_fusionMode()refframe.set_fusionMode()refframe.set_fusionMode()refframe.set_fusionMode()refframe→set_fusionMode()refframe.set_fusionMode()refframe.set_fusionMode()refframe.set_fusionMode()refframe.set_fusionMode()YRefFrame set_fusionMode

Change the sensor fusion mode.

js
function set_fusionMode(newval)
cpp
int set_fusionMode(Y_FUSIONMODE_enum newval)
m
-(int) setFusionMode: (Y_FUSIONMODE_enum) newval
pas
integer set_fusionMode(newval: Integer): integer
vb
function set_fusionMode(ByVal newval As Integer) As Integer
cs
int set_fusionMode(int newval)
java
int set_fusionMode(int newval)
uwp
async Task<int> set_fusionMode(int newval)
py
set_fusionMode(newval)
php
function set_fusionMode($newval)
ts
async set_fusionMode(newval: YRefFrame_FusionMode): Promise<number>
es
async set_fusionMode(newval)
dnp
int set_fusionMode(int newval)
cp
int set_fusionMode(int newval)
cmd
YRefFrame target set_fusionMode newval

Note that available sensor fusion modes depend on the sensor type. Remember to call the matching module saveToFlash() method to save the setting permanently.

Parameters :

newvala value among YRefFrame.FUSIONMODE_NDOF, YRefFrame.FUSIONMODE_NDOF_FMC_OFF, YRefFrame.FUSIONMODE_M4G, YRefFrame.FUSIONMODE_COMPASS, YRefFrame.FUSIONMODE_IMU, YRefFrame.FUSIONMODE_INCLIN_90DEG_1G8, YRefFrame.FUSIONMODE_INCLIN_90DEG_3G6 and YRefFrame.FUSIONMODE_INCLIN_10DEG

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

refframe→set_logicalName()
refframe→setLogicalName()
refframe.set_logicalName()refframe→set_logicalName()[refframe setLogicalName: ]refframe.set_logicalName()refframe.set_logicalName()refframe.set_logicalName()refframe.set_logicalName()refframe.set_logicalName()refframe.set_logicalName()refframe→set_logicalName()refframe.set_logicalName()refframe.set_logicalName()refframe.set_logicalName()refframe.set_logicalName()YRefFrame set_logicalName

Changes the logical name of the reference frame.

js
function set_logicalName(newval)
cpp
int set_logicalName(string newval)
m
-(int) setLogicalName: (NSString*) newval
pas
integer set_logicalName(newval: string): integer
vb
function set_logicalName(ByVal newval As String) As Integer
cs
int set_logicalName(string newval)
java
int set_logicalName(String newval)
uwp
async Task<int> set_logicalName(string newval)
py
set_logicalName(newval)
php
function set_logicalName($newval)
ts
async set_logicalName(newval: string): Promise<number>
es
async set_logicalName(newval)
dnp
int set_logicalName(string newval)
cp
int set_logicalName(string newval)
cmd
YRefFrame target set_logicalName newval

You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the logical name of the reference frame.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

refframe→set_mountPosition()
refframe→setMountPosition()
refframe.set_mountPosition()refframe→set_mountPosition()[refframe setMountPosition: ]refframe.set_mountPosition()refframe.set_mountPosition()refframe.set_mountPosition()refframe.set_mountPosition()refframe.set_mountPosition()refframe.set_mountPosition()refframe→set_mountPosition()refframe.set_mountPosition()refframe.set_mountPosition()refframe.set_mountPosition()refframe.set_mountPosition()YRefFrame set_mountPosition

Changes the compass and tilt sensor frame of reference.

js
function set_mountPosition(position, orientation)
cpp
int set_mountPosition(Y_MOUNTPOSITION position,
  Y_MOUNTORIENTATION orientation)
m
-(int) setMountPosition: (Y_MOUNTPOSITION) position
  : (Y_MOUNTORIENTATION) orientation
pas
LongInt set_mountPosition(position: TYMOUNTPOSITION,
  orientation: TYMOUNTORIENTATION): LongInt
vb
function set_mountPosition(ByVal position As Y_MOUNTPOSITION,
  ByVal orientation As Y_MOUNTORIENTATION) As Integer
cs
int set_mountPosition(MOUNTPOSITION position,
  MOUNTORIENTATION orientation)
java
int set_mountPosition(MOUNTPOSITION position,
  MOUNTORIENTATION orientation)
uwp
async Task<int> set_mountPosition(MOUNTPOSITION position,
  MOUNTORIENTATION orientation)
py
set_mountPosition(position, orientation)
php
function set_mountPosition($position, $orientation)
ts
async set_mountPosition(position: YRefFrame_MountPosition, orientation: YRefFrame_MountOrientation): Promise<number>
es
async set_mountPosition(position, orientation)
dnp
int set_mountPosition(int position, int orientation)
cp
int set_mountPosition(int position, int orientation)
cmd
YRefFrame target set_mountPosition position orientation

The magnetic compass and the tilt sensors (pitch and roll) naturally work in the plane parallel to the earth surface. In case the device is not installed upright and horizontally, you must select its reference orientation (parallel to the earth surface) so that the measures are made relative to this position.

Parameters :

Remember to call the saveToFlash() method of the module if the modification must be kept.
positiona value among the YRefFrame.MOUNTPOSITION enumeration (YRefFrame.MOUNTPOSITION_BOTTOM, YRefFrame.MOUNTPOSITION_TOP, YRefFrame.MOUNTPOSITION_FRONT, YRefFrame.MOUNTPOSITION_RIGHT, YRefFrame.MOUNTPOSITION_REAR, YRefFrame.MOUNTPOSITION_LEFT), corresponding to the installation in a box, on one of the six faces.
orientationa value among the enumeration YRefFrame.MOUNTORIENTATION (YRefFrame.MOUNTORIENTATION_TWELVE, YRefFrame.MOUNTORIENTATION_THREE, YRefFrame.MOUNTORIENTATION_SIX, YRefFrame.MOUNTORIENTATION_NINE) corresponding to the orientation of the "X" arrow on the device, as on a clock dial seen from an observer in the center of the box. On the bottom face, the 12H orientation points to the front, while on the top face, the 12H orientation points to the rear.

On failure, throws an exception or returns a negative error code.

refframe→set_userData()
refframe→setUserData()
refframe.set_userData()refframe→set_userData()[refframe setUserData: ]refframe.set_userData()refframe.set_userData()refframe.set_userData()refframe.set_userData()refframe.set_userData()refframe→set_userData()refframe.set_userData()refframe.set_userData()

Stores a user context provided as argument in the userData attribute of the function.

js
function set_userData(data)
cpp
void set_userData(void * data)
m
-(void) setUserData: (id) data
pas
set_userData(data: Tobject)
vb
procedure set_userData(ByVal data As Object)
cs
void set_userData(object data)
java
void set_userData(Object data)
py
set_userData(data)
php
function set_userData($data)
ts
async set_userData(data: object|null): Promise<void>
es
async set_userData(data)

This attribute is never touched by the API, and is at disposal of the caller to store a context.

Parameters :

dataany kind of object to be stored

refframe→start3DCalibration()refframe.start3DCalibration()refframe→start3DCalibration()[refframe start3DCalibration]refframe.start3DCalibration()refframe.start3DCalibration()refframe.start3DCalibration()refframe.start3DCalibration()refframe.start3DCalibration()refframe.start3DCalibration()refframe→start3DCalibration()refframe.start3DCalibration()refframe.start3DCalibration()refframe.start3DCalibration()refframe.start3DCalibration()YRefFrame start3DCalibration

Initiates the sensors tridimensional calibration process.

js
function start3DCalibration()
cpp
int start3DCalibration()
m
-(int) start3DCalibration
pas
LongInt start3DCalibration(): LongInt
vb
function start3DCalibration() As Integer
cs
int start3DCalibration()
java
int start3DCalibration()
uwp
async Task<int> start3DCalibration()
py
start3DCalibration()
php
function start3DCalibration()
ts
async start3DCalibration(): Promise<number>
es
async start3DCalibration()
dnp
int start3DCalibration()
cp
int start3DCalibration()
cmd
YRefFrame target start3DCalibration

This calibration is used at low level for inertial position estimation and to enhance the precision of the tilt sensors.

After calling this method, the device should be moved according to the instructions provided by method get_3DCalibrationHint, and more3DCalibration should be invoked about 5 times per second. The calibration procedure is completed when the method get_3DCalibrationProgress returns 100. At this point, the computed calibration parameters can be applied using method save3DCalibration. The calibration process can be cancelled at any time using method cancel3DCalibration.

On failure, throws an exception or returns a negative error code.

refframe→unmuteValueCallbacks()refframe.unmuteValueCallbacks()refframe→unmuteValueCallbacks()[refframe unmuteValueCallbacks]refframe.unmuteValueCallbacks()refframe.unmuteValueCallbacks()refframe.unmuteValueCallbacks()refframe.unmuteValueCallbacks()refframe.unmuteValueCallbacks()refframe.unmuteValueCallbacks()refframe→unmuteValueCallbacks()refframe.unmuteValueCallbacks()refframe.unmuteValueCallbacks()refframe.unmuteValueCallbacks()refframe.unmuteValueCallbacks()YRefFrame unmuteValueCallbacks

Re-enables the propagation of every new advertised value to the parent hub.

js
function unmuteValueCallbacks()
cpp
int unmuteValueCallbacks()
m
-(int) unmuteValueCallbacks
pas
LongInt unmuteValueCallbacks(): LongInt
vb
function unmuteValueCallbacks() As Integer
cs
int unmuteValueCallbacks()
java
int unmuteValueCallbacks()
uwp
async Task<int> unmuteValueCallbacks()
py
unmuteValueCallbacks()
php
function unmuteValueCallbacks()
ts
async unmuteValueCallbacks(): Promise<number>
es
async unmuteValueCallbacks()
dnp
int unmuteValueCallbacks()
cp
int unmuteValueCallbacks()
cmd
YRefFrame target unmuteValueCallbacks

This function reverts the effect of a previous call to muteValueCallbacks(). Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

refframe→wait_async()refframe.wait_async()refframe.wait_async()refframe.wait_async()

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

js
function wait_async(callback, context)
ts
wait_async(callback: Function, context: object)
es
wait_async(callback, context)

The callback function can therefore freely issue synchronous or asynchronous commands, without risking to block the JavaScript VM.

Parameters :

callbackcallback function that is invoked when all pending commands on the module are completed. The callback function receives two arguments: the caller-specific context object and the receiving function object.
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing.

24.6. Class YTilt

Tilt sensor control interface, available for instance in the Yocto-3D-V2 or the Yocto-Inclinometer

The YSensor class is the parent class for all Yoctopuce sensor types. It can be used to read the current value and unit of any sensor, read the min/max value, configure autonomous recording frequency and access recorded data. It also provide a function to register a callback invoked each time the observed value changes, or at a predefined interval. Using this class rather than a specific subclass makes it possible to create generic applications that work with any Yoctopuce sensor, even those that do not yet exist. Note: The YAnButton class is the only analog input which does not inherit from YSensor.

In order to use the functions described here, you should include:

es
in HTML: <script src="../../lib/yocto_tilt.js"></script>
in node.js: require('yoctolib-es2017/yocto_tilt.js');
js
<script type='text/javascript' src='yocto_tilt.js'></script>
cpp
#include "yocto_tilt.h"
m
#import "yocto_tilt.h"
pas
uses yocto_tilt;
vb
yocto_tilt.vb
cs
yocto_tilt.cs
java
import com.yoctopuce.YoctoAPI.YTilt;
uwp
import com.yoctopuce.YoctoAPI.YTilt;
py
from yocto_tilt import *
php
require_once('yocto_tilt.php');
ts
in HTML: import { YTilt } from '../../dist/esm/yocto_tilt.js';
in Node.js: import { YTilt } from 'yoctolib-cjs/yocto_tilt.js';
dnp
import YoctoProxyAPI.YTiltProxy
cp
#include "yocto_tilt_proxy.h"
vi
YTilt.vi
ml
import YoctoProxyAPI.YTiltProxy
Global functions
YTilt.FindTilt(func)

Retrieves a tilt sensor for a given identifier.

YTilt.FindTiltInContext(yctx, func)

Retrieves a tilt sensor for a given identifier in a YAPI context.

YTilt.FirstTilt()

Starts the enumeration of tilt sensors currently accessible.

YTilt.FirstTiltInContext(yctx)

Starts the enumeration of tilt sensors currently accessible.

YTilt.GetSimilarFunctions()

Enumerates all functions of type Tilt available on the devices currently reachable by the library, and returns their unique hardware ID.

YTilt properties
tilt→AdvMode [writable]

Measuring mode used for the advertised value pushed to the parent hub.

tilt→AdvertisedValue [read-only]

Short string representing the current state of the function.

tilt→Bandwidth [writable]

Measure update frequency, measured in Hz.

tilt→FriendlyName [read-only]

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

tilt→FunctionId [read-only]

Hardware identifier of the sensor, without reference to the module.

tilt→HardwareId [read-only]

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

tilt→IsOnline [read-only]

Checks if the function is currently reachable.

tilt→LogFrequency [writable]

Datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

tilt→LogicalName [writable]

Logical name of the function.

tilt→ReportFrequency [writable]

Timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

tilt→Resolution [writable]

Resolution of the measured values.

tilt→SerialNumber [read-only]

Serial number of the module, as set by the factory.

YTilt methods
tilt→calibrateFromPoints(rawValues, refValues)

Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.

tilt→calibrateToZero()

Performs a zero calibration for the tilt measurement (Yocto-Inclinometer only).

tilt→clearCache()

Invalidates the cache.

tilt→describe()

Returns a short text that describes unambiguously the instance of the tilt sensor in the form TYPE(NAME)=SERIAL.FUNCTIONID.

tilt→get_advMode()

Returns the measuring mode used for the advertised value pushed to the parent hub.

tilt→get_advertisedValue()

Returns the current value of the tilt sensor (no more than 6 characters).

tilt→get_bandwidth()

Returns the measure update frequency, measured in Hz.

tilt→get_currentRawValue()

Returns the uncalibrated, unrounded raw value returned by the sensor, in degrees, as a floating point number.

tilt→get_currentValue()

Returns the current value of the inclination, in degrees, as a floating point number.

tilt→get_dataLogger()

Returns the YDatalogger object of the device hosting the sensor.

tilt→get_errorMessage()

Returns the error message of the latest error with the tilt sensor.

tilt→get_errorType()

Returns the numerical error code of the latest error with the tilt sensor.

tilt→get_friendlyName()

Returns a global identifier of the tilt sensor in the format MODULE_NAME.FUNCTION_NAME.

tilt→get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

tilt→get_functionId()

Returns the hardware identifier of the tilt sensor, without reference to the module.

tilt→get_hardwareId()

Returns the unique hardware identifier of the tilt sensor in the form SERIAL.FUNCTIONID.

tilt→get_highestValue()

Returns the maximal value observed for the inclination since the device was started.

tilt→get_logFrequency()

Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

tilt→get_logicalName()

Returns the logical name of the tilt sensor.

tilt→get_lowestValue()

Returns the minimal value observed for the inclination since the device was started.

tilt→get_module()

Gets the YModule object for the device on which the function is located.

tilt→get_module_async(callback, context)

Gets the YModule object for the device on which the function is located (asynchronous version).

tilt→get_recordedData(startTime, endTime)

Retrieves a YDataSet object holding historical data for this sensor, for a specified time interval.

tilt→get_reportFrequency()

Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

tilt→get_resolution()

Returns the resolution of the measured values.

tilt→get_sensorState()

Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.

tilt→get_serialNumber()

Returns the serial number of the module, as set by the factory.

tilt→get_unit()

Returns the measuring unit for the inclination.

tilt→get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

tilt→isOnline()

Checks if the tilt sensor is currently reachable, without raising any error.

tilt→isOnline_async(callback, context)

Checks if the tilt sensor is currently reachable, without raising any error (asynchronous version).

tilt→isReadOnly()

Test if the function is readOnly.

tilt→isSensorReady()

Checks if the sensor is currently able to provide an up-to-date measure.

tilt→load(msValidity)

Preloads the tilt sensor cache with a specified validity duration.

tilt→loadAttribute(attrName)

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

tilt→loadCalibrationPoints(rawValues, refValues)

Retrieves error correction data points previously entered using the method calibrateFromPoints.

tilt→load_async(msValidity, callback, context)

Preloads the tilt sensor cache with a specified validity duration (asynchronous version).

tilt→muteValueCallbacks()

Disables the propagation of every new advertised value to the parent hub.

tilt→nextTilt()

Continues the enumeration of tilt sensors started using yFirstTilt().

tilt→registerTimedReportCallback(callback)

Registers the callback function that is invoked on every periodic timed notification.

tilt→registerValueCallback(callback)

Registers the callback function that is invoked on every change of advertised value.

tilt→restoreZeroCalibration()

Cancels any previous zero calibration for the tilt measurement (Yocto-Inclinometer only).

tilt→set_advMode(newval)

Changes the measuring mode used for the advertised value pushed to the parent hub.

tilt→set_bandwidth(newval)

Changes the measure update frequency, measured in Hz.

tilt→set_highestValue(newval)

Changes the recorded maximal value observed.

tilt→set_logFrequency(newval)

Changes the datalogger recording frequency for this function.

tilt→set_logicalName(newval)

Changes the logical name of the tilt sensor.

tilt→set_lowestValue(newval)

Changes the recorded minimal value observed.

tilt→set_reportFrequency(newval)

Changes the timed value notification frequency for this function.

tilt→set_resolution(newval)

Changes the resolution of the measured physical values.

tilt→set_userData(data)

Stores a user context provided as argument in the userData attribute of the function.

tilt→startDataLogger()

Starts the data logger on the device.

tilt→stopDataLogger()

Stops the datalogger on the device.

tilt→unmuteValueCallbacks()

Re-enables the propagation of every new advertised value to the parent hub.

tilt→wait_async(callback, context)

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

YTilt.FindTilt()
YTilt.FindTilt()
yFindTilt()YTilt::FindTilt()[YTilt FindTilt: ]yFindTilt()YTilt.FindTilt()YTilt.FindTilt()YTilt.FindTilt()YTilt.FindTilt()YTilt.FindTilt()YTilt::FindTilt()YTilt.FindTilt()YTilt.FindTilt()YTilt.FindTilt()YTilt.FindTilt()

Retrieves a tilt sensor for a given identifier.

js
function yFindTilt(func)
cpp
YTilt* FindTilt(string func)
m
+(YTilt*) FindTilt: (NSString*) func
pas
TYTilt yFindTilt(func: string): TYTilt
vb
function FindTilt(ByVal func As String) As YTilt
cs
static YTilt FindTilt(string func)
java
static YTilt FindTilt(String func)
uwp
static YTilt FindTilt(string func)
py
FindTilt(func)
php
function FindTilt($func)
ts
static FindTilt(func: string): YTilt
es
static FindTilt(func)
dnp
static YTiltProxy FindTilt(string func)
cp
static YTiltProxy * FindTilt(string func)

The identifier can be specified using several formats:

This function does not require that the tilt sensor is online at the time it is invoked. The returned object is nevertheless valid. Use the method YTilt.isOnline() to test if the tilt sensor is indeed online at a given time. In case of ambiguity when looking for a tilt sensor by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

If a call to this object's is_online() method returns FALSE although you are certain that the matching device is plugged, make sure that you did call registerHub() at application initialization time.

Parameters :

funca string that uniquely characterizes the tilt sensor, for instance Y3DMK002.tilt1.

Returns :

a YTilt object allowing you to drive the tilt sensor.

YTilt.FindTiltInContext()
YTilt.FindTiltInContext()
YTilt.FindTiltInContext()YTilt.FindTiltInContext()YTilt.FindTiltInContext()YTilt.FindTiltInContext()

Retrieves a tilt sensor for a given identifier in a YAPI context.

java
static YTilt FindTiltInContext(YAPIContext yctx, String func)
uwp
static YTilt FindTiltInContext(YAPIContext yctx, string func)
ts
static FindTiltInContext(yctx: YAPIContext, func: string): YTilt
es
static FindTiltInContext(yctx, func)

The identifier can be specified using several formats:

This function does not require that the tilt sensor is online at the time it is invoked. The returned object is nevertheless valid. Use the method YTilt.isOnline() to test if the tilt sensor is indeed online at a given time. In case of ambiguity when looking for a tilt sensor by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

Parameters :

yctxa YAPI context
funca string that uniquely characterizes the tilt sensor, for instance Y3DMK002.tilt1.

Returns :

a YTilt object allowing you to drive the tilt sensor.

YTilt.FirstTilt()
YTilt.FirstTilt()
yFirstTilt()YTilt::FirstTilt()[YTilt FirstTilt]yFirstTilt()YTilt.FirstTilt()YTilt.FirstTilt()YTilt.FirstTilt()YTilt.FirstTilt()YTilt.FirstTilt()YTilt::FirstTilt()YTilt.FirstTilt()YTilt.FirstTilt()

Starts the enumeration of tilt sensors currently accessible.

js
function yFirstTilt()
cpp
YTilt * FirstTilt()
m
+(YTilt*) FirstTilt
pas
TYTilt yFirstTilt(): TYTilt
vb
function FirstTilt() As YTilt
cs
static YTilt FirstTilt()
java
static YTilt FirstTilt()
uwp
static YTilt FirstTilt()
py
FirstTilt()
php
function FirstTilt()
ts
static FirstTilt(): YTilt | null
es
static FirstTilt()

Use the method YTilt.nextTilt() to iterate on next tilt sensors.

Returns :

a pointer to a YTilt object, corresponding to the first tilt sensor currently online, or a null pointer if there are none.

YTilt.FirstTiltInContext()
YTilt.FirstTiltInContext()
YTilt.FirstTiltInContext()YTilt.FirstTiltInContext()YTilt.FirstTiltInContext()YTilt.FirstTiltInContext()

Starts the enumeration of tilt sensors currently accessible.

java
static YTilt FirstTiltInContext(YAPIContext yctx)
uwp
static YTilt FirstTiltInContext(YAPIContext yctx)
ts
static FirstTiltInContext(yctx: YAPIContext): YTilt | null
es
static FirstTiltInContext(yctx)

Use the method YTilt.nextTilt() to iterate on next tilt sensors.

Parameters :

yctxa YAPI context.

Returns :

a pointer to a YTilt object, corresponding to the first tilt sensor currently online, or a null pointer if there are none.

YTilt.GetSimilarFunctions()
YTilt.GetSimilarFunctions()
YTilt.GetSimilarFunctions()YTilt.GetSimilarFunctions()

Enumerates all functions of type Tilt available on the devices currently reachable by the library, and returns their unique hardware ID.

dnp
static new string[] GetSimilarFunctions()
cp
static vector<string> GetSimilarFunctions()

Each of these IDs can be provided as argument to the method YTilt.FindTilt to obtain an object that can control the corresponding device.

Returns :

an array of strings, each string containing the unique hardwareId of a device function currently connected.

tilt→AdvModetilt.AdvMode

Measuring mode used for the advertised value pushed to the parent hub.

dnp
int AdvMode

Writable. Remember to call the saveToFlash() method of the module if the modification must be kept.

tilt→AdvertisedValuetilt.AdvertisedValue

Short string representing the current state of the function.

dnp
string AdvertisedValue

tilt→Bandwidthtilt.Bandwidth

Measure update frequency, measured in Hz.

dnp
int Bandwidth

Writable. When the frequency is lower, the device performs averaging. Remember to call the saveToFlash() method of the module if the modification must be kept.

tilt→FriendlyNametilt.FriendlyName

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

dnp
string FriendlyName

The returned string uses the logical names of the module and of the function if they are defined, otherwise the serial number of the module and the hardware identifier of the function (for example: MyCustomName.relay1)

tilt→FunctionIdtilt.FunctionId

Hardware identifier of the sensor, without reference to the module.

dnp
string FunctionId

For example relay1

tilt→HardwareIdtilt.HardwareId

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

dnp
string HardwareId

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the function (for example RELAYLO1-123456.relay1).

tilt→IsOnlinetilt.IsOnline

Checks if the function is currently reachable.

dnp
bool IsOnline

If there is a cached value for the function in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the function.

tilt→LogFrequencytilt.LogFrequency

Datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

dnp
string LogFrequency

Writable. Changes the datalogger recording frequency for this function. The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (eg. "4/h"). To disable recording for this function, use the value "OFF". Note that setting the datalogger recording frequency to a greater value than the sensor native sampling frequency is useless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

tilt→LogicalNametilt.LogicalName

Logical name of the function.

dnp
string LogicalName

Writable. You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

tilt→ReportFrequencytilt.ReportFrequency

Timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

dnp
string ReportFrequency

Writable. Changes the timed value notification frequency for this function. The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (e.g. "4/h"). To disable timed value notifications for this function, use the value "OFF". Note that setting the timed value notification frequency to a greater value than the sensor native sampling frequency is unless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

tilt→Resolutiontilt.Resolution

Resolution of the measured values.

dnp
double Resolution

The resolution corresponds to the numerical precision of the measures, which is not always the same as the actual precision of the sensor. Remember to call the saveToFlash() method of the module if the modification must be kept.

Writable. Changes the resolution of the measured physical values. The resolution corresponds to the numerical precision when displaying value. It does not change the precision of the measure itself. Remember to call the saveToFlash() method of the module if the modification must be kept.

tilt→SerialNumbertilt.SerialNumber

Serial number of the module, as set by the factory.

dnp
string SerialNumber

tilt→calibrateFromPoints()tilt.calibrateFromPoints()tilt→calibrateFromPoints()[tilt calibrateFromPoints: ]tilt.calibrateFromPoints()tilt.calibrateFromPoints()tilt.calibrateFromPoints()tilt.calibrateFromPoints()tilt.calibrateFromPoints()tilt.calibrateFromPoints()tilt→calibrateFromPoints()tilt.calibrateFromPoints()tilt.calibrateFromPoints()tilt.calibrateFromPoints()tilt.calibrateFromPoints()YTilt calibrateFromPoints

Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.

js
function calibrateFromPoints(rawValues, refValues)
cpp
int calibrateFromPoints(vector<double> rawValues,
  vector<double> refValues)
m
-(int) calibrateFromPoints: (NSMutableArray*) rawValues
  : (NSMutableArray*) refValues
pas
LongInt calibrateFromPoints(rawValues: TDoubleArray,
  refValues: TDoubleArray): LongInt
vb
procedure calibrateFromPoints(ByVal rawValues As List(Of)
cs
int calibrateFromPoints(List<double> rawValues,
  List<double> refValues)
java
int calibrateFromPoints(ArrayList<Double> rawValues,
  ArrayList<Double> refValues)
uwp
async Task<int> calibrateFromPoints(List<double> rawValues,
  List<double> refValues)
py
calibrateFromPoints(rawValues, refValues)
php
function calibrateFromPoints($rawValues, $refValues)
ts
async calibrateFromPoints(rawValues: number[], refValues: number[]): Promise<number>
es
async calibrateFromPoints(rawValues, refValues)
dnp
int calibrateFromPoints(double[] rawValues,
  double[] refValues)
cp
int calibrateFromPoints(vector<double> rawValues,
  vector<double> refValues)
cmd
YTilt target calibrateFromPoints rawValues refValues

It is possible to configure up to five correction points. Correction points must be provided in ascending order, and be in the range of the sensor. The device will automatically perform a linear interpolation of the error correction between specified points. Remember to call the saveToFlash() method of the module if the modification must be kept.

For more information on advanced capabilities to refine the calibration of sensors, please contact support@yoctopuce.com.

Parameters :

rawValuesarray of floating point numbers, corresponding to the raw values returned by the sensor for the correction points.
refValuesarray of floating point numbers, corresponding to the corrected values for the correction points.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→calibrateToZero()tilt.calibrateToZero()tilt→calibrateToZero()[tilt calibrateToZero]tilt.calibrateToZero()tilt.calibrateToZero()tilt.calibrateToZero()tilt.calibrateToZero()tilt.calibrateToZero()tilt.calibrateToZero()tilt→calibrateToZero()tilt.calibrateToZero()tilt.calibrateToZero()tilt.calibrateToZero()tilt.calibrateToZero()YTilt calibrateToZero

Performs a zero calibration for the tilt measurement (Yocto-Inclinometer only).

js
function calibrateToZero()
cpp
int calibrateToZero()
m
-(int) calibrateToZero
pas
LongInt calibrateToZero(): LongInt
vb
function calibrateToZero() As Integer
cs
int calibrateToZero()
java
int calibrateToZero()
uwp
async Task<int> calibrateToZero()
py
calibrateToZero()
php
function calibrateToZero()
ts
async calibrateToZero(): Promise<number>
es
async calibrateToZero()
dnp
int calibrateToZero()
cp
int calibrateToZero()
cmd
YTilt target calibrateToZero

When this method is invoked, a simple shift (translation) is applied so that the current position is reported as a zero angle. Be aware that this shift will also affect the measurement boundaries.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→clearCache()tilt.clearCache()tilt→clearCache()[tilt clearCache]tilt.clearCache()tilt.clearCache()tilt.clearCache()tilt.clearCache()tilt.clearCache()tilt→clearCache()tilt.clearCache()tilt.clearCache()

Invalidates the cache.

js
function clearCache()
cpp
void clearCache()
m
-(void) clearCache
pas
clearCache()
vb
procedure clearCache()
cs
void clearCache()
java
void clearCache()
py
clearCache()
php
function clearCache()
ts
async clearCache(): Promise<void>
es
async clearCache()

Invalidates the cache of the tilt sensor attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.

tilt→describe()tilt.describe()tilt→describe()[tilt describe]tilt.describe()tilt.describe()tilt.describe()tilt.describe()tilt.describe()tilt→describe()tilt.describe()tilt.describe()

Returns a short text that describes unambiguously the instance of the tilt sensor in the form TYPE(NAME)=SERIAL.FUNCTIONID.

js
function describe()
cpp
string describe()
m
-(NSString*) describe
pas
string describe(): string
vb
function describe() As String
cs
string describe()
java
String describe()
py
describe()
php
function describe()
ts
async describe(): Promise<string>
es
async describe()

More precisely, TYPE is the type of the function, NAME it the name used for the first access to the function, SERIAL is the serial number of the module if the module is connected or "unresolved", and FUNCTIONID is the hardware identifier of the function if the module is connected. For example, this method returns Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1 if the module is already connected or Relay(BadCustomeName.relay1)=unresolved if the module has not yet been connected. This method does not trigger any USB or TCP transaction and can therefore be used in a debugger.

Returns :

a string that describes the tilt sensor (ex: Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1)

tilt→get_advMode()
tilt→advMode()
tilt.get_advMode()tilt→get_advMode()[tilt advMode]tilt.get_advMode()tilt.get_advMode()tilt.get_advMode()tilt.get_advMode()tilt.get_advMode()tilt.get_advMode()tilt→get_advMode()tilt.get_advMode()tilt.get_advMode()tilt.get_advMode()tilt.get_advMode()YTilt get_advMode

Returns the measuring mode used for the advertised value pushed to the parent hub.

js
function get_advMode()
cpp
Y_ADVMODE_enum get_advMode()
m
-(Y_ADVMODE_enum) advMode
pas
Integer get_advMode(): Integer
vb
function get_advMode() As Integer
cs
int get_advMode()
java
int get_advMode()
uwp
async Task<int> get_advMode()
py
get_advMode()
php
function get_advMode()
ts
async get_advMode(): Promise<YSensor_AdvMode>
es
async get_advMode()
dnp
int get_advMode()
cp
int get_advMode()
cmd
YTilt target get_advMode

Returns :

a value among YTilt.ADVMODE_IMMEDIATE, YTilt.ADVMODE_PERIOD_AVG, YTilt.ADVMODE_PERIOD_MIN and YTilt.ADVMODE_PERIOD_MAX corresponding to the measuring mode used for the advertised value pushed to the parent hub

On failure, throws an exception or returns YTilt.ADVMODE_INVALID.

tilt→get_advertisedValue()
tilt→advertisedValue()
tilt.get_advertisedValue()tilt→get_advertisedValue()[tilt advertisedValue]tilt.get_advertisedValue()tilt.get_advertisedValue()tilt.get_advertisedValue()tilt.get_advertisedValue()tilt.get_advertisedValue()tilt.get_advertisedValue()tilt→get_advertisedValue()tilt.get_advertisedValue()tilt.get_advertisedValue()tilt.get_advertisedValue()tilt.get_advertisedValue()YTilt get_advertisedValue

Returns the current value of the tilt sensor (no more than 6 characters).

js
function get_advertisedValue()
cpp
string get_advertisedValue()
m
-(NSString*) advertisedValue
pas
string get_advertisedValue(): string
vb
function get_advertisedValue() As String
cs
string get_advertisedValue()
java
String get_advertisedValue()
uwp
async Task<string> get_advertisedValue()
py
get_advertisedValue()
php
function get_advertisedValue()
ts
async get_advertisedValue(): Promise<string>
es
async get_advertisedValue()
dnp
string get_advertisedValue()
cp
string get_advertisedValue()
cmd
YTilt target get_advertisedValue

Returns :

a string corresponding to the current value of the tilt sensor (no more than 6 characters).

On failure, throws an exception or returns YTilt.ADVERTISEDVALUE_INVALID.

tilt→get_bandwidth()
tilt→bandwidth()
tilt.get_bandwidth()tilt→get_bandwidth()[tilt bandwidth]tilt.get_bandwidth()tilt.get_bandwidth()tilt.get_bandwidth()tilt.get_bandwidth()tilt.get_bandwidth()tilt.get_bandwidth()tilt→get_bandwidth()tilt.get_bandwidth()tilt.get_bandwidth()tilt.get_bandwidth()tilt.get_bandwidth()YTilt get_bandwidth

Returns the measure update frequency, measured in Hz.

js
function get_bandwidth()
cpp
int get_bandwidth()
m
-(int) bandwidth
pas
LongInt get_bandwidth(): LongInt
vb
function get_bandwidth() As Integer
cs
int get_bandwidth()
java
int get_bandwidth()
uwp
async Task<int> get_bandwidth()
py
get_bandwidth()
php
function get_bandwidth()
ts
async get_bandwidth(): Promise<number>
es
async get_bandwidth()
dnp
int get_bandwidth()
cp
int get_bandwidth()
cmd
YTilt target get_bandwidth

Returns :

an integer corresponding to the measure update frequency, measured in Hz

On failure, throws an exception or returns YTilt.BANDWIDTH_INVALID.

tilt→get_currentRawValue()
tilt→currentRawValue()
tilt.get_currentRawValue()tilt→get_currentRawValue()[tilt currentRawValue]tilt.get_currentRawValue()tilt.get_currentRawValue()tilt.get_currentRawValue()tilt.get_currentRawValue()tilt.get_currentRawValue()tilt.get_currentRawValue()tilt→get_currentRawValue()tilt.get_currentRawValue()tilt.get_currentRawValue()tilt.get_currentRawValue()tilt.get_currentRawValue()YTilt get_currentRawValue

Returns the uncalibrated, unrounded raw value returned by the sensor, in degrees, as a floating point number.

js
function get_currentRawValue()
cpp
double get_currentRawValue()
m
-(double) currentRawValue
pas
double get_currentRawValue(): double
vb
function get_currentRawValue() As Double
cs
double get_currentRawValue()
java
double get_currentRawValue()
uwp
async Task<double> get_currentRawValue()
py
get_currentRawValue()
php
function get_currentRawValue()
ts
async get_currentRawValue(): Promise<number>
es
async get_currentRawValue()
dnp
double get_currentRawValue()
cp
double get_currentRawValue()
cmd
YTilt target get_currentRawValue

Returns :

a floating point number corresponding to the uncalibrated, unrounded raw value returned by the sensor, in degrees, as a floating point number

On failure, throws an exception or returns YTilt.CURRENTRAWVALUE_INVALID.

tilt→get_currentValue()
tilt→currentValue()
tilt.get_currentValue()tilt→get_currentValue()[tilt currentValue]tilt.get_currentValue()tilt.get_currentValue()tilt.get_currentValue()tilt.get_currentValue()tilt.get_currentValue()tilt.get_currentValue()tilt→get_currentValue()tilt.get_currentValue()tilt.get_currentValue()tilt.get_currentValue()tilt.get_currentValue()YTilt get_currentValue

Returns the current value of the inclination, in degrees, as a floating point number.

js
function get_currentValue()
cpp
double get_currentValue()
m
-(double) currentValue
pas
double get_currentValue(): double
vb
function get_currentValue() As Double
cs
double get_currentValue()
java
double get_currentValue()
uwp
async Task<double> get_currentValue()
py
get_currentValue()
php
function get_currentValue()
ts
async get_currentValue(): Promise<number>
es
async get_currentValue()
dnp
double get_currentValue()
cp
double get_currentValue()
cmd
YTilt target get_currentValue

Note that a get_currentValue() call will *not* start a measure in the device, it will just return the last measure that occurred in the device. Indeed, internally, each Yoctopuce devices is continuously making measurements at a hardware specific frequency.

If continuously calling get_currentValue() leads you to performances issues, then you might consider to switch to callback programming model. Check the "advanced programming" chapter in in your device user manual for more information.

Returns :

a floating point number corresponding to the current value of the inclination, in degrees, as a floating point number

On failure, throws an exception or returns YTilt.CURRENTVALUE_INVALID.

tilt→get_dataLogger()
tilt→dataLogger()
tilt.get_dataLogger()tilt→get_dataLogger()[tilt dataLogger]tilt.get_dataLogger()tilt.get_dataLogger()tilt.get_dataLogger()tilt.get_dataLogger()tilt.get_dataLogger()tilt.get_dataLogger()tilt→get_dataLogger()tilt.get_dataLogger()tilt.get_dataLogger()tilt.get_dataLogger()tilt.get_dataLogger()

Returns the YDatalogger object of the device hosting the sensor.

js
function get_dataLogger()
cpp
YDataLogger* get_dataLogger()
m
-(YDataLogger*) dataLogger
pas
TYDataLogger get_dataLogger(): TYDataLogger
vb
function get_dataLogger() As YDataLogger
cs
YDataLogger get_dataLogger()
java
YDataLogger get_dataLogger()
uwp
async Task<YDataLogger> get_dataLogger()
py
get_dataLogger()
php
function get_dataLogger()
ts
async get_dataLogger(): Promise<YDataLogger | null>
es
async get_dataLogger()
dnp
YDataLoggerProxy get_dataLogger()
cp
YDataLoggerProxy* get_dataLogger()

This method returns an object that can control global parameters of the data logger. The returned object should not be freed.

Returns :

an YDatalogger object, or null on error.

tilt→get_errorMessage()
tilt→errorMessage()
tilt.get_errorMessage()tilt→get_errorMessage()[tilt errorMessage]tilt.get_errorMessage()tilt.get_errorMessage()tilt.get_errorMessage()tilt.get_errorMessage()tilt.get_errorMessage()tilt→get_errorMessage()tilt.get_errorMessage()tilt.get_errorMessage()

Returns the error message of the latest error with the tilt sensor.

js
function get_errorMessage()
cpp
string get_errorMessage()
m
-(NSString*) errorMessage
pas
string get_errorMessage(): string
vb
function get_errorMessage() As String
cs
string get_errorMessage()
java
String get_errorMessage()
py
get_errorMessage()
php
function get_errorMessage()
ts
get_errorMessage(): string
es
get_errorMessage()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a string corresponding to the latest error message that occured while using the tilt sensor object

tilt→get_errorType()
tilt→errorType()
tilt.get_errorType()tilt→get_errorType()[tilt errorType]tilt.get_errorType()tilt.get_errorType()tilt.get_errorType()tilt.get_errorType()tilt.get_errorType()tilt→get_errorType()tilt.get_errorType()tilt.get_errorType()

Returns the numerical error code of the latest error with the tilt sensor.

js
function get_errorType()
cpp
YRETCODE get_errorType()
m
-(YRETCODE) errorType
pas
YRETCODE get_errorType(): YRETCODE
vb
function get_errorType() As YRETCODE
cs
YRETCODE get_errorType()
java
int get_errorType()
py
get_errorType()
php
function get_errorType()
ts
get_errorType(): number
es
get_errorType()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a number corresponding to the code of the latest error that occurred while using the tilt sensor object

tilt→get_friendlyName()
tilt→friendlyName()
tilt.get_friendlyName()tilt→get_friendlyName()[tilt friendlyName]tilt.get_friendlyName()tilt.get_friendlyName()tilt.get_friendlyName()tilt→get_friendlyName()tilt.get_friendlyName()tilt.get_friendlyName()tilt.get_friendlyName()tilt.get_friendlyName()

Returns a global identifier of the tilt sensor in the format MODULE_NAME.FUNCTION_NAME.

js
function get_friendlyName()
cpp
string get_friendlyName()
m
-(NSString*) friendlyName
cs
string get_friendlyName()
java
String get_friendlyName()
py
get_friendlyName()
php
function get_friendlyName()
ts
async get_friendlyName(): Promise<string>
es
async get_friendlyName()
dnp
string get_friendlyName()
cp
string get_friendlyName()

The returned string uses the logical names of the module and of the tilt sensor if they are defined, otherwise the serial number of the module and the hardware identifier of the tilt sensor (for example: MyCustomName.relay1)

Returns :

a string that uniquely identifies the tilt sensor using logical names (ex: MyCustomName.relay1)

On failure, throws an exception or returns YTilt.FRIENDLYNAME_INVALID.

tilt→get_functionDescriptor()
tilt→functionDescriptor()
tilt.get_functionDescriptor()tilt→get_functionDescriptor()[tilt functionDescriptor]tilt.get_functionDescriptor()tilt.get_functionDescriptor()tilt.get_functionDescriptor()tilt.get_functionDescriptor()tilt.get_functionDescriptor()tilt→get_functionDescriptor()tilt.get_functionDescriptor()tilt.get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

js
function get_functionDescriptor()
cpp
YFUN_DESCR get_functionDescriptor()
m
-(YFUN_DESCR) functionDescriptor
pas
YFUN_DESCR get_functionDescriptor(): YFUN_DESCR
vb
function get_functionDescriptor() As YFUN_DESCR
cs
YFUN_DESCR get_functionDescriptor()
java
String get_functionDescriptor()
py
get_functionDescriptor()
php
function get_functionDescriptor()
ts
async get_functionDescriptor(): Promise<string>
es
async get_functionDescriptor()

This identifier can be used to test if two instances of YFunction reference the same physical function on the same physical device.

Returns :

an identifier of type YFUN_DESCR.

If the function has never been contacted, the returned value is Y$CLASSNAME$.FUNCTIONDESCRIPTOR_INVALID.

tilt→get_functionId()
tilt→functionId()
tilt.get_functionId()tilt→get_functionId()[tilt functionId]tilt.get_functionId()tilt.get_functionId()tilt.get_functionId()tilt.get_functionId()tilt→get_functionId()tilt.get_functionId()tilt.get_functionId()tilt.get_functionId()tilt.get_functionId()

Returns the hardware identifier of the tilt sensor, without reference to the module.

js
function get_functionId()
cpp
string get_functionId()
m
-(NSString*) functionId
vb
function get_functionId() As String
cs
string get_functionId()
java
String get_functionId()
py
get_functionId()
php
function get_functionId()
ts
async get_functionId(): Promise<string>
es
async get_functionId()
dnp
string get_functionId()
cp
string get_functionId()

For example relay1

Returns :

a string that identifies the tilt sensor (ex: relay1)

On failure, throws an exception or returns YTilt.FUNCTIONID_INVALID.

tilt→get_hardwareId()
tilt→hardwareId()
tilt.get_hardwareId()tilt→get_hardwareId()[tilt hardwareId]tilt.get_hardwareId()tilt.get_hardwareId()tilt.get_hardwareId()tilt.get_hardwareId()tilt→get_hardwareId()tilt.get_hardwareId()tilt.get_hardwareId()tilt.get_hardwareId()tilt.get_hardwareId()

Returns the unique hardware identifier of the tilt sensor in the form SERIAL.FUNCTIONID.

js
function get_hardwareId()
cpp
string get_hardwareId()
m
-(NSString*) hardwareId
vb
function get_hardwareId() As String
cs
string get_hardwareId()
java
String get_hardwareId()
py
get_hardwareId()
php
function get_hardwareId()
ts
async get_hardwareId(): Promise<string>
es
async get_hardwareId()
dnp
string get_hardwareId()
cp
string get_hardwareId()

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the tilt sensor (for example RELAYLO1-123456.relay1).

Returns :

a string that uniquely identifies the tilt sensor (ex: RELAYLO1-123456.relay1)

On failure, throws an exception or returns YTilt.HARDWAREID_INVALID.

tilt→get_highestValue()
tilt→highestValue()
tilt.get_highestValue()tilt→get_highestValue()[tilt highestValue]tilt.get_highestValue()tilt.get_highestValue()tilt.get_highestValue()tilt.get_highestValue()tilt.get_highestValue()tilt.get_highestValue()tilt→get_highestValue()tilt.get_highestValue()tilt.get_highestValue()tilt.get_highestValue()tilt.get_highestValue()YTilt get_highestValue

Returns the maximal value observed for the inclination since the device was started.

js
function get_highestValue()
cpp
double get_highestValue()
m
-(double) highestValue
pas
double get_highestValue(): double
vb
function get_highestValue() As Double
cs
double get_highestValue()
java
double get_highestValue()
uwp
async Task<double> get_highestValue()
py
get_highestValue()
php
function get_highestValue()
ts
async get_highestValue(): Promise<number>
es
async get_highestValue()
dnp
double get_highestValue()
cp
double get_highestValue()
cmd
YTilt target get_highestValue

Can be reset to an arbitrary value thanks to set_highestValue().

Returns :

a floating point number corresponding to the maximal value observed for the inclination since the device was started

On failure, throws an exception or returns YTilt.HIGHESTVALUE_INVALID.

tilt→get_logFrequency()
tilt→logFrequency()
tilt.get_logFrequency()tilt→get_logFrequency()[tilt logFrequency]tilt.get_logFrequency()tilt.get_logFrequency()tilt.get_logFrequency()tilt.get_logFrequency()tilt.get_logFrequency()tilt.get_logFrequency()tilt→get_logFrequency()tilt.get_logFrequency()tilt.get_logFrequency()tilt.get_logFrequency()tilt.get_logFrequency()YTilt get_logFrequency

Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

js
function get_logFrequency()
cpp
string get_logFrequency()
m
-(NSString*) logFrequency
pas
string get_logFrequency(): string
vb
function get_logFrequency() As String
cs
string get_logFrequency()
java
String get_logFrequency()
uwp
async Task<string> get_logFrequency()
py
get_logFrequency()
php
function get_logFrequency()
ts
async get_logFrequency(): Promise<string>
es
async get_logFrequency()
dnp
string get_logFrequency()
cp
string get_logFrequency()
cmd
YTilt target get_logFrequency

Returns :

a string corresponding to the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory

On failure, throws an exception or returns YTilt.LOGFREQUENCY_INVALID.

tilt→get_logicalName()
tilt→logicalName()
tilt.get_logicalName()tilt→get_logicalName()[tilt logicalName]tilt.get_logicalName()tilt.get_logicalName()tilt.get_logicalName()tilt.get_logicalName()tilt.get_logicalName()tilt.get_logicalName()tilt→get_logicalName()tilt.get_logicalName()tilt.get_logicalName()tilt.get_logicalName()tilt.get_logicalName()YTilt get_logicalName

Returns the logical name of the tilt sensor.

js
function get_logicalName()
cpp
string get_logicalName()
m
-(NSString*) logicalName
pas
string get_logicalName(): string
vb
function get_logicalName() As String
cs
string get_logicalName()
java
String get_logicalName()
uwp
async Task<string> get_logicalName()
py
get_logicalName()
php
function get_logicalName()
ts
async get_logicalName(): Promise<string>
es
async get_logicalName()
dnp
string get_logicalName()
cp
string get_logicalName()
cmd
YTilt target get_logicalName

Returns :

a string corresponding to the logical name of the tilt sensor.

On failure, throws an exception or returns YTilt.LOGICALNAME_INVALID.

tilt→get_lowestValue()
tilt→lowestValue()
tilt.get_lowestValue()tilt→get_lowestValue()[tilt lowestValue]tilt.get_lowestValue()tilt.get_lowestValue()tilt.get_lowestValue()tilt.get_lowestValue()tilt.get_lowestValue()tilt.get_lowestValue()tilt→get_lowestValue()tilt.get_lowestValue()tilt.get_lowestValue()tilt.get_lowestValue()tilt.get_lowestValue()YTilt get_lowestValue

Returns the minimal value observed for the inclination since the device was started.

js
function get_lowestValue()
cpp
double get_lowestValue()
m
-(double) lowestValue
pas
double get_lowestValue(): double
vb
function get_lowestValue() As Double
cs
double get_lowestValue()
java
double get_lowestValue()
uwp
async Task<double> get_lowestValue()
py
get_lowestValue()
php
function get_lowestValue()
ts
async get_lowestValue(): Promise<number>
es
async get_lowestValue()
dnp
double get_lowestValue()
cp
double get_lowestValue()
cmd
YTilt target get_lowestValue

Can be reset to an arbitrary value thanks to set_lowestValue().

Returns :

a floating point number corresponding to the minimal value observed for the inclination since the device was started

On failure, throws an exception or returns YTilt.LOWESTVALUE_INVALID.

tilt→get_module()
tilt→module()
tilt.get_module()tilt→get_module()[tilt module]tilt.get_module()tilt.get_module()tilt.get_module()tilt.get_module()tilt.get_module()tilt→get_module()tilt.get_module()tilt.get_module()tilt.get_module()tilt.get_module()

Gets the YModule object for the device on which the function is located.

js
function get_module()
cpp
YModule * get_module()
m
-(YModule*) module
pas
TYModule get_module(): TYModule
vb
function get_module() As YModule
cs
YModule get_module()
java
YModule get_module()
py
get_module()
php
function get_module()
ts
async get_module(): Promise<YModule>
es
async get_module()
dnp
YModuleProxy get_module()
cp
YModuleProxy * get_module()

If the function cannot be located on any module, the returned instance of YModule is not shown as on-line.

Returns :

an instance of YModule

tilt→get_module_async()
tilt→module_async()
tilt.get_module_async()

Gets the YModule object for the device on which the function is located (asynchronous version).

js
function get_module_async(callback, context)

If the function cannot be located on any module, the returned YModule object does not show as on-line.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking Firefox JavaScript VM that does not implement context switching during blocking I/O calls. See the documentation section on asynchronous JavasSript calls for more details.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the requested YModule object
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

tilt→get_recordedData()
tilt→recordedData()
tilt.get_recordedData()tilt→get_recordedData()[tilt recordedData: ]tilt.get_recordedData()tilt.get_recordedData()tilt.get_recordedData()tilt.get_recordedData()tilt.get_recordedData()tilt.get_recordedData()tilt→get_recordedData()tilt.get_recordedData()tilt.get_recordedData()tilt.get_recordedData()tilt.get_recordedData()YTilt get_recordedData

Retrieves a YDataSet object holding historical data for this sensor, for a specified time interval.

js
function get_recordedData(startTime, endTime)
cpp
YDataSet get_recordedData(double startTime, double endTime)
m
-(YDataSet*) recordedData: (double) startTime
  : (double) endTime
pas
TYDataSet get_recordedData(startTime: double, endTime: double): TYDataSet
vb
function get_recordedData(ByVal startTime As Double,
  ByVal endTime As Double) As YDataSet
cs
YDataSet get_recordedData(double startTime, double endTime)
java
YDataSet get_recordedData(double startTime, double endTime)
uwp
async Task<YDataSet> get_recordedData(double startTime,
  double endTime)
py
get_recordedData(startTime, endTime)
php
function get_recordedData($startTime, $endTime)
ts
async get_recordedData(startTime: number, endTime: number): Promise<YDataSet>
es
async get_recordedData(startTime, endTime)
dnp
YDataSetProxy get_recordedData(double startTime,
  double endTime)
cp
YDataSetProxy* get_recordedData(double startTime,
  double endTime)
cmd
YTilt target get_recordedData startTime endTime

The measures will be retrieved from the data logger, which must have been turned on at the desired time. See the documentation of the YDataSet class for information on how to get an overview of the recorded data, and how to load progressively a large set of measures from the data logger.

This function only works if the device uses a recent firmware, as YDataSet objects are not supported by firmwares older than version 13000.

Parameters :

startTimethe start of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without initial limit.
endTimethe end of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without ending limit.

Returns :

an instance of YDataSet, providing access to historical data. Past measures can be loaded progressively using methods from the YDataSet object.

tilt→get_reportFrequency()
tilt→reportFrequency()
tilt.get_reportFrequency()tilt→get_reportFrequency()[tilt reportFrequency]tilt.get_reportFrequency()tilt.get_reportFrequency()tilt.get_reportFrequency()tilt.get_reportFrequency()tilt.get_reportFrequency()tilt.get_reportFrequency()tilt→get_reportFrequency()tilt.get_reportFrequency()tilt.get_reportFrequency()tilt.get_reportFrequency()tilt.get_reportFrequency()YTilt get_reportFrequency

Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

js
function get_reportFrequency()
cpp
string get_reportFrequency()
m
-(NSString*) reportFrequency
pas
string get_reportFrequency(): string
vb
function get_reportFrequency() As String
cs
string get_reportFrequency()
java
String get_reportFrequency()
uwp
async Task<string> get_reportFrequency()
py
get_reportFrequency()
php
function get_reportFrequency()
ts
async get_reportFrequency(): Promise<string>
es
async get_reportFrequency()
dnp
string get_reportFrequency()
cp
string get_reportFrequency()
cmd
YTilt target get_reportFrequency

Returns :

a string corresponding to the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function

On failure, throws an exception or returns YTilt.REPORTFREQUENCY_INVALID.

tilt→get_resolution()
tilt→resolution()
tilt.get_resolution()tilt→get_resolution()[tilt resolution]tilt.get_resolution()tilt.get_resolution()tilt.get_resolution()tilt.get_resolution()tilt.get_resolution()tilt.get_resolution()tilt→get_resolution()tilt.get_resolution()tilt.get_resolution()tilt.get_resolution()tilt.get_resolution()YTilt get_resolution

Returns the resolution of the measured values.

js
function get_resolution()
cpp
double get_resolution()
m
-(double) resolution
pas
double get_resolution(): double
vb
function get_resolution() As Double
cs
double get_resolution()
java
double get_resolution()
uwp
async Task<double> get_resolution()
py
get_resolution()
php
function get_resolution()
ts
async get_resolution(): Promise<number>
es
async get_resolution()
dnp
double get_resolution()
cp
double get_resolution()
cmd
YTilt target get_resolution

The resolution corresponds to the numerical precision of the measures, which is not always the same as the actual precision of the sensor. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

a floating point number corresponding to the resolution of the measured values

On failure, throws an exception or returns YTilt.RESOLUTION_INVALID.

tilt→get_sensorState()
tilt→sensorState()
tilt.get_sensorState()tilt→get_sensorState()[tilt sensorState]tilt.get_sensorState()tilt.get_sensorState()tilt.get_sensorState()tilt.get_sensorState()tilt.get_sensorState()tilt.get_sensorState()tilt→get_sensorState()tilt.get_sensorState()tilt.get_sensorState()tilt.get_sensorState()tilt.get_sensorState()YTilt get_sensorState

Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.

js
function get_sensorState()
cpp
int get_sensorState()
m
-(int) sensorState
pas
LongInt get_sensorState(): LongInt
vb
function get_sensorState() As Integer
cs
int get_sensorState()
java
int get_sensorState()
uwp
async Task<int> get_sensorState()
py
get_sensorState()
php
function get_sensorState()
ts
async get_sensorState(): Promise<number>
es
async get_sensorState()
dnp
int get_sensorState()
cp
int get_sensorState()
cmd
YTilt target get_sensorState

Returns :

an integer corresponding to the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now

On failure, throws an exception or returns YTilt.SENSORSTATE_INVALID.

tilt→get_serialNumber()
tilt→serialNumber()
tilt.get_serialNumber()tilt→get_serialNumber()[tilt serialNumber]tilt.get_serialNumber()tilt.get_serialNumber()tilt.get_serialNumber()tilt.get_serialNumber()tilt.get_serialNumber()tilt.get_serialNumber()tilt→get_serialNumber()tilt.get_serialNumber()tilt.get_serialNumber()tilt.get_serialNumber()tilt.get_serialNumber()YTilt get_serialNumber

Returns the serial number of the module, as set by the factory.

js
function get_serialNumber()
cpp
string get_serialNumber()
m
-(NSString*) serialNumber
pas
string get_serialNumber(): string
vb
function get_serialNumber() As String
cs
string get_serialNumber()
java
String get_serialNumber()
uwp
async Task<string> get_serialNumber()
py
get_serialNumber()
php
function get_serialNumber()
ts
async get_serialNumber(): Promise<string>
es
async get_serialNumber()
dnp
string get_serialNumber()
cp
string get_serialNumber()
cmd
YTilt target get_serialNumber

Returns :

a string corresponding to the serial number of the module, as set by the factory.

On failure, throws an exception or returns YFunction.SERIALNUMBER_INVALID.

tilt→get_unit()
tilt→unit()
tilt.get_unit()tilt→get_unit()[tilt unit]tilt.get_unit()tilt.get_unit()tilt.get_unit()tilt.get_unit()tilt.get_unit()tilt.get_unit()tilt→get_unit()tilt.get_unit()tilt.get_unit()tilt.get_unit()tilt.get_unit()YTilt get_unit

Returns the measuring unit for the inclination.

js
function get_unit()
cpp
string get_unit()
m
-(NSString*) unit
pas
string get_unit(): string
vb
function get_unit() As String
cs
string get_unit()
java
String get_unit()
uwp
async Task<string> get_unit()
py
get_unit()
php
function get_unit()
ts
async get_unit(): Promise<string>
es
async get_unit()
dnp
string get_unit()
cp
string get_unit()
cmd
YTilt target get_unit

Returns :

a string corresponding to the measuring unit for the inclination

On failure, throws an exception or returns YTilt.UNIT_INVALID.

tilt→get_userData()
tilt→userData()
tilt.get_userData()tilt→get_userData()[tilt userData]tilt.get_userData()tilt.get_userData()tilt.get_userData()tilt.get_userData()tilt.get_userData()tilt→get_userData()tilt.get_userData()tilt.get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

js
function get_userData()
cpp
void * get_userData()
m
-(id) userData
pas
Tobject get_userData(): Tobject
vb
function get_userData() As Object
cs
object get_userData()
java
Object get_userData()
py
get_userData()
php
function get_userData()
ts
async get_userData(): Promise<object|null>
es
async get_userData()

This attribute is never touched directly by the API, and is at disposal of the caller to store a context.

Returns :

the object stored previously by the caller.

tilt→isOnline()tilt.isOnline()tilt→isOnline()[tilt isOnline]tilt.isOnline()tilt.isOnline()tilt.isOnline()tilt.isOnline()tilt.isOnline()tilt→isOnline()tilt.isOnline()tilt.isOnline()tilt.isOnline()tilt.isOnline()

Checks if the tilt sensor is currently reachable, without raising any error.

js
function isOnline()
cpp
bool isOnline()
m
-(BOOL) isOnline
pas
boolean isOnline(): boolean
vb
function isOnline() As Boolean
cs
bool isOnline()
java
boolean isOnline()
py
isOnline()
php
function isOnline()
ts
async isOnline(): Promise<boolean>
es
async isOnline()
dnp
bool isOnline()
cp
bool isOnline()

If there is a cached value for the tilt sensor in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the tilt sensor.

Returns :

true if the tilt sensor can be reached, and false otherwise

tilt→isOnline_async()tilt.isOnline_async()

Checks if the tilt sensor is currently reachable, without raising any error (asynchronous version).

js
function isOnline_async(callback, context)

If there is a cached value for the tilt sensor in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the requested function.

This asynchronous version exists only in Javascript. It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the boolean result
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

tilt→isReadOnly()tilt→isReadOnly()[tilt isReadOnly]tilt.isReadOnly()tilt.isReadOnly()tilt.isReadOnly()tilt.isReadOnly()tilt.isReadOnly()tilt.isReadOnly()tilt→isReadOnly()tilt.isReadOnly()tilt.isReadOnly()tilt.isReadOnly()tilt.isReadOnly()YTilt isReadOnly

Test if the function is readOnly.

cpp
bool isReadOnly()
m
-(bool) isReadOnly
pas
boolean isReadOnly(): boolean
vb
function isReadOnly() As Boolean
cs
bool isReadOnly()
java
boolean isReadOnly()
uwp
async Task<bool> isReadOnly()
py
isReadOnly()
php
function isReadOnly()
ts
async isReadOnly(): Promise<boolean>
es
async isReadOnly()
dnp
bool isReadOnly()
cp
bool isReadOnly()
cmd
YTilt target isReadOnly

Return true if the function is write protected or that the function is not available.

Returns :

true if the function is readOnly or not online.

tilt→isSensorReady()YTilt isSensorReady

Checks if the sensor is currently able to provide an up-to-date measure.

cmd
YTilt target isSensorReady

Returns false if the device is unreachable, or if the sensor does not have a current measure to transmit. No exception is raised if there is an error while trying to contact the device hosting $THEFUNCTION$.

Returns :

true if the sensor can provide an up-to-date measure, and false otherwise

tilt→load()tilt.load()tilt→load()[tilt load: ]tilt.load()tilt.load()tilt.load()tilt.load()tilt.load()tilt→load()tilt.load()tilt.load()

Preloads the tilt sensor cache with a specified validity duration.

js
function load(msValidity)
cpp
YRETCODE load(int msValidity)
m
-(YRETCODE) load: (u64) msValidity
pas
YRETCODE load(msValidity: u64): YRETCODE
vb
function load(ByVal msValidity As Long) As YRETCODE
cs
YRETCODE load(ulong msValidity)
java
int load(long msValidity)
py
load(msValidity)
php
function load($msValidity)
ts
async load(msValidity: number): Promise<number>
es
async load(msValidity)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

Parameters :

msValidityan integer corresponding to the validity attributed to the loaded function parameters, in milliseconds

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→loadAttribute()tilt.loadAttribute()tilt→loadAttribute()[tilt loadAttribute: ]tilt.loadAttribute()tilt.loadAttribute()tilt.loadAttribute()tilt.loadAttribute()tilt.loadAttribute()tilt.loadAttribute()tilt→loadAttribute()tilt.loadAttribute()tilt.loadAttribute()tilt.loadAttribute()tilt.loadAttribute()

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

js
function loadAttribute(attrName)
cpp
string loadAttribute(string attrName)
m
-(NSString*) loadAttribute: (NSString*) attrName
pas
string loadAttribute(attrName: string): string
vb
function loadAttribute(ByVal attrName As String) As String
cs
string loadAttribute(string attrName)
java
String loadAttribute(String attrName)
uwp
async Task<string> loadAttribute(string attrName)
py
loadAttribute(attrName)
php
function loadAttribute($attrName)
ts
async loadAttribute(attrName: string): Promise<string>
es
async loadAttribute(attrName)
dnp
string loadAttribute(string attrName)
cp
string loadAttribute(string attrName)

Parameters :

attrNamethe name of the requested attribute

Returns :

a string with the value of the the attribute

On failure, throws an exception or returns an empty string.

tilt→loadCalibrationPoints()tilt.loadCalibrationPoints()tilt→loadCalibrationPoints()[tilt loadCalibrationPoints: ]tilt.loadCalibrationPoints()tilt.loadCalibrationPoints()tilt.loadCalibrationPoints()tilt.loadCalibrationPoints()tilt.loadCalibrationPoints()tilt.loadCalibrationPoints()tilt→loadCalibrationPoints()tilt.loadCalibrationPoints()tilt.loadCalibrationPoints()YTilt loadCalibrationPoints

Retrieves error correction data points previously entered using the method calibrateFromPoints.

js
function loadCalibrationPoints(rawValues, refValues)
cpp
int loadCalibrationPoints(vector<double> rawValues,
  vector<double> refValues)
m
-(int) loadCalibrationPoints: (NSMutableArray*) rawValues
  : (NSMutableArray*) refValues
pas
LongInt loadCalibrationPoints(var rawValues: TDoubleArray,
  var refValues: TDoubleArray): LongInt
vb
procedure loadCalibrationPoints(ByVal rawValues As List(Of)
cs
int loadCalibrationPoints(List<double> rawValues,
  List<double> refValues)
java
int loadCalibrationPoints(ArrayList<Double> rawValues,
  ArrayList<Double> refValues)
uwp
async Task<int> loadCalibrationPoints(List<double> rawValues,
  List<double> refValues)
py
loadCalibrationPoints(rawValues, refValues)
php
function loadCalibrationPoints(&$rawValues, &$refValues)
ts
async loadCalibrationPoints(rawValues: number[], refValues: number[]): Promise<number>
es
async loadCalibrationPoints(rawValues, refValues)
cmd
YTilt target loadCalibrationPoints rawValues refValues

Parameters :

rawValuesarray of floating point numbers, that will be filled by the function with the raw sensor values for the correction points.
refValuesarray of floating point numbers, that will be filled by the function with the desired values for the correction points.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→load_async()tilt.load_async()

Preloads the tilt sensor cache with a specified validity duration (asynchronous version).

js
function load_async(msValidity, callback, context)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking the JavaScript virtual machine.

Parameters :

msValidityan integer corresponding to the validity of the loaded function parameters, in milliseconds
callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the error code (or YAPI.SUCCESS)
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

tilt→muteValueCallbacks()tilt.muteValueCallbacks()tilt→muteValueCallbacks()[tilt muteValueCallbacks]tilt.muteValueCallbacks()tilt.muteValueCallbacks()tilt.muteValueCallbacks()tilt.muteValueCallbacks()tilt.muteValueCallbacks()tilt.muteValueCallbacks()tilt→muteValueCallbacks()tilt.muteValueCallbacks()tilt.muteValueCallbacks()tilt.muteValueCallbacks()tilt.muteValueCallbacks()YTilt muteValueCallbacks

Disables the propagation of every new advertised value to the parent hub.

js
function muteValueCallbacks()
cpp
int muteValueCallbacks()
m
-(int) muteValueCallbacks
pas
LongInt muteValueCallbacks(): LongInt
vb
function muteValueCallbacks() As Integer
cs
int muteValueCallbacks()
java
int muteValueCallbacks()
uwp
async Task<int> muteValueCallbacks()
py
muteValueCallbacks()
php
function muteValueCallbacks()
ts
async muteValueCallbacks(): Promise<number>
es
async muteValueCallbacks()
dnp
int muteValueCallbacks()
cp
int muteValueCallbacks()
cmd
YTilt target muteValueCallbacks

You can use this function to save bandwidth and CPU on computers with limited resources, or to prevent unwanted invocations of the HTTP callback. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→nextTilt()tilt.nextTilt()tilt→nextTilt()[tilt nextTilt]tilt.nextTilt()tilt.nextTilt()tilt.nextTilt()tilt.nextTilt()tilt.nextTilt()tilt.nextTilt()tilt→nextTilt()tilt.nextTilt()tilt.nextTilt()

Continues the enumeration of tilt sensors started using yFirstTilt().

js
function nextTilt()
cpp
YTilt * nextTilt()
m
-(nullable YTilt*) nextTilt
pas
TYTilt nextTilt(): TYTilt
vb
function nextTilt() As YTilt
cs
YTilt nextTilt()
java
YTilt nextTilt()
uwp
YTilt nextTilt()
py
nextTilt()
php
function nextTilt()
ts
nextTilt(): YTilt | null
es
nextTilt()

Caution: You can't make any assumption about the returned tilt sensors order. If you want to find a specific a tilt sensor, use Tilt.findTilt() and a hardwareID or a logical name.

Returns :

a pointer to a YTilt object, corresponding to a tilt sensor currently online, or a null pointer if there are no more tilt sensors to enumerate.

tilt→registerTimedReportCallback()tilt.registerTimedReportCallback()tilt→registerTimedReportCallback()[tilt registerTimedReportCallback: ]tilt.registerTimedReportCallback()tilt.registerTimedReportCallback()tilt.registerTimedReportCallback()tilt.registerTimedReportCallback()tilt.registerTimedReportCallback()tilt.registerTimedReportCallback()tilt→registerTimedReportCallback()tilt.registerTimedReportCallback()tilt.registerTimedReportCallback()

Registers the callback function that is invoked on every periodic timed notification.

js
function registerTimedReportCallback(callback)
cpp
int registerTimedReportCallback(YTiltTimedReportCallback callback)
m
-(int) registerTimedReportCallback: (YTiltTimedReportCallback _Nullable) callback
pas
LongInt registerTimedReportCallback(callback: TYTiltTimedReportCallback): LongInt
vb
function registerTimedReportCallback(ByVal callback As YTiltTimedReportCallback) As Integer
cs
int registerTimedReportCallback(TimedReportCallback callback)
java
int registerTimedReportCallback(TimedReportCallback callback)
uwp
async Task<int> registerTimedReportCallback(TimedReportCallback callback)
py
registerTimedReportCallback(callback)
php
function registerTimedReportCallback($callback)
ts
async registerTimedReportCallback(callback: YTiltTimedReportCallback | null): Promise<number>
es
async registerTimedReportCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and an YMeasure object describing the new advertised value.

tilt→registerValueCallback()tilt.registerValueCallback()tilt→registerValueCallback()[tilt registerValueCallback: ]tilt.registerValueCallback()tilt.registerValueCallback()tilt.registerValueCallback()tilt.registerValueCallback()tilt.registerValueCallback()tilt.registerValueCallback()tilt→registerValueCallback()tilt.registerValueCallback()tilt.registerValueCallback()

Registers the callback function that is invoked on every change of advertised value.

js
function registerValueCallback(callback)
cpp
int registerValueCallback(YTiltValueCallback callback)
m
-(int) registerValueCallback: (YTiltValueCallback _Nullable) callback
pas
LongInt registerValueCallback(callback: TYTiltValueCallback): LongInt
vb
function registerValueCallback(ByVal callback As YTiltValueCallback) As Integer
cs
int registerValueCallback(ValueCallback callback)
java
int registerValueCallback(UpdateCallback callback)
uwp
async Task<int> registerValueCallback(ValueCallback callback)
py
registerValueCallback(callback)
php
function registerValueCallback($callback)
ts
async registerValueCallback(callback: YTiltValueCallback | null): Promise<number>
es
async registerValueCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and the character string describing the new advertised value.

tilt→restoreZeroCalibration()tilt.restoreZeroCalibration()tilt→restoreZeroCalibration()[tilt restoreZeroCalibration]tilt.restoreZeroCalibration()tilt.restoreZeroCalibration()tilt.restoreZeroCalibration()tilt.restoreZeroCalibration()tilt.restoreZeroCalibration()tilt.restoreZeroCalibration()tilt→restoreZeroCalibration()tilt.restoreZeroCalibration()tilt.restoreZeroCalibration()tilt.restoreZeroCalibration()tilt.restoreZeroCalibration()YTilt restoreZeroCalibration

Cancels any previous zero calibration for the tilt measurement (Yocto-Inclinometer only).

js
function restoreZeroCalibration()
cpp
int restoreZeroCalibration()
m
-(int) restoreZeroCalibration
pas
LongInt restoreZeroCalibration(): LongInt
vb
function restoreZeroCalibration() As Integer
cs
int restoreZeroCalibration()
java
int restoreZeroCalibration()
uwp
async Task<int> restoreZeroCalibration()
py
restoreZeroCalibration()
php
function restoreZeroCalibration()
ts
async restoreZeroCalibration(): Promise<number>
es
async restoreZeroCalibration()
dnp
int restoreZeroCalibration()
cp
int restoreZeroCalibration()
cmd
YTilt target restoreZeroCalibration

This function restores the factory zero calibration.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→set_advMode()
tilt→setAdvMode()
tilt.set_advMode()tilt→set_advMode()[tilt setAdvMode: ]tilt.set_advMode()tilt.set_advMode()tilt.set_advMode()tilt.set_advMode()tilt.set_advMode()tilt.set_advMode()tilt→set_advMode()tilt.set_advMode()tilt.set_advMode()tilt.set_advMode()tilt.set_advMode()YTilt set_advMode

Changes the measuring mode used for the advertised value pushed to the parent hub.

js
function set_advMode(newval)
cpp
int set_advMode(Y_ADVMODE_enum newval)
m
-(int) setAdvMode: (Y_ADVMODE_enum) newval
pas
integer set_advMode(newval: Integer): integer
vb
function set_advMode(ByVal newval As Integer) As Integer
cs
int set_advMode(int newval)
java
int set_advMode(int newval)
uwp
async Task<int> set_advMode(int newval)
py
set_advMode(newval)
php
function set_advMode($newval)
ts
async set_advMode(newval: YSensor_AdvMode): Promise<number>
es
async set_advMode(newval)
dnp
int set_advMode(int newval)
cp
int set_advMode(int newval)
cmd
YTilt target set_advMode newval

Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala value among YTilt.ADVMODE_IMMEDIATE, YTilt.ADVMODE_PERIOD_AVG, YTilt.ADVMODE_PERIOD_MIN and YTilt.ADVMODE_PERIOD_MAX corresponding to the measuring mode used for the advertised value pushed to the parent hub

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→set_bandwidth()
tilt→setBandwidth()
tilt.set_bandwidth()tilt→set_bandwidth()[tilt setBandwidth: ]tilt.set_bandwidth()tilt.set_bandwidth()tilt.set_bandwidth()tilt.set_bandwidth()tilt.set_bandwidth()tilt.set_bandwidth()tilt→set_bandwidth()tilt.set_bandwidth()tilt.set_bandwidth()tilt.set_bandwidth()tilt.set_bandwidth()YTilt set_bandwidth

Changes the measure update frequency, measured in Hz.

js
function set_bandwidth(newval)
cpp
int set_bandwidth(int newval)
m
-(int) setBandwidth: (int) newval
pas
integer set_bandwidth(newval: LongInt): integer
vb
function set_bandwidth(ByVal newval As Integer) As Integer
cs
int set_bandwidth(int newval)
java
int set_bandwidth(int newval)
uwp
async Task<int> set_bandwidth(int newval)
py
set_bandwidth(newval)
php
function set_bandwidth($newval)
ts
async set_bandwidth(newval: number): Promise<number>
es
async set_bandwidth(newval)
dnp
int set_bandwidth(int newval)
cp
int set_bandwidth(int newval)
cmd
YTilt target set_bandwidth newval

When the frequency is lower, the device performs averaging. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvalan integer corresponding to the measure update frequency, measured in Hz

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→set_highestValue()
tilt→setHighestValue()
tilt.set_highestValue()tilt→set_highestValue()[tilt setHighestValue: ]tilt.set_highestValue()tilt.set_highestValue()tilt.set_highestValue()tilt.set_highestValue()tilt.set_highestValue()tilt.set_highestValue()tilt→set_highestValue()tilt.set_highestValue()tilt.set_highestValue()tilt.set_highestValue()tilt.set_highestValue()YTilt set_highestValue

Changes the recorded maximal value observed.

js
function set_highestValue(newval)
cpp
int set_highestValue(double newval)
m
-(int) setHighestValue: (double) newval
pas
integer set_highestValue(newval: double): integer
vb
function set_highestValue(ByVal newval As Double) As Integer
cs
int set_highestValue(double newval)
java
int set_highestValue(double newval)
uwp
async Task<int> set_highestValue(double newval)
py
set_highestValue(newval)
php
function set_highestValue($newval)
ts
async set_highestValue(newval: number): Promise<number>
es
async set_highestValue(newval)
dnp
int set_highestValue(double newval)
cp
int set_highestValue(double newval)
cmd
YTilt target set_highestValue newval

Can be used to reset the value returned by get_lowestValue().

Parameters :

newvala floating point number corresponding to the recorded maximal value observed

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→set_logFrequency()
tilt→setLogFrequency()
tilt.set_logFrequency()tilt→set_logFrequency()[tilt setLogFrequency: ]tilt.set_logFrequency()tilt.set_logFrequency()tilt.set_logFrequency()tilt.set_logFrequency()tilt.set_logFrequency()tilt.set_logFrequency()tilt→set_logFrequency()tilt.set_logFrequency()tilt.set_logFrequency()tilt.set_logFrequency()tilt.set_logFrequency()YTilt set_logFrequency

Changes the datalogger recording frequency for this function.

js
function set_logFrequency(newval)
cpp
int set_logFrequency(string newval)
m
-(int) setLogFrequency: (NSString*) newval
pas
integer set_logFrequency(newval: string): integer
vb
function set_logFrequency(ByVal newval As String) As Integer
cs
int set_logFrequency(string newval)
java
int set_logFrequency(String newval)
uwp
async Task<int> set_logFrequency(string newval)
py
set_logFrequency(newval)
php
function set_logFrequency($newval)
ts
async set_logFrequency(newval: string): Promise<number>
es
async set_logFrequency(newval)
dnp
int set_logFrequency(string newval)
cp
int set_logFrequency(string newval)
cmd
YTilt target set_logFrequency newval

The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (eg. "4/h"). To disable recording for this function, use the value "OFF". Note that setting the datalogger recording frequency to a greater value than the sensor native sampling frequency is useless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the datalogger recording frequency for this function

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→set_logicalName()
tilt→setLogicalName()
tilt.set_logicalName()tilt→set_logicalName()[tilt setLogicalName: ]tilt.set_logicalName()tilt.set_logicalName()tilt.set_logicalName()tilt.set_logicalName()tilt.set_logicalName()tilt.set_logicalName()tilt→set_logicalName()tilt.set_logicalName()tilt.set_logicalName()tilt.set_logicalName()tilt.set_logicalName()YTilt set_logicalName

Changes the logical name of the tilt sensor.

js
function set_logicalName(newval)
cpp
int set_logicalName(string newval)
m
-(int) setLogicalName: (NSString*) newval
pas
integer set_logicalName(newval: string): integer
vb
function set_logicalName(ByVal newval As String) As Integer
cs
int set_logicalName(string newval)
java
int set_logicalName(String newval)
uwp
async Task<int> set_logicalName(string newval)
py
set_logicalName(newval)
php
function set_logicalName($newval)
ts
async set_logicalName(newval: string): Promise<number>
es
async set_logicalName(newval)
dnp
int set_logicalName(string newval)
cp
int set_logicalName(string newval)
cmd
YTilt target set_logicalName newval

You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the logical name of the tilt sensor.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→set_lowestValue()
tilt→setLowestValue()
tilt.set_lowestValue()tilt→set_lowestValue()[tilt setLowestValue: ]tilt.set_lowestValue()tilt.set_lowestValue()tilt.set_lowestValue()tilt.set_lowestValue()tilt.set_lowestValue()tilt.set_lowestValue()tilt→set_lowestValue()tilt.set_lowestValue()tilt.set_lowestValue()tilt.set_lowestValue()tilt.set_lowestValue()YTilt set_lowestValue

Changes the recorded minimal value observed.

js
function set_lowestValue(newval)
cpp
int set_lowestValue(double newval)
m
-(int) setLowestValue: (double) newval
pas
integer set_lowestValue(newval: double): integer
vb
function set_lowestValue(ByVal newval As Double) As Integer
cs
int set_lowestValue(double newval)
java
int set_lowestValue(double newval)
uwp
async Task<int> set_lowestValue(double newval)
py
set_lowestValue(newval)
php
function set_lowestValue($newval)
ts
async set_lowestValue(newval: number): Promise<number>
es
async set_lowestValue(newval)
dnp
int set_lowestValue(double newval)
cp
int set_lowestValue(double newval)
cmd
YTilt target set_lowestValue newval

Can be used to reset the value returned by get_lowestValue().

Parameters :

newvala floating point number corresponding to the recorded minimal value observed

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→set_reportFrequency()
tilt→setReportFrequency()
tilt.set_reportFrequency()tilt→set_reportFrequency()[tilt setReportFrequency: ]tilt.set_reportFrequency()tilt.set_reportFrequency()tilt.set_reportFrequency()tilt.set_reportFrequency()tilt.set_reportFrequency()tilt.set_reportFrequency()tilt→set_reportFrequency()tilt.set_reportFrequency()tilt.set_reportFrequency()tilt.set_reportFrequency()tilt.set_reportFrequency()YTilt set_reportFrequency

Changes the timed value notification frequency for this function.

js
function set_reportFrequency(newval)
cpp
int set_reportFrequency(string newval)
m
-(int) setReportFrequency: (NSString*) newval
pas
integer set_reportFrequency(newval: string): integer
vb
function set_reportFrequency(ByVal newval As String) As Integer
cs
int set_reportFrequency(string newval)
java
int set_reportFrequency(String newval)
uwp
async Task<int> set_reportFrequency(string newval)
py
set_reportFrequency(newval)
php
function set_reportFrequency($newval)
ts
async set_reportFrequency(newval: string): Promise<number>
es
async set_reportFrequency(newval)
dnp
int set_reportFrequency(string newval)
cp
int set_reportFrequency(string newval)
cmd
YTilt target set_reportFrequency newval

The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (e.g. "4/h"). To disable timed value notifications for this function, use the value "OFF". Note that setting the timed value notification frequency to a greater value than the sensor native sampling frequency is unless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the timed value notification frequency for this function

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→set_resolution()
tilt→setResolution()
tilt.set_resolution()tilt→set_resolution()[tilt setResolution: ]tilt.set_resolution()tilt.set_resolution()tilt.set_resolution()tilt.set_resolution()tilt.set_resolution()tilt.set_resolution()tilt→set_resolution()tilt.set_resolution()tilt.set_resolution()tilt.set_resolution()tilt.set_resolution()YTilt set_resolution

Changes the resolution of the measured physical values.

js
function set_resolution(newval)
cpp
int set_resolution(double newval)
m
-(int) setResolution: (double) newval
pas
integer set_resolution(newval: double): integer
vb
function set_resolution(ByVal newval As Double) As Integer
cs
int set_resolution(double newval)
java
int set_resolution(double newval)
uwp
async Task<int> set_resolution(double newval)
py
set_resolution(newval)
php
function set_resolution($newval)
ts
async set_resolution(newval: number): Promise<number>
es
async set_resolution(newval)
dnp
int set_resolution(double newval)
cp
int set_resolution(double newval)
cmd
YTilt target set_resolution newval

The resolution corresponds to the numerical precision when displaying value. It does not change the precision of the measure itself. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala floating point number corresponding to the resolution of the measured physical values

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→set_userData()
tilt→setUserData()
tilt.set_userData()tilt→set_userData()[tilt setUserData: ]tilt.set_userData()tilt.set_userData()tilt.set_userData()tilt.set_userData()tilt.set_userData()tilt→set_userData()tilt.set_userData()tilt.set_userData()

Stores a user context provided as argument in the userData attribute of the function.

js
function set_userData(data)
cpp
void set_userData(void * data)
m
-(void) setUserData: (id) data
pas
set_userData(data: Tobject)
vb
procedure set_userData(ByVal data As Object)
cs
void set_userData(object data)
java
void set_userData(Object data)
py
set_userData(data)
php
function set_userData($data)
ts
async set_userData(data: object|null): Promise<void>
es
async set_userData(data)

This attribute is never touched by the API, and is at disposal of the caller to store a context.

Parameters :

dataany kind of object to be stored

tilt→startDataLogger()tilt.startDataLogger()tilt→startDataLogger()[tilt startDataLogger]tilt.startDataLogger()tilt.startDataLogger()tilt.startDataLogger()tilt.startDataLogger()tilt.startDataLogger()tilt.startDataLogger()tilt→startDataLogger()tilt.startDataLogger()tilt.startDataLogger()tilt.startDataLogger()tilt.startDataLogger()YTilt startDataLogger

Starts the data logger on the device.

js
function startDataLogger()
cpp
int startDataLogger()
m
-(int) startDataLogger
pas
LongInt startDataLogger(): LongInt
vb
function startDataLogger() As Integer
cs
int startDataLogger()
java
int startDataLogger()
uwp
async Task<int> startDataLogger()
py
startDataLogger()
php
function startDataLogger()
ts
async startDataLogger(): Promise<number>
es
async startDataLogger()
dnp
int startDataLogger()
cp
int startDataLogger()
cmd
YTilt target startDataLogger

Note that the data logger will only save the measures on this sensor if the logFrequency is not set to "OFF".

Returns :

YAPI.SUCCESS if the call succeeds.

tilt→stopDataLogger()tilt.stopDataLogger()tilt→stopDataLogger()[tilt stopDataLogger]tilt.stopDataLogger()tilt.stopDataLogger()tilt.stopDataLogger()tilt.stopDataLogger()tilt.stopDataLogger()tilt.stopDataLogger()tilt→stopDataLogger()tilt.stopDataLogger()tilt.stopDataLogger()tilt.stopDataLogger()tilt.stopDataLogger()YTilt stopDataLogger

Stops the datalogger on the device.

js
function stopDataLogger()
cpp
int stopDataLogger()
m
-(int) stopDataLogger
pas
LongInt stopDataLogger(): LongInt
vb
function stopDataLogger() As Integer
cs
int stopDataLogger()
java
int stopDataLogger()
uwp
async Task<int> stopDataLogger()
py
stopDataLogger()
php
function stopDataLogger()
ts
async stopDataLogger(): Promise<number>
es
async stopDataLogger()
dnp
int stopDataLogger()
cp
int stopDataLogger()
cmd
YTilt target stopDataLogger

Returns :

YAPI.SUCCESS if the call succeeds.

tilt→unmuteValueCallbacks()tilt.unmuteValueCallbacks()tilt→unmuteValueCallbacks()[tilt unmuteValueCallbacks]tilt.unmuteValueCallbacks()tilt.unmuteValueCallbacks()tilt.unmuteValueCallbacks()tilt.unmuteValueCallbacks()tilt.unmuteValueCallbacks()tilt.unmuteValueCallbacks()tilt→unmuteValueCallbacks()tilt.unmuteValueCallbacks()tilt.unmuteValueCallbacks()tilt.unmuteValueCallbacks()tilt.unmuteValueCallbacks()YTilt unmuteValueCallbacks

Re-enables the propagation of every new advertised value to the parent hub.

js
function unmuteValueCallbacks()
cpp
int unmuteValueCallbacks()
m
-(int) unmuteValueCallbacks
pas
LongInt unmuteValueCallbacks(): LongInt
vb
function unmuteValueCallbacks() As Integer
cs
int unmuteValueCallbacks()
java
int unmuteValueCallbacks()
uwp
async Task<int> unmuteValueCallbacks()
py
unmuteValueCallbacks()
php
function unmuteValueCallbacks()
ts
async unmuteValueCallbacks(): Promise<number>
es
async unmuteValueCallbacks()
dnp
int unmuteValueCallbacks()
cp
int unmuteValueCallbacks()
cmd
YTilt target unmuteValueCallbacks

This function reverts the effect of a previous call to muteValueCallbacks(). Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

tilt→wait_async()tilt.wait_async()tilt.wait_async()tilt.wait_async()

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

js
function wait_async(callback, context)
ts
wait_async(callback: Function, context: object)
es
wait_async(callback, context)

The callback function can therefore freely issue synchronous or asynchronous commands, without risking to block the JavaScript VM.

Parameters :

callbackcallback function that is invoked when all pending commands on the module are completed. The callback function receives two arguments: the caller-specific context object and the receiving function object.
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing.

24.7. Class YCompass

Compass function control interface, available for instance in the Yocto-3D-V2

The YCompass class allows you to read and configure Yoctopuce compass functions. It inherits from YSensor class the core functions to read measurements, to register callback functions, and to access the autonomous datalogger.

In order to use the functions described here, you should include:

es
in HTML: <script src="../../lib/yocto_compass.js"></script>
in node.js: require('yoctolib-es2017/yocto_compass.js');
js
<script type='text/javascript' src='yocto_compass.js'></script>
cpp
#include "yocto_compass.h"
m
#import "yocto_compass.h"
pas
uses yocto_compass;
vb
yocto_compass.vb
cs
yocto_compass.cs
java
import com.yoctopuce.YoctoAPI.YCompass;
uwp
import com.yoctopuce.YoctoAPI.YCompass;
py
from yocto_compass import *
php
require_once('yocto_compass.php');
ts
in HTML: import { YCompass } from '../../dist/esm/yocto_compass.js';
in Node.js: import { YCompass } from 'yoctolib-cjs/yocto_compass.js';
dnp
import YoctoProxyAPI.YCompassProxy
cp
#include "yocto_compass_proxy.h"
vi
YCompass.vi
ml
import YoctoProxyAPI.YCompassProxy
Global functions
YCompass.FindCompass(func)

Retrieves a compass function for a given identifier.

YCompass.FindCompassInContext(yctx, func)

Retrieves a compass function for a given identifier in a YAPI context.

YCompass.FirstCompass()

Starts the enumeration of compass functions currently accessible.

YCompass.FirstCompassInContext(yctx)

Starts the enumeration of compass functions currently accessible.

YCompass.GetSimilarFunctions()

Enumerates all functions of type Compass available on the devices currently reachable by the library, and returns their unique hardware ID.

YCompass properties
compass→AdvMode [writable]

Measuring mode used for the advertised value pushed to the parent hub.

compass→AdvertisedValue [read-only]

Short string representing the current state of the function.

compass→Bandwidth [writable]

Measure update frequency, measured in Hz.

compass→FriendlyName [read-only]

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

compass→FunctionId [read-only]

Hardware identifier of the sensor, without reference to the module.

compass→HardwareId [read-only]

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

compass→IsOnline [read-only]

Checks if the function is currently reachable.

compass→LogFrequency [writable]

Datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

compass→LogicalName [writable]

Logical name of the function.

compass→ReportFrequency [writable]

Timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

compass→Resolution [writable]

Resolution of the measured values.

compass→SerialNumber [read-only]

Serial number of the module, as set by the factory.

YCompass methods
compass→calibrateFromPoints(rawValues, refValues)

Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.

compass→clearCache()

Invalidates the cache.

compass→describe()

Returns a short text that describes unambiguously the instance of the compass function in the form TYPE(NAME)=SERIAL.FUNCTIONID.

compass→get_advMode()

Returns the measuring mode used for the advertised value pushed to the parent hub.

compass→get_advertisedValue()

Returns the current value of the compass function (no more than 6 characters).

compass→get_bandwidth()

Returns the measure update frequency, measured in Hz.

compass→get_currentRawValue()

Returns the uncalibrated, unrounded raw value returned by the sensor, in degrees, as a floating point number.

compass→get_currentValue()

Returns the current value of the relative bearing, in degrees, as a floating point number.

compass→get_dataLogger()

Returns the YDatalogger object of the device hosting the sensor.

compass→get_errorMessage()

Returns the error message of the latest error with the compass function.

compass→get_errorType()

Returns the numerical error code of the latest error with the compass function.

compass→get_friendlyName()

Returns a global identifier of the compass function in the format MODULE_NAME.FUNCTION_NAME.

compass→get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

compass→get_functionId()

Returns the hardware identifier of the compass function, without reference to the module.

compass→get_hardwareId()

Returns the unique hardware identifier of the compass function in the form SERIAL.FUNCTIONID.

compass→get_highestValue()

Returns the maximal value observed for the relative bearing since the device was started.

compass→get_logFrequency()

Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

compass→get_logicalName()

Returns the logical name of the compass function.

compass→get_lowestValue()

Returns the minimal value observed for the relative bearing since the device was started.

compass→get_magneticHeading()

Returns the magnetic heading, regardless of the configured bearing.

compass→get_module()

Gets the YModule object for the device on which the function is located.

compass→get_module_async(callback, context)

Gets the YModule object for the device on which the function is located (asynchronous version).

compass→get_recordedData(startTime, endTime)

Retrieves a YDataSet object holding historical data for this sensor, for a specified time interval.

compass→get_reportFrequency()

Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

compass→get_resolution()

Returns the resolution of the measured values.

compass→get_sensorState()

Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.

compass→get_serialNumber()

Returns the serial number of the module, as set by the factory.

compass→get_unit()

Returns the measuring unit for the relative bearing.

compass→get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

compass→isOnline()

Checks if the compass function is currently reachable, without raising any error.

compass→isOnline_async(callback, context)

Checks if the compass function is currently reachable, without raising any error (asynchronous version).

compass→isReadOnly()

Test if the function is readOnly.

compass→isSensorReady()

Checks if the sensor is currently able to provide an up-to-date measure.

compass→load(msValidity)

Preloads the compass function cache with a specified validity duration.

compass→loadAttribute(attrName)

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

compass→loadCalibrationPoints(rawValues, refValues)

Retrieves error correction data points previously entered using the method calibrateFromPoints.

compass→load_async(msValidity, callback, context)

Preloads the compass function cache with a specified validity duration (asynchronous version).

compass→muteValueCallbacks()

Disables the propagation of every new advertised value to the parent hub.

compass→nextCompass()

Continues the enumeration of compass functions started using yFirstCompass().

compass→registerTimedReportCallback(callback)

Registers the callback function that is invoked on every periodic timed notification.

compass→registerValueCallback(callback)

Registers the callback function that is invoked on every change of advertised value.

compass→set_advMode(newval)

Changes the measuring mode used for the advertised value pushed to the parent hub.

compass→set_bandwidth(newval)

Changes the measure update frequency, measured in Hz.

compass→set_highestValue(newval)

Changes the recorded maximal value observed.

compass→set_logFrequency(newval)

Changes the datalogger recording frequency for this function.

compass→set_logicalName(newval)

Changes the logical name of the compass function.

compass→set_lowestValue(newval)

Changes the recorded minimal value observed.

compass→set_reportFrequency(newval)

Changes the timed value notification frequency for this function.

compass→set_resolution(newval)

Changes the resolution of the measured physical values.

compass→set_userData(data)

Stores a user context provided as argument in the userData attribute of the function.

compass→startDataLogger()

Starts the data logger on the device.

compass→stopDataLogger()

Stops the datalogger on the device.

compass→unmuteValueCallbacks()

Re-enables the propagation of every new advertised value to the parent hub.

compass→wait_async(callback, context)

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

YCompass.FindCompass()
YCompass.FindCompass()
yFindCompass()YCompass::FindCompass()[YCompass FindCompass: ]yFindCompass()YCompass.FindCompass()YCompass.FindCompass()YCompass.FindCompass()YCompass.FindCompass()YCompass.FindCompass()YCompass::FindCompass()YCompass.FindCompass()YCompass.FindCompass()YCompass.FindCompass()YCompass.FindCompass()

Retrieves a compass function for a given identifier.

js
function yFindCompass(func)
cpp
YCompass* FindCompass(string func)
m
+(YCompass*) FindCompass: (NSString*) func
pas
TYCompass yFindCompass(func: string): TYCompass
vb
function FindCompass(ByVal func As String) As YCompass
cs
static YCompass FindCompass(string func)
java
static YCompass FindCompass(String func)
uwp
static YCompass FindCompass(string func)
py
FindCompass(func)
php
function FindCompass($func)
ts
static FindCompass(func: string): YCompass
es
static FindCompass(func)
dnp
static YCompassProxy FindCompass(string func)
cp
static YCompassProxy * FindCompass(string func)

The identifier can be specified using several formats:

This function does not require that the compass function is online at the time it is invoked. The returned object is nevertheless valid. Use the method YCompass.isOnline() to test if the compass function is indeed online at a given time. In case of ambiguity when looking for a compass function by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

If a call to this object's is_online() method returns FALSE although you are certain that the matching device is plugged, make sure that you did call registerHub() at application initialization time.

Parameters :

funca string that uniquely characterizes the compass function, for instance Y3DMK002.compass.

Returns :

a YCompass object allowing you to drive the compass function.

YCompass.FindCompassInContext()
YCompass.FindCompassInContext()
YCompass.FindCompassInContext()YCompass.FindCompassInContext()YCompass.FindCompassInContext()YCompass.FindCompassInContext()

Retrieves a compass function for a given identifier in a YAPI context.

java
static YCompass FindCompassInContext(YAPIContext yctx, String func)
uwp
static YCompass FindCompassInContext(YAPIContext yctx, string func)
ts
static FindCompassInContext(yctx: YAPIContext, func: string): YCompass
es
static FindCompassInContext(yctx, func)

The identifier can be specified using several formats:

This function does not require that the compass function is online at the time it is invoked. The returned object is nevertheless valid. Use the method YCompass.isOnline() to test if the compass function is indeed online at a given time. In case of ambiguity when looking for a compass function by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

Parameters :

yctxa YAPI context
funca string that uniquely characterizes the compass function, for instance Y3DMK002.compass.

Returns :

a YCompass object allowing you to drive the compass function.

YCompass.FirstCompass()
YCompass.FirstCompass()
yFirstCompass()YCompass::FirstCompass()[YCompass FirstCompass]yFirstCompass()YCompass.FirstCompass()YCompass.FirstCompass()YCompass.FirstCompass()YCompass.FirstCompass()YCompass.FirstCompass()YCompass::FirstCompass()YCompass.FirstCompass()YCompass.FirstCompass()

Starts the enumeration of compass functions currently accessible.

js
function yFirstCompass()
cpp
YCompass * FirstCompass()
m
+(YCompass*) FirstCompass
pas
TYCompass yFirstCompass(): TYCompass
vb
function FirstCompass() As YCompass
cs
static YCompass FirstCompass()
java
static YCompass FirstCompass()
uwp
static YCompass FirstCompass()
py
FirstCompass()
php
function FirstCompass()
ts
static FirstCompass(): YCompass | null
es
static FirstCompass()

Use the method YCompass.nextCompass() to iterate on next compass functions.

Returns :

a pointer to a YCompass object, corresponding to the first compass function currently online, or a null pointer if there are none.

YCompass.FirstCompassInContext()
YCompass.FirstCompassInContext()
YCompass.FirstCompassInContext()YCompass.FirstCompassInContext()YCompass.FirstCompassInContext()YCompass.FirstCompassInContext()

Starts the enumeration of compass functions currently accessible.

java
static YCompass FirstCompassInContext(YAPIContext yctx)
uwp
static YCompass FirstCompassInContext(YAPIContext yctx)
ts
static FirstCompassInContext(yctx: YAPIContext): YCompass | null
es
static FirstCompassInContext(yctx)

Use the method YCompass.nextCompass() to iterate on next compass functions.

Parameters :

yctxa YAPI context.

Returns :

a pointer to a YCompass object, corresponding to the first compass function currently online, or a null pointer if there are none.

YCompass.GetSimilarFunctions()
YCompass.GetSimilarFunctions()
YCompass.GetSimilarFunctions()YCompass.GetSimilarFunctions()

Enumerates all functions of type Compass available on the devices currently reachable by the library, and returns their unique hardware ID.

dnp
static new string[] GetSimilarFunctions()
cp
static vector<string> GetSimilarFunctions()

Each of these IDs can be provided as argument to the method YCompass.FindCompass to obtain an object that can control the corresponding device.

Returns :

an array of strings, each string containing the unique hardwareId of a device function currently connected.

compass→AdvModecompass.AdvMode

Measuring mode used for the advertised value pushed to the parent hub.

dnp
int AdvMode

Writable. Remember to call the saveToFlash() method of the module if the modification must be kept.

compass→AdvertisedValuecompass.AdvertisedValue

Short string representing the current state of the function.

dnp
string AdvertisedValue

compass→Bandwidthcompass.Bandwidth

Measure update frequency, measured in Hz.

dnp
int Bandwidth

Writable. When the frequency is lower, the device performs averaging. Remember to call the saveToFlash() method of the module if the modification must be kept.

compass→FriendlyNamecompass.FriendlyName

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

dnp
string FriendlyName

The returned string uses the logical names of the module and of the function if they are defined, otherwise the serial number of the module and the hardware identifier of the function (for example: MyCustomName.relay1)

compass→FunctionIdcompass.FunctionId

Hardware identifier of the sensor, without reference to the module.

dnp
string FunctionId

For example relay1

compass→HardwareIdcompass.HardwareId

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

dnp
string HardwareId

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the function (for example RELAYLO1-123456.relay1).

compass→IsOnlinecompass.IsOnline

Checks if the function is currently reachable.

dnp
bool IsOnline

If there is a cached value for the function in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the function.

compass→LogFrequencycompass.LogFrequency

Datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

dnp
string LogFrequency

Writable. Changes the datalogger recording frequency for this function. The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (eg. "4/h"). To disable recording for this function, use the value "OFF". Note that setting the datalogger recording frequency to a greater value than the sensor native sampling frequency is useless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

compass→LogicalNamecompass.LogicalName

Logical name of the function.

dnp
string LogicalName

Writable. You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

compass→ReportFrequencycompass.ReportFrequency

Timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

dnp
string ReportFrequency

Writable. Changes the timed value notification frequency for this function. The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (e.g. "4/h"). To disable timed value notifications for this function, use the value "OFF". Note that setting the timed value notification frequency to a greater value than the sensor native sampling frequency is unless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

compass→Resolutioncompass.Resolution

Resolution of the measured values.

dnp
double Resolution

The resolution corresponds to the numerical precision of the measures, which is not always the same as the actual precision of the sensor. Remember to call the saveToFlash() method of the module if the modification must be kept.

Writable. Changes the resolution of the measured physical values. The resolution corresponds to the numerical precision when displaying value. It does not change the precision of the measure itself. Remember to call the saveToFlash() method of the module if the modification must be kept.

compass→SerialNumbercompass.SerialNumber

Serial number of the module, as set by the factory.

dnp
string SerialNumber

compass→calibrateFromPoints()compass.calibrateFromPoints()compass→calibrateFromPoints()[compass calibrateFromPoints: ]compass.calibrateFromPoints()compass.calibrateFromPoints()compass.calibrateFromPoints()compass.calibrateFromPoints()compass.calibrateFromPoints()compass.calibrateFromPoints()compass→calibrateFromPoints()compass.calibrateFromPoints()compass.calibrateFromPoints()compass.calibrateFromPoints()compass.calibrateFromPoints()YCompass calibrateFromPoints

Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.

js
function calibrateFromPoints(rawValues, refValues)
cpp
int calibrateFromPoints(vector<double> rawValues,
  vector<double> refValues)
m
-(int) calibrateFromPoints: (NSMutableArray*) rawValues
  : (NSMutableArray*) refValues
pas
LongInt calibrateFromPoints(rawValues: TDoubleArray,
  refValues: TDoubleArray): LongInt
vb
procedure calibrateFromPoints(ByVal rawValues As List(Of)
cs
int calibrateFromPoints(List<double> rawValues,
  List<double> refValues)
java
int calibrateFromPoints(ArrayList<Double> rawValues,
  ArrayList<Double> refValues)
uwp
async Task<int> calibrateFromPoints(List<double> rawValues,
  List<double> refValues)
py
calibrateFromPoints(rawValues, refValues)
php
function calibrateFromPoints($rawValues, $refValues)
ts
async calibrateFromPoints(rawValues: number[], refValues: number[]): Promise<number>
es
async calibrateFromPoints(rawValues, refValues)
dnp
int calibrateFromPoints(double[] rawValues,
  double[] refValues)
cp
int calibrateFromPoints(vector<double> rawValues,
  vector<double> refValues)
cmd
YCompass target calibrateFromPoints rawValues refValues

It is possible to configure up to five correction points. Correction points must be provided in ascending order, and be in the range of the sensor. The device will automatically perform a linear interpolation of the error correction between specified points. Remember to call the saveToFlash() method of the module if the modification must be kept.

For more information on advanced capabilities to refine the calibration of sensors, please contact support@yoctopuce.com.

Parameters :

rawValuesarray of floating point numbers, corresponding to the raw values returned by the sensor for the correction points.
refValuesarray of floating point numbers, corresponding to the corrected values for the correction points.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→clearCache()compass.clearCache()compass→clearCache()[compass clearCache]compass.clearCache()compass.clearCache()compass.clearCache()compass.clearCache()compass.clearCache()compass→clearCache()compass.clearCache()compass.clearCache()

Invalidates the cache.

js
function clearCache()
cpp
void clearCache()
m
-(void) clearCache
pas
clearCache()
vb
procedure clearCache()
cs
void clearCache()
java
void clearCache()
py
clearCache()
php
function clearCache()
ts
async clearCache(): Promise<void>
es
async clearCache()

Invalidates the cache of the compass function attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.

compass→describe()compass.describe()compass→describe()[compass describe]compass.describe()compass.describe()compass.describe()compass.describe()compass.describe()compass→describe()compass.describe()compass.describe()

Returns a short text that describes unambiguously the instance of the compass function in the form TYPE(NAME)=SERIAL.FUNCTIONID.

js
function describe()
cpp
string describe()
m
-(NSString*) describe
pas
string describe(): string
vb
function describe() As String
cs
string describe()
java
String describe()
py
describe()
php
function describe()
ts
async describe(): Promise<string>
es
async describe()

More precisely, TYPE is the type of the function, NAME it the name used for the first access to the function, SERIAL is the serial number of the module if the module is connected or "unresolved", and FUNCTIONID is the hardware identifier of the function if the module is connected. For example, this method returns Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1 if the module is already connected or Relay(BadCustomeName.relay1)=unresolved if the module has not yet been connected. This method does not trigger any USB or TCP transaction and can therefore be used in a debugger.

Returns :

a string that describes the compass function (ex: Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1)

compass→get_advMode()
compass→advMode()
compass.get_advMode()compass→get_advMode()[compass advMode]compass.get_advMode()compass.get_advMode()compass.get_advMode()compass.get_advMode()compass.get_advMode()compass.get_advMode()compass→get_advMode()compass.get_advMode()compass.get_advMode()compass.get_advMode()compass.get_advMode()YCompass get_advMode

Returns the measuring mode used for the advertised value pushed to the parent hub.

js
function get_advMode()
cpp
Y_ADVMODE_enum get_advMode()
m
-(Y_ADVMODE_enum) advMode
pas
Integer get_advMode(): Integer
vb
function get_advMode() As Integer
cs
int get_advMode()
java
int get_advMode()
uwp
async Task<int> get_advMode()
py
get_advMode()
php
function get_advMode()
ts
async get_advMode(): Promise<YSensor_AdvMode>
es
async get_advMode()
dnp
int get_advMode()
cp
int get_advMode()
cmd
YCompass target get_advMode

Returns :

a value among YCompass.ADVMODE_IMMEDIATE, YCompass.ADVMODE_PERIOD_AVG, YCompass.ADVMODE_PERIOD_MIN and YCompass.ADVMODE_PERIOD_MAX corresponding to the measuring mode used for the advertised value pushed to the parent hub

On failure, throws an exception or returns YCompass.ADVMODE_INVALID.

compass→get_advertisedValue()
compass→advertisedValue()
compass.get_advertisedValue()compass→get_advertisedValue()[compass advertisedValue]compass.get_advertisedValue()compass.get_advertisedValue()compass.get_advertisedValue()compass.get_advertisedValue()compass.get_advertisedValue()compass.get_advertisedValue()compass→get_advertisedValue()compass.get_advertisedValue()compass.get_advertisedValue()compass.get_advertisedValue()compass.get_advertisedValue()YCompass get_advertisedValue

Returns the current value of the compass function (no more than 6 characters).

js
function get_advertisedValue()
cpp
string get_advertisedValue()
m
-(NSString*) advertisedValue
pas
string get_advertisedValue(): string
vb
function get_advertisedValue() As String
cs
string get_advertisedValue()
java
String get_advertisedValue()
uwp
async Task<string> get_advertisedValue()
py
get_advertisedValue()
php
function get_advertisedValue()
ts
async get_advertisedValue(): Promise<string>
es
async get_advertisedValue()
dnp
string get_advertisedValue()
cp
string get_advertisedValue()
cmd
YCompass target get_advertisedValue

Returns :

a string corresponding to the current value of the compass function (no more than 6 characters).

On failure, throws an exception or returns YCompass.ADVERTISEDVALUE_INVALID.

compass→get_bandwidth()
compass→bandwidth()
compass.get_bandwidth()compass→get_bandwidth()[compass bandwidth]compass.get_bandwidth()compass.get_bandwidth()compass.get_bandwidth()compass.get_bandwidth()compass.get_bandwidth()compass.get_bandwidth()compass→get_bandwidth()compass.get_bandwidth()compass.get_bandwidth()compass.get_bandwidth()compass.get_bandwidth()YCompass get_bandwidth

Returns the measure update frequency, measured in Hz.

js
function get_bandwidth()
cpp
int get_bandwidth()
m
-(int) bandwidth
pas
LongInt get_bandwidth(): LongInt
vb
function get_bandwidth() As Integer
cs
int get_bandwidth()
java
int get_bandwidth()
uwp
async Task<int> get_bandwidth()
py
get_bandwidth()
php
function get_bandwidth()
ts
async get_bandwidth(): Promise<number>
es
async get_bandwidth()
dnp
int get_bandwidth()
cp
int get_bandwidth()
cmd
YCompass target get_bandwidth

Returns :

an integer corresponding to the measure update frequency, measured in Hz

On failure, throws an exception or returns YCompass.BANDWIDTH_INVALID.

compass→get_currentRawValue()
compass→currentRawValue()
compass.get_currentRawValue()compass→get_currentRawValue()[compass currentRawValue]compass.get_currentRawValue()compass.get_currentRawValue()compass.get_currentRawValue()compass.get_currentRawValue()compass.get_currentRawValue()compass.get_currentRawValue()compass→get_currentRawValue()compass.get_currentRawValue()compass.get_currentRawValue()compass.get_currentRawValue()compass.get_currentRawValue()YCompass get_currentRawValue

Returns the uncalibrated, unrounded raw value returned by the sensor, in degrees, as a floating point number.

js
function get_currentRawValue()
cpp
double get_currentRawValue()
m
-(double) currentRawValue
pas
double get_currentRawValue(): double
vb
function get_currentRawValue() As Double
cs
double get_currentRawValue()
java
double get_currentRawValue()
uwp
async Task<double> get_currentRawValue()
py
get_currentRawValue()
php
function get_currentRawValue()
ts
async get_currentRawValue(): Promise<number>
es
async get_currentRawValue()
dnp
double get_currentRawValue()
cp
double get_currentRawValue()
cmd
YCompass target get_currentRawValue

Returns :

a floating point number corresponding to the uncalibrated, unrounded raw value returned by the sensor, in degrees, as a floating point number

On failure, throws an exception or returns YCompass.CURRENTRAWVALUE_INVALID.

compass→get_currentValue()
compass→currentValue()
compass.get_currentValue()compass→get_currentValue()[compass currentValue]compass.get_currentValue()compass.get_currentValue()compass.get_currentValue()compass.get_currentValue()compass.get_currentValue()compass.get_currentValue()compass→get_currentValue()compass.get_currentValue()compass.get_currentValue()compass.get_currentValue()compass.get_currentValue()YCompass get_currentValue

Returns the current value of the relative bearing, in degrees, as a floating point number.

js
function get_currentValue()
cpp
double get_currentValue()
m
-(double) currentValue
pas
double get_currentValue(): double
vb
function get_currentValue() As Double
cs
double get_currentValue()
java
double get_currentValue()
uwp
async Task<double> get_currentValue()
py
get_currentValue()
php
function get_currentValue()
ts
async get_currentValue(): Promise<number>
es
async get_currentValue()
dnp
double get_currentValue()
cp
double get_currentValue()
cmd
YCompass target get_currentValue

Note that a get_currentValue() call will *not* start a measure in the device, it will just return the last measure that occurred in the device. Indeed, internally, each Yoctopuce devices is continuously making measurements at a hardware specific frequency.

If continuously calling get_currentValue() leads you to performances issues, then you might consider to switch to callback programming model. Check the "advanced programming" chapter in in your device user manual for more information.

Returns :

a floating point number corresponding to the current value of the relative bearing, in degrees, as a floating point number

On failure, throws an exception or returns YCompass.CURRENTVALUE_INVALID.

compass→get_dataLogger()
compass→dataLogger()
compass.get_dataLogger()compass→get_dataLogger()[compass dataLogger]compass.get_dataLogger()compass.get_dataLogger()compass.get_dataLogger()compass.get_dataLogger()compass.get_dataLogger()compass.get_dataLogger()compass→get_dataLogger()compass.get_dataLogger()compass.get_dataLogger()compass.get_dataLogger()compass.get_dataLogger()

Returns the YDatalogger object of the device hosting the sensor.

js
function get_dataLogger()
cpp
YDataLogger* get_dataLogger()
m
-(YDataLogger*) dataLogger
pas
TYDataLogger get_dataLogger(): TYDataLogger
vb
function get_dataLogger() As YDataLogger
cs
YDataLogger get_dataLogger()
java
YDataLogger get_dataLogger()
uwp
async Task<YDataLogger> get_dataLogger()
py
get_dataLogger()
php
function get_dataLogger()
ts
async get_dataLogger(): Promise<YDataLogger | null>
es
async get_dataLogger()
dnp
YDataLoggerProxy get_dataLogger()
cp
YDataLoggerProxy* get_dataLogger()

This method returns an object that can control global parameters of the data logger. The returned object should not be freed.

Returns :

an YDatalogger object, or null on error.

compass→get_errorMessage()
compass→errorMessage()
compass.get_errorMessage()compass→get_errorMessage()[compass errorMessage]compass.get_errorMessage()compass.get_errorMessage()compass.get_errorMessage()compass.get_errorMessage()compass.get_errorMessage()compass→get_errorMessage()compass.get_errorMessage()compass.get_errorMessage()

Returns the error message of the latest error with the compass function.

js
function get_errorMessage()
cpp
string get_errorMessage()
m
-(NSString*) errorMessage
pas
string get_errorMessage(): string
vb
function get_errorMessage() As String
cs
string get_errorMessage()
java
String get_errorMessage()
py
get_errorMessage()
php
function get_errorMessage()
ts
get_errorMessage(): string
es
get_errorMessage()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a string corresponding to the latest error message that occured while using the compass function object

compass→get_errorType()
compass→errorType()
compass.get_errorType()compass→get_errorType()[compass errorType]compass.get_errorType()compass.get_errorType()compass.get_errorType()compass.get_errorType()compass.get_errorType()compass→get_errorType()compass.get_errorType()compass.get_errorType()

Returns the numerical error code of the latest error with the compass function.

js
function get_errorType()
cpp
YRETCODE get_errorType()
m
-(YRETCODE) errorType
pas
YRETCODE get_errorType(): YRETCODE
vb
function get_errorType() As YRETCODE
cs
YRETCODE get_errorType()
java
int get_errorType()
py
get_errorType()
php
function get_errorType()
ts
get_errorType(): number
es
get_errorType()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a number corresponding to the code of the latest error that occurred while using the compass function object

compass→get_friendlyName()
compass→friendlyName()
compass.get_friendlyName()compass→get_friendlyName()[compass friendlyName]compass.get_friendlyName()compass.get_friendlyName()compass.get_friendlyName()compass→get_friendlyName()compass.get_friendlyName()compass.get_friendlyName()compass.get_friendlyName()compass.get_friendlyName()

Returns a global identifier of the compass function in the format MODULE_NAME.FUNCTION_NAME.

js
function get_friendlyName()
cpp
string get_friendlyName()
m
-(NSString*) friendlyName
cs
string get_friendlyName()
java
String get_friendlyName()
py
get_friendlyName()
php
function get_friendlyName()
ts
async get_friendlyName(): Promise<string>
es
async get_friendlyName()
dnp
string get_friendlyName()
cp
string get_friendlyName()

The returned string uses the logical names of the module and of the compass function if they are defined, otherwise the serial number of the module and the hardware identifier of the compass function (for example: MyCustomName.relay1)

Returns :

a string that uniquely identifies the compass function using logical names (ex: MyCustomName.relay1)

On failure, throws an exception or returns YCompass.FRIENDLYNAME_INVALID.

compass→get_functionDescriptor()
compass→functionDescriptor()
compass.get_functionDescriptor()compass→get_functionDescriptor()[compass functionDescriptor]compass.get_functionDescriptor()compass.get_functionDescriptor()compass.get_functionDescriptor()compass.get_functionDescriptor()compass.get_functionDescriptor()compass→get_functionDescriptor()compass.get_functionDescriptor()compass.get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

js
function get_functionDescriptor()
cpp
YFUN_DESCR get_functionDescriptor()
m
-(YFUN_DESCR) functionDescriptor
pas
YFUN_DESCR get_functionDescriptor(): YFUN_DESCR
vb
function get_functionDescriptor() As YFUN_DESCR
cs
YFUN_DESCR get_functionDescriptor()
java
String get_functionDescriptor()
py
get_functionDescriptor()
php
function get_functionDescriptor()
ts
async get_functionDescriptor(): Promise<string>
es
async get_functionDescriptor()

This identifier can be used to test if two instances of YFunction reference the same physical function on the same physical device.

Returns :

an identifier of type YFUN_DESCR.

If the function has never been contacted, the returned value is Y$CLASSNAME$.FUNCTIONDESCRIPTOR_INVALID.

compass→get_functionId()
compass→functionId()
compass.get_functionId()compass→get_functionId()[compass functionId]compass.get_functionId()compass.get_functionId()compass.get_functionId()compass.get_functionId()compass→get_functionId()compass.get_functionId()compass.get_functionId()compass.get_functionId()compass.get_functionId()

Returns the hardware identifier of the compass function, without reference to the module.

js
function get_functionId()
cpp
string get_functionId()
m
-(NSString*) functionId
vb
function get_functionId() As String
cs
string get_functionId()
java
String get_functionId()
py
get_functionId()
php
function get_functionId()
ts
async get_functionId(): Promise<string>
es
async get_functionId()
dnp
string get_functionId()
cp
string get_functionId()

For example relay1

Returns :

a string that identifies the compass function (ex: relay1)

On failure, throws an exception or returns YCompass.FUNCTIONID_INVALID.

compass→get_hardwareId()
compass→hardwareId()
compass.get_hardwareId()compass→get_hardwareId()[compass hardwareId]compass.get_hardwareId()compass.get_hardwareId()compass.get_hardwareId()compass.get_hardwareId()compass→get_hardwareId()compass.get_hardwareId()compass.get_hardwareId()compass.get_hardwareId()compass.get_hardwareId()

Returns the unique hardware identifier of the compass function in the form SERIAL.FUNCTIONID.

js
function get_hardwareId()
cpp
string get_hardwareId()
m
-(NSString*) hardwareId
vb
function get_hardwareId() As String
cs
string get_hardwareId()
java
String get_hardwareId()
py
get_hardwareId()
php
function get_hardwareId()
ts
async get_hardwareId(): Promise<string>
es
async get_hardwareId()
dnp
string get_hardwareId()
cp
string get_hardwareId()

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the compass function (for example RELAYLO1-123456.relay1).

Returns :

a string that uniquely identifies the compass function (ex: RELAYLO1-123456.relay1)

On failure, throws an exception or returns YCompass.HARDWAREID_INVALID.

compass→get_highestValue()
compass→highestValue()
compass.get_highestValue()compass→get_highestValue()[compass highestValue]compass.get_highestValue()compass.get_highestValue()compass.get_highestValue()compass.get_highestValue()compass.get_highestValue()compass.get_highestValue()compass→get_highestValue()compass.get_highestValue()compass.get_highestValue()compass.get_highestValue()compass.get_highestValue()YCompass get_highestValue

Returns the maximal value observed for the relative bearing since the device was started.

js
function get_highestValue()
cpp
double get_highestValue()
m
-(double) highestValue
pas
double get_highestValue(): double
vb
function get_highestValue() As Double
cs
double get_highestValue()
java
double get_highestValue()
uwp
async Task<double> get_highestValue()
py
get_highestValue()
php
function get_highestValue()
ts
async get_highestValue(): Promise<number>
es
async get_highestValue()
dnp
double get_highestValue()
cp
double get_highestValue()
cmd
YCompass target get_highestValue

Can be reset to an arbitrary value thanks to set_highestValue().

Returns :

a floating point number corresponding to the maximal value observed for the relative bearing since the device was started

On failure, throws an exception or returns YCompass.HIGHESTVALUE_INVALID.

compass→get_logFrequency()
compass→logFrequency()
compass.get_logFrequency()compass→get_logFrequency()[compass logFrequency]compass.get_logFrequency()compass.get_logFrequency()compass.get_logFrequency()compass.get_logFrequency()compass.get_logFrequency()compass.get_logFrequency()compass→get_logFrequency()compass.get_logFrequency()compass.get_logFrequency()compass.get_logFrequency()compass.get_logFrequency()YCompass get_logFrequency

Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

js
function get_logFrequency()
cpp
string get_logFrequency()
m
-(NSString*) logFrequency
pas
string get_logFrequency(): string
vb
function get_logFrequency() As String
cs
string get_logFrequency()
java
String get_logFrequency()
uwp
async Task<string> get_logFrequency()
py
get_logFrequency()
php
function get_logFrequency()
ts
async get_logFrequency(): Promise<string>
es
async get_logFrequency()
dnp
string get_logFrequency()
cp
string get_logFrequency()
cmd
YCompass target get_logFrequency

Returns :

a string corresponding to the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory

On failure, throws an exception or returns YCompass.LOGFREQUENCY_INVALID.

compass→get_logicalName()
compass→logicalName()
compass.get_logicalName()compass→get_logicalName()[compass logicalName]compass.get_logicalName()compass.get_logicalName()compass.get_logicalName()compass.get_logicalName()compass.get_logicalName()compass.get_logicalName()compass→get_logicalName()compass.get_logicalName()compass.get_logicalName()compass.get_logicalName()compass.get_logicalName()YCompass get_logicalName

Returns the logical name of the compass function.

js
function get_logicalName()
cpp
string get_logicalName()
m
-(NSString*) logicalName
pas
string get_logicalName(): string
vb
function get_logicalName() As String
cs
string get_logicalName()
java
String get_logicalName()
uwp
async Task<string> get_logicalName()
py
get_logicalName()
php
function get_logicalName()
ts
async get_logicalName(): Promise<string>
es
async get_logicalName()
dnp
string get_logicalName()
cp
string get_logicalName()
cmd
YCompass target get_logicalName

Returns :

a string corresponding to the logical name of the compass function.

On failure, throws an exception or returns YCompass.LOGICALNAME_INVALID.

compass→get_lowestValue()
compass→lowestValue()
compass.get_lowestValue()compass→get_lowestValue()[compass lowestValue]compass.get_lowestValue()compass.get_lowestValue()compass.get_lowestValue()compass.get_lowestValue()compass.get_lowestValue()compass.get_lowestValue()compass→get_lowestValue()compass.get_lowestValue()compass.get_lowestValue()compass.get_lowestValue()compass.get_lowestValue()YCompass get_lowestValue

Returns the minimal value observed for the relative bearing since the device was started.

js
function get_lowestValue()
cpp
double get_lowestValue()
m
-(double) lowestValue
pas
double get_lowestValue(): double
vb
function get_lowestValue() As Double
cs
double get_lowestValue()
java
double get_lowestValue()
uwp
async Task<double> get_lowestValue()
py
get_lowestValue()
php
function get_lowestValue()
ts
async get_lowestValue(): Promise<number>
es
async get_lowestValue()
dnp
double get_lowestValue()
cp
double get_lowestValue()
cmd
YCompass target get_lowestValue

Can be reset to an arbitrary value thanks to set_lowestValue().

Returns :

a floating point number corresponding to the minimal value observed for the relative bearing since the device was started

On failure, throws an exception or returns YCompass.LOWESTVALUE_INVALID.

compass→get_magneticHeading()
compass→magneticHeading()
compass.get_magneticHeading()compass→get_magneticHeading()[compass magneticHeading]compass.get_magneticHeading()compass.get_magneticHeading()compass.get_magneticHeading()compass.get_magneticHeading()compass.get_magneticHeading()compass.get_magneticHeading()compass→get_magneticHeading()compass.get_magneticHeading()compass.get_magneticHeading()compass.get_magneticHeading()compass.get_magneticHeading()YCompass get_magneticHeading

Returns the magnetic heading, regardless of the configured bearing.

js
function get_magneticHeading()
cpp
double get_magneticHeading()
m
-(double) magneticHeading
pas
double get_magneticHeading(): double
vb
function get_magneticHeading() As Double
cs
double get_magneticHeading()
java
double get_magneticHeading()
uwp
async Task<double> get_magneticHeading()
py
get_magneticHeading()
php
function get_magneticHeading()
ts
async get_magneticHeading(): Promise<number>
es
async get_magneticHeading()
dnp
double get_magneticHeading()
cp
double get_magneticHeading()
cmd
YCompass target get_magneticHeading

Returns :

a floating point number corresponding to the magnetic heading, regardless of the configured bearing

On failure, throws an exception or returns YCompass.MAGNETICHEADING_INVALID.

compass→get_module()
compass→module()
compass.get_module()compass→get_module()[compass module]compass.get_module()compass.get_module()compass.get_module()compass.get_module()compass.get_module()compass→get_module()compass.get_module()compass.get_module()compass.get_module()compass.get_module()

Gets the YModule object for the device on which the function is located.

js
function get_module()
cpp
YModule * get_module()
m
-(YModule*) module
pas
TYModule get_module(): TYModule
vb
function get_module() As YModule
cs
YModule get_module()
java
YModule get_module()
py
get_module()
php
function get_module()
ts
async get_module(): Promise<YModule>
es
async get_module()
dnp
YModuleProxy get_module()
cp
YModuleProxy * get_module()

If the function cannot be located on any module, the returned instance of YModule is not shown as on-line.

Returns :

an instance of YModule

compass→get_module_async()
compass→module_async()
compass.get_module_async()

Gets the YModule object for the device on which the function is located (asynchronous version).

js
function get_module_async(callback, context)

If the function cannot be located on any module, the returned YModule object does not show as on-line.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking Firefox JavaScript VM that does not implement context switching during blocking I/O calls. See the documentation section on asynchronous JavasSript calls for more details.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the requested YModule object
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

compass→get_recordedData()
compass→recordedData()
compass.get_recordedData()compass→get_recordedData()[compass recordedData: ]compass.get_recordedData()compass.get_recordedData()compass.get_recordedData()compass.get_recordedData()compass.get_recordedData()compass.get_recordedData()compass→get_recordedData()compass.get_recordedData()compass.get_recordedData()compass.get_recordedData()compass.get_recordedData()YCompass get_recordedData

Retrieves a YDataSet object holding historical data for this sensor, for a specified time interval.

js
function get_recordedData(startTime, endTime)
cpp
YDataSet get_recordedData(double startTime, double endTime)
m
-(YDataSet*) recordedData: (double) startTime
  : (double) endTime
pas
TYDataSet get_recordedData(startTime: double, endTime: double): TYDataSet
vb
function get_recordedData(ByVal startTime As Double,
  ByVal endTime As Double) As YDataSet
cs
YDataSet get_recordedData(double startTime, double endTime)
java
YDataSet get_recordedData(double startTime, double endTime)
uwp
async Task<YDataSet> get_recordedData(double startTime,
  double endTime)
py
get_recordedData(startTime, endTime)
php
function get_recordedData($startTime, $endTime)
ts
async get_recordedData(startTime: number, endTime: number): Promise<YDataSet>
es
async get_recordedData(startTime, endTime)
dnp
YDataSetProxy get_recordedData(double startTime,
  double endTime)
cp
YDataSetProxy* get_recordedData(double startTime,
  double endTime)
cmd
YCompass target get_recordedData startTime endTime

The measures will be retrieved from the data logger, which must have been turned on at the desired time. See the documentation of the YDataSet class for information on how to get an overview of the recorded data, and how to load progressively a large set of measures from the data logger.

This function only works if the device uses a recent firmware, as YDataSet objects are not supported by firmwares older than version 13000.

Parameters :

startTimethe start of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without initial limit.
endTimethe end of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without ending limit.

Returns :

an instance of YDataSet, providing access to historical data. Past measures can be loaded progressively using methods from the YDataSet object.

compass→get_reportFrequency()
compass→reportFrequency()
compass.get_reportFrequency()compass→get_reportFrequency()[compass reportFrequency]compass.get_reportFrequency()compass.get_reportFrequency()compass.get_reportFrequency()compass.get_reportFrequency()compass.get_reportFrequency()compass.get_reportFrequency()compass→get_reportFrequency()compass.get_reportFrequency()compass.get_reportFrequency()compass.get_reportFrequency()compass.get_reportFrequency()YCompass get_reportFrequency

Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

js
function get_reportFrequency()
cpp
string get_reportFrequency()
m
-(NSString*) reportFrequency
pas
string get_reportFrequency(): string
vb
function get_reportFrequency() As String
cs
string get_reportFrequency()
java
String get_reportFrequency()
uwp
async Task<string> get_reportFrequency()
py
get_reportFrequency()
php
function get_reportFrequency()
ts
async get_reportFrequency(): Promise<string>
es
async get_reportFrequency()
dnp
string get_reportFrequency()
cp
string get_reportFrequency()
cmd
YCompass target get_reportFrequency

Returns :

a string corresponding to the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function

On failure, throws an exception or returns YCompass.REPORTFREQUENCY_INVALID.

compass→get_resolution()
compass→resolution()
compass.get_resolution()compass→get_resolution()[compass resolution]compass.get_resolution()compass.get_resolution()compass.get_resolution()compass.get_resolution()compass.get_resolution()compass.get_resolution()compass→get_resolution()compass.get_resolution()compass.get_resolution()compass.get_resolution()compass.get_resolution()YCompass get_resolution

Returns the resolution of the measured values.

js
function get_resolution()
cpp
double get_resolution()
m
-(double) resolution
pas
double get_resolution(): double
vb
function get_resolution() As Double
cs
double get_resolution()
java
double get_resolution()
uwp
async Task<double> get_resolution()
py
get_resolution()
php
function get_resolution()
ts
async get_resolution(): Promise<number>
es
async get_resolution()
dnp
double get_resolution()
cp
double get_resolution()
cmd
YCompass target get_resolution

The resolution corresponds to the numerical precision of the measures, which is not always the same as the actual precision of the sensor. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

a floating point number corresponding to the resolution of the measured values

On failure, throws an exception or returns YCompass.RESOLUTION_INVALID.

compass→get_sensorState()
compass→sensorState()
compass.get_sensorState()compass→get_sensorState()[compass sensorState]compass.get_sensorState()compass.get_sensorState()compass.get_sensorState()compass.get_sensorState()compass.get_sensorState()compass.get_sensorState()compass→get_sensorState()compass.get_sensorState()compass.get_sensorState()compass.get_sensorState()compass.get_sensorState()YCompass get_sensorState

Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.

js
function get_sensorState()
cpp
int get_sensorState()
m
-(int) sensorState
pas
LongInt get_sensorState(): LongInt
vb
function get_sensorState() As Integer
cs
int get_sensorState()
java
int get_sensorState()
uwp
async Task<int> get_sensorState()
py
get_sensorState()
php
function get_sensorState()
ts
async get_sensorState(): Promise<number>
es
async get_sensorState()
dnp
int get_sensorState()
cp
int get_sensorState()
cmd
YCompass target get_sensorState

Returns :

an integer corresponding to the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now

On failure, throws an exception or returns YCompass.SENSORSTATE_INVALID.

compass→get_serialNumber()
compass→serialNumber()
compass.get_serialNumber()compass→get_serialNumber()[compass serialNumber]compass.get_serialNumber()compass.get_serialNumber()compass.get_serialNumber()compass.get_serialNumber()compass.get_serialNumber()compass.get_serialNumber()compass→get_serialNumber()compass.get_serialNumber()compass.get_serialNumber()compass.get_serialNumber()compass.get_serialNumber()YCompass get_serialNumber

Returns the serial number of the module, as set by the factory.

js
function get_serialNumber()
cpp
string get_serialNumber()
m
-(NSString*) serialNumber
pas
string get_serialNumber(): string
vb
function get_serialNumber() As String
cs
string get_serialNumber()
java
String get_serialNumber()
uwp
async Task<string> get_serialNumber()
py
get_serialNumber()
php
function get_serialNumber()
ts
async get_serialNumber(): Promise<string>
es
async get_serialNumber()
dnp
string get_serialNumber()
cp
string get_serialNumber()
cmd
YCompass target get_serialNumber

Returns :

a string corresponding to the serial number of the module, as set by the factory.

On failure, throws an exception or returns YFunction.SERIALNUMBER_INVALID.

compass→get_unit()
compass→unit()
compass.get_unit()compass→get_unit()[compass unit]compass.get_unit()compass.get_unit()compass.get_unit()compass.get_unit()compass.get_unit()compass.get_unit()compass→get_unit()compass.get_unit()compass.get_unit()compass.get_unit()compass.get_unit()YCompass get_unit

Returns the measuring unit for the relative bearing.

js
function get_unit()
cpp
string get_unit()
m
-(NSString*) unit
pas
string get_unit(): string
vb
function get_unit() As String
cs
string get_unit()
java
String get_unit()
uwp
async Task<string> get_unit()
py
get_unit()
php
function get_unit()
ts
async get_unit(): Promise<string>
es
async get_unit()
dnp
string get_unit()
cp
string get_unit()
cmd
YCompass target get_unit

Returns :

a string corresponding to the measuring unit for the relative bearing

On failure, throws an exception or returns YCompass.UNIT_INVALID.

compass→get_userData()
compass→userData()
compass.get_userData()compass→get_userData()[compass userData]compass.get_userData()compass.get_userData()compass.get_userData()compass.get_userData()compass.get_userData()compass→get_userData()compass.get_userData()compass.get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

js
function get_userData()
cpp
void * get_userData()
m
-(id) userData
pas
Tobject get_userData(): Tobject
vb
function get_userData() As Object
cs
object get_userData()
java
Object get_userData()
py
get_userData()
php
function get_userData()
ts
async get_userData(): Promise<object|null>
es
async get_userData()

This attribute is never touched directly by the API, and is at disposal of the caller to store a context.

Returns :

the object stored previously by the caller.

compass→isOnline()compass.isOnline()compass→isOnline()[compass isOnline]compass.isOnline()compass.isOnline()compass.isOnline()compass.isOnline()compass.isOnline()compass→isOnline()compass.isOnline()compass.isOnline()compass.isOnline()compass.isOnline()

Checks if the compass function is currently reachable, without raising any error.

js
function isOnline()
cpp
bool isOnline()
m
-(BOOL) isOnline
pas
boolean isOnline(): boolean
vb
function isOnline() As Boolean
cs
bool isOnline()
java
boolean isOnline()
py
isOnline()
php
function isOnline()
ts
async isOnline(): Promise<boolean>
es
async isOnline()
dnp
bool isOnline()
cp
bool isOnline()

If there is a cached value for the compass function in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the compass function.

Returns :

true if the compass function can be reached, and false otherwise

compass→isOnline_async()compass.isOnline_async()

Checks if the compass function is currently reachable, without raising any error (asynchronous version).

js
function isOnline_async(callback, context)

If there is a cached value for the compass function in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the requested function.

This asynchronous version exists only in Javascript. It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the boolean result
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

compass→isReadOnly()compass→isReadOnly()[compass isReadOnly]compass.isReadOnly()compass.isReadOnly()compass.isReadOnly()compass.isReadOnly()compass.isReadOnly()compass.isReadOnly()compass→isReadOnly()compass.isReadOnly()compass.isReadOnly()compass.isReadOnly()compass.isReadOnly()YCompass isReadOnly

Test if the function is readOnly.

cpp
bool isReadOnly()
m
-(bool) isReadOnly
pas
boolean isReadOnly(): boolean
vb
function isReadOnly() As Boolean
cs
bool isReadOnly()
java
boolean isReadOnly()
uwp
async Task<bool> isReadOnly()
py
isReadOnly()
php
function isReadOnly()
ts
async isReadOnly(): Promise<boolean>
es
async isReadOnly()
dnp
bool isReadOnly()
cp
bool isReadOnly()
cmd
YCompass target isReadOnly

Return true if the function is write protected or that the function is not available.

Returns :

true if the function is readOnly or not online.

compass→isSensorReady()YCompass isSensorReady

Checks if the sensor is currently able to provide an up-to-date measure.

cmd
YCompass target isSensorReady

Returns false if the device is unreachable, or if the sensor does not have a current measure to transmit. No exception is raised if there is an error while trying to contact the device hosting $THEFUNCTION$.

Returns :

true if the sensor can provide an up-to-date measure, and false otherwise

compass→load()compass.load()compass→load()[compass load: ]compass.load()compass.load()compass.load()compass.load()compass.load()compass→load()compass.load()compass.load()

Preloads the compass function cache with a specified validity duration.

js
function load(msValidity)
cpp
YRETCODE load(int msValidity)
m
-(YRETCODE) load: (u64) msValidity
pas
YRETCODE load(msValidity: u64): YRETCODE
vb
function load(ByVal msValidity As Long) As YRETCODE
cs
YRETCODE load(ulong msValidity)
java
int load(long msValidity)
py
load(msValidity)
php
function load($msValidity)
ts
async load(msValidity: number): Promise<number>
es
async load(msValidity)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

Parameters :

msValidityan integer corresponding to the validity attributed to the loaded function parameters, in milliseconds

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→loadAttribute()compass.loadAttribute()compass→loadAttribute()[compass loadAttribute: ]compass.loadAttribute()compass.loadAttribute()compass.loadAttribute()compass.loadAttribute()compass.loadAttribute()compass.loadAttribute()compass→loadAttribute()compass.loadAttribute()compass.loadAttribute()compass.loadAttribute()compass.loadAttribute()

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

js
function loadAttribute(attrName)
cpp
string loadAttribute(string attrName)
m
-(NSString*) loadAttribute: (NSString*) attrName
pas
string loadAttribute(attrName: string): string
vb
function loadAttribute(ByVal attrName As String) As String
cs
string loadAttribute(string attrName)
java
String loadAttribute(String attrName)
uwp
async Task<string> loadAttribute(string attrName)
py
loadAttribute(attrName)
php
function loadAttribute($attrName)
ts
async loadAttribute(attrName: string): Promise<string>
es
async loadAttribute(attrName)
dnp
string loadAttribute(string attrName)
cp
string loadAttribute(string attrName)

Parameters :

attrNamethe name of the requested attribute

Returns :

a string with the value of the the attribute

On failure, throws an exception or returns an empty string.

compass→loadCalibrationPoints()compass.loadCalibrationPoints()compass→loadCalibrationPoints()[compass loadCalibrationPoints: ]compass.loadCalibrationPoints()compass.loadCalibrationPoints()compass.loadCalibrationPoints()compass.loadCalibrationPoints()compass.loadCalibrationPoints()compass.loadCalibrationPoints()compass→loadCalibrationPoints()compass.loadCalibrationPoints()compass.loadCalibrationPoints()YCompass loadCalibrationPoints

Retrieves error correction data points previously entered using the method calibrateFromPoints.

js
function loadCalibrationPoints(rawValues, refValues)
cpp
int loadCalibrationPoints(vector<double> rawValues,
  vector<double> refValues)
m
-(int) loadCalibrationPoints: (NSMutableArray*) rawValues
  : (NSMutableArray*) refValues
pas
LongInt loadCalibrationPoints(var rawValues: TDoubleArray,
  var refValues: TDoubleArray): LongInt
vb
procedure loadCalibrationPoints(ByVal rawValues As List(Of)
cs
int loadCalibrationPoints(List<double> rawValues,
  List<double> refValues)
java
int loadCalibrationPoints(ArrayList<Double> rawValues,
  ArrayList<Double> refValues)
uwp
async Task<int> loadCalibrationPoints(List<double> rawValues,
  List<double> refValues)
py
loadCalibrationPoints(rawValues, refValues)
php
function loadCalibrationPoints(&$rawValues, &$refValues)
ts
async loadCalibrationPoints(rawValues: number[], refValues: number[]): Promise<number>
es
async loadCalibrationPoints(rawValues, refValues)
cmd
YCompass target loadCalibrationPoints rawValues refValues

Parameters :

rawValuesarray of floating point numbers, that will be filled by the function with the raw sensor values for the correction points.
refValuesarray of floating point numbers, that will be filled by the function with the desired values for the correction points.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→load_async()compass.load_async()

Preloads the compass function cache with a specified validity duration (asynchronous version).

js
function load_async(msValidity, callback, context)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking the JavaScript virtual machine.

Parameters :

msValidityan integer corresponding to the validity of the loaded function parameters, in milliseconds
callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the error code (or YAPI.SUCCESS)
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

compass→muteValueCallbacks()compass.muteValueCallbacks()compass→muteValueCallbacks()[compass muteValueCallbacks]compass.muteValueCallbacks()compass.muteValueCallbacks()compass.muteValueCallbacks()compass.muteValueCallbacks()compass.muteValueCallbacks()compass.muteValueCallbacks()compass→muteValueCallbacks()compass.muteValueCallbacks()compass.muteValueCallbacks()compass.muteValueCallbacks()compass.muteValueCallbacks()YCompass muteValueCallbacks

Disables the propagation of every new advertised value to the parent hub.

js
function muteValueCallbacks()
cpp
int muteValueCallbacks()
m
-(int) muteValueCallbacks
pas
LongInt muteValueCallbacks(): LongInt
vb
function muteValueCallbacks() As Integer
cs
int muteValueCallbacks()
java
int muteValueCallbacks()
uwp
async Task<int> muteValueCallbacks()
py
muteValueCallbacks()
php
function muteValueCallbacks()
ts
async muteValueCallbacks(): Promise<number>
es
async muteValueCallbacks()
dnp
int muteValueCallbacks()
cp
int muteValueCallbacks()
cmd
YCompass target muteValueCallbacks

You can use this function to save bandwidth and CPU on computers with limited resources, or to prevent unwanted invocations of the HTTP callback. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→nextCompass()compass.nextCompass()compass→nextCompass()[compass nextCompass]compass.nextCompass()compass.nextCompass()compass.nextCompass()compass.nextCompass()compass.nextCompass()compass.nextCompass()compass→nextCompass()compass.nextCompass()compass.nextCompass()

Continues the enumeration of compass functions started using yFirstCompass().

js
function nextCompass()
cpp
YCompass * nextCompass()
m
-(nullable YCompass*) nextCompass
pas
TYCompass nextCompass(): TYCompass
vb
function nextCompass() As YCompass
cs
YCompass nextCompass()
java
YCompass nextCompass()
uwp
YCompass nextCompass()
py
nextCompass()
php
function nextCompass()
ts
nextCompass(): YCompass | null
es
nextCompass()

Caution: You can't make any assumption about the returned compass functions order. If you want to find a specific a compass function, use Compass.findCompass() and a hardwareID or a logical name.

Returns :

a pointer to a YCompass object, corresponding to a compass function currently online, or a null pointer if there are no more compass functions to enumerate.

compass→registerTimedReportCallback()compass.registerTimedReportCallback()compass→registerTimedReportCallback()[compass registerTimedReportCallback: ]compass.registerTimedReportCallback()compass.registerTimedReportCallback()compass.registerTimedReportCallback()compass.registerTimedReportCallback()compass.registerTimedReportCallback()compass.registerTimedReportCallback()compass→registerTimedReportCallback()compass.registerTimedReportCallback()compass.registerTimedReportCallback()

Registers the callback function that is invoked on every periodic timed notification.

js
function registerTimedReportCallback(callback)
cpp
int registerTimedReportCallback(YCompassTimedReportCallback callback)
m
-(int) registerTimedReportCallback: (YCompassTimedReportCallback _Nullable) callback
pas
LongInt registerTimedReportCallback(callback: TYCompassTimedReportCallback): LongInt
vb
function registerTimedReportCallback(ByVal callback As YCompassTimedReportCallback) As Integer
cs
int registerTimedReportCallback(TimedReportCallback callback)
java
int registerTimedReportCallback(TimedReportCallback callback)
uwp
async Task<int> registerTimedReportCallback(TimedReportCallback callback)
py
registerTimedReportCallback(callback)
php
function registerTimedReportCallback($callback)
ts
async registerTimedReportCallback(callback: YCompassTimedReportCallback | null): Promise<number>
es
async registerTimedReportCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and an YMeasure object describing the new advertised value.

compass→registerValueCallback()compass.registerValueCallback()compass→registerValueCallback()[compass registerValueCallback: ]compass.registerValueCallback()compass.registerValueCallback()compass.registerValueCallback()compass.registerValueCallback()compass.registerValueCallback()compass.registerValueCallback()compass→registerValueCallback()compass.registerValueCallback()compass.registerValueCallback()

Registers the callback function that is invoked on every change of advertised value.

js
function registerValueCallback(callback)
cpp
int registerValueCallback(YCompassValueCallback callback)
m
-(int) registerValueCallback: (YCompassValueCallback _Nullable) callback
pas
LongInt registerValueCallback(callback: TYCompassValueCallback): LongInt
vb
function registerValueCallback(ByVal callback As YCompassValueCallback) As Integer
cs
int registerValueCallback(ValueCallback callback)
java
int registerValueCallback(UpdateCallback callback)
uwp
async Task<int> registerValueCallback(ValueCallback callback)
py
registerValueCallback(callback)
php
function registerValueCallback($callback)
ts
async registerValueCallback(callback: YCompassValueCallback | null): Promise<number>
es
async registerValueCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and the character string describing the new advertised value.

compass→set_advMode()
compass→setAdvMode()
compass.set_advMode()compass→set_advMode()[compass setAdvMode: ]compass.set_advMode()compass.set_advMode()compass.set_advMode()compass.set_advMode()compass.set_advMode()compass.set_advMode()compass→set_advMode()compass.set_advMode()compass.set_advMode()compass.set_advMode()compass.set_advMode()YCompass set_advMode

Changes the measuring mode used for the advertised value pushed to the parent hub.

js
function set_advMode(newval)
cpp
int set_advMode(Y_ADVMODE_enum newval)
m
-(int) setAdvMode: (Y_ADVMODE_enum) newval
pas
integer set_advMode(newval: Integer): integer
vb
function set_advMode(ByVal newval As Integer) As Integer
cs
int set_advMode(int newval)
java
int set_advMode(int newval)
uwp
async Task<int> set_advMode(int newval)
py
set_advMode(newval)
php
function set_advMode($newval)
ts
async set_advMode(newval: YSensor_AdvMode): Promise<number>
es
async set_advMode(newval)
dnp
int set_advMode(int newval)
cp
int set_advMode(int newval)
cmd
YCompass target set_advMode newval

Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala value among YCompass.ADVMODE_IMMEDIATE, YCompass.ADVMODE_PERIOD_AVG, YCompass.ADVMODE_PERIOD_MIN and YCompass.ADVMODE_PERIOD_MAX corresponding to the measuring mode used for the advertised value pushed to the parent hub

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→set_bandwidth()
compass→setBandwidth()
compass.set_bandwidth()compass→set_bandwidth()[compass setBandwidth: ]compass.set_bandwidth()compass.set_bandwidth()compass.set_bandwidth()compass.set_bandwidth()compass.set_bandwidth()compass.set_bandwidth()compass→set_bandwidth()compass.set_bandwidth()compass.set_bandwidth()compass.set_bandwidth()compass.set_bandwidth()YCompass set_bandwidth

Changes the measure update frequency, measured in Hz.

js
function set_bandwidth(newval)
cpp
int set_bandwidth(int newval)
m
-(int) setBandwidth: (int) newval
pas
integer set_bandwidth(newval: LongInt): integer
vb
function set_bandwidth(ByVal newval As Integer) As Integer
cs
int set_bandwidth(int newval)
java
int set_bandwidth(int newval)
uwp
async Task<int> set_bandwidth(int newval)
py
set_bandwidth(newval)
php
function set_bandwidth($newval)
ts
async set_bandwidth(newval: number): Promise<number>
es
async set_bandwidth(newval)
dnp
int set_bandwidth(int newval)
cp
int set_bandwidth(int newval)
cmd
YCompass target set_bandwidth newval

When the frequency is lower, the device performs averaging. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvalan integer corresponding to the measure update frequency, measured in Hz

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→set_highestValue()
compass→setHighestValue()
compass.set_highestValue()compass→set_highestValue()[compass setHighestValue: ]compass.set_highestValue()compass.set_highestValue()compass.set_highestValue()compass.set_highestValue()compass.set_highestValue()compass.set_highestValue()compass→set_highestValue()compass.set_highestValue()compass.set_highestValue()compass.set_highestValue()compass.set_highestValue()YCompass set_highestValue

Changes the recorded maximal value observed.

js
function set_highestValue(newval)
cpp
int set_highestValue(double newval)
m
-(int) setHighestValue: (double) newval
pas
integer set_highestValue(newval: double): integer
vb
function set_highestValue(ByVal newval As Double) As Integer
cs
int set_highestValue(double newval)
java
int set_highestValue(double newval)
uwp
async Task<int> set_highestValue(double newval)
py
set_highestValue(newval)
php
function set_highestValue($newval)
ts
async set_highestValue(newval: number): Promise<number>
es
async set_highestValue(newval)
dnp
int set_highestValue(double newval)
cp
int set_highestValue(double newval)
cmd
YCompass target set_highestValue newval

Can be used to reset the value returned by get_lowestValue().

Parameters :

newvala floating point number corresponding to the recorded maximal value observed

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→set_logFrequency()
compass→setLogFrequency()
compass.set_logFrequency()compass→set_logFrequency()[compass setLogFrequency: ]compass.set_logFrequency()compass.set_logFrequency()compass.set_logFrequency()compass.set_logFrequency()compass.set_logFrequency()compass.set_logFrequency()compass→set_logFrequency()compass.set_logFrequency()compass.set_logFrequency()compass.set_logFrequency()compass.set_logFrequency()YCompass set_logFrequency

Changes the datalogger recording frequency for this function.

js
function set_logFrequency(newval)
cpp
int set_logFrequency(string newval)
m
-(int) setLogFrequency: (NSString*) newval
pas
integer set_logFrequency(newval: string): integer
vb
function set_logFrequency(ByVal newval As String) As Integer
cs
int set_logFrequency(string newval)
java
int set_logFrequency(String newval)
uwp
async Task<int> set_logFrequency(string newval)
py
set_logFrequency(newval)
php
function set_logFrequency($newval)
ts
async set_logFrequency(newval: string): Promise<number>
es
async set_logFrequency(newval)
dnp
int set_logFrequency(string newval)
cp
int set_logFrequency(string newval)
cmd
YCompass target set_logFrequency newval

The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (eg. "4/h"). To disable recording for this function, use the value "OFF". Note that setting the datalogger recording frequency to a greater value than the sensor native sampling frequency is useless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the datalogger recording frequency for this function

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→set_logicalName()
compass→setLogicalName()
compass.set_logicalName()compass→set_logicalName()[compass setLogicalName: ]compass.set_logicalName()compass.set_logicalName()compass.set_logicalName()compass.set_logicalName()compass.set_logicalName()compass.set_logicalName()compass→set_logicalName()compass.set_logicalName()compass.set_logicalName()compass.set_logicalName()compass.set_logicalName()YCompass set_logicalName

Changes the logical name of the compass function.

js
function set_logicalName(newval)
cpp
int set_logicalName(string newval)
m
-(int) setLogicalName: (NSString*) newval
pas
integer set_logicalName(newval: string): integer
vb
function set_logicalName(ByVal newval As String) As Integer
cs
int set_logicalName(string newval)
java
int set_logicalName(String newval)
uwp
async Task<int> set_logicalName(string newval)
py
set_logicalName(newval)
php
function set_logicalName($newval)
ts
async set_logicalName(newval: string): Promise<number>
es
async set_logicalName(newval)
dnp
int set_logicalName(string newval)
cp
int set_logicalName(string newval)
cmd
YCompass target set_logicalName newval

You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the logical name of the compass function.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→set_lowestValue()
compass→setLowestValue()
compass.set_lowestValue()compass→set_lowestValue()[compass setLowestValue: ]compass.set_lowestValue()compass.set_lowestValue()compass.set_lowestValue()compass.set_lowestValue()compass.set_lowestValue()compass.set_lowestValue()compass→set_lowestValue()compass.set_lowestValue()compass.set_lowestValue()compass.set_lowestValue()compass.set_lowestValue()YCompass set_lowestValue

Changes the recorded minimal value observed.

js
function set_lowestValue(newval)
cpp
int set_lowestValue(double newval)
m
-(int) setLowestValue: (double) newval
pas
integer set_lowestValue(newval: double): integer
vb
function set_lowestValue(ByVal newval As Double) As Integer
cs
int set_lowestValue(double newval)
java
int set_lowestValue(double newval)
uwp
async Task<int> set_lowestValue(double newval)
py
set_lowestValue(newval)
php
function set_lowestValue($newval)
ts
async set_lowestValue(newval: number): Promise<number>
es
async set_lowestValue(newval)
dnp
int set_lowestValue(double newval)
cp
int set_lowestValue(double newval)
cmd
YCompass target set_lowestValue newval

Can be used to reset the value returned by get_lowestValue().

Parameters :

newvala floating point number corresponding to the recorded minimal value observed

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→set_reportFrequency()
compass→setReportFrequency()
compass.set_reportFrequency()compass→set_reportFrequency()[compass setReportFrequency: ]compass.set_reportFrequency()compass.set_reportFrequency()compass.set_reportFrequency()compass.set_reportFrequency()compass.set_reportFrequency()compass.set_reportFrequency()compass→set_reportFrequency()compass.set_reportFrequency()compass.set_reportFrequency()compass.set_reportFrequency()compass.set_reportFrequency()YCompass set_reportFrequency

Changes the timed value notification frequency for this function.

js
function set_reportFrequency(newval)
cpp
int set_reportFrequency(string newval)
m
-(int) setReportFrequency: (NSString*) newval
pas
integer set_reportFrequency(newval: string): integer
vb
function set_reportFrequency(ByVal newval As String) As Integer
cs
int set_reportFrequency(string newval)
java
int set_reportFrequency(String newval)
uwp
async Task<int> set_reportFrequency(string newval)
py
set_reportFrequency(newval)
php
function set_reportFrequency($newval)
ts
async set_reportFrequency(newval: string): Promise<number>
es
async set_reportFrequency(newval)
dnp
int set_reportFrequency(string newval)
cp
int set_reportFrequency(string newval)
cmd
YCompass target set_reportFrequency newval

The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (e.g. "4/h"). To disable timed value notifications for this function, use the value "OFF". Note that setting the timed value notification frequency to a greater value than the sensor native sampling frequency is unless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the timed value notification frequency for this function

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→set_resolution()
compass→setResolution()
compass.set_resolution()compass→set_resolution()[compass setResolution: ]compass.set_resolution()compass.set_resolution()compass.set_resolution()compass.set_resolution()compass.set_resolution()compass.set_resolution()compass→set_resolution()compass.set_resolution()compass.set_resolution()compass.set_resolution()compass.set_resolution()YCompass set_resolution

Changes the resolution of the measured physical values.

js
function set_resolution(newval)
cpp
int set_resolution(double newval)
m
-(int) setResolution: (double) newval
pas
integer set_resolution(newval: double): integer
vb
function set_resolution(ByVal newval As Double) As Integer
cs
int set_resolution(double newval)
java
int set_resolution(double newval)
uwp
async Task<int> set_resolution(double newval)
py
set_resolution(newval)
php
function set_resolution($newval)
ts
async set_resolution(newval: number): Promise<number>
es
async set_resolution(newval)
dnp
int set_resolution(double newval)
cp
int set_resolution(double newval)
cmd
YCompass target set_resolution newval

The resolution corresponds to the numerical precision when displaying value. It does not change the precision of the measure itself. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala floating point number corresponding to the resolution of the measured physical values

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→set_userData()
compass→setUserData()
compass.set_userData()compass→set_userData()[compass setUserData: ]compass.set_userData()compass.set_userData()compass.set_userData()compass.set_userData()compass.set_userData()compass→set_userData()compass.set_userData()compass.set_userData()

Stores a user context provided as argument in the userData attribute of the function.

js
function set_userData(data)
cpp
void set_userData(void * data)
m
-(void) setUserData: (id) data
pas
set_userData(data: Tobject)
vb
procedure set_userData(ByVal data As Object)
cs
void set_userData(object data)
java
void set_userData(Object data)
py
set_userData(data)
php
function set_userData($data)
ts
async set_userData(data: object|null): Promise<void>
es
async set_userData(data)

This attribute is never touched by the API, and is at disposal of the caller to store a context.

Parameters :

dataany kind of object to be stored

compass→startDataLogger()compass.startDataLogger()compass→startDataLogger()[compass startDataLogger]compass.startDataLogger()compass.startDataLogger()compass.startDataLogger()compass.startDataLogger()compass.startDataLogger()compass.startDataLogger()compass→startDataLogger()compass.startDataLogger()compass.startDataLogger()compass.startDataLogger()compass.startDataLogger()YCompass startDataLogger

Starts the data logger on the device.

js
function startDataLogger()
cpp
int startDataLogger()
m
-(int) startDataLogger
pas
LongInt startDataLogger(): LongInt
vb
function startDataLogger() As Integer
cs
int startDataLogger()
java
int startDataLogger()
uwp
async Task<int> startDataLogger()
py
startDataLogger()
php
function startDataLogger()
ts
async startDataLogger(): Promise<number>
es
async startDataLogger()
dnp
int startDataLogger()
cp
int startDataLogger()
cmd
YCompass target startDataLogger

Note that the data logger will only save the measures on this sensor if the logFrequency is not set to "OFF".

Returns :

YAPI.SUCCESS if the call succeeds.

compass→stopDataLogger()compass.stopDataLogger()compass→stopDataLogger()[compass stopDataLogger]compass.stopDataLogger()compass.stopDataLogger()compass.stopDataLogger()compass.stopDataLogger()compass.stopDataLogger()compass.stopDataLogger()compass→stopDataLogger()compass.stopDataLogger()compass.stopDataLogger()compass.stopDataLogger()compass.stopDataLogger()YCompass stopDataLogger

Stops the datalogger on the device.

js
function stopDataLogger()
cpp
int stopDataLogger()
m
-(int) stopDataLogger
pas
LongInt stopDataLogger(): LongInt
vb
function stopDataLogger() As Integer
cs
int stopDataLogger()
java
int stopDataLogger()
uwp
async Task<int> stopDataLogger()
py
stopDataLogger()
php
function stopDataLogger()
ts
async stopDataLogger(): Promise<number>
es
async stopDataLogger()
dnp
int stopDataLogger()
cp
int stopDataLogger()
cmd
YCompass target stopDataLogger

Returns :

YAPI.SUCCESS if the call succeeds.

compass→unmuteValueCallbacks()compass.unmuteValueCallbacks()compass→unmuteValueCallbacks()[compass unmuteValueCallbacks]compass.unmuteValueCallbacks()compass.unmuteValueCallbacks()compass.unmuteValueCallbacks()compass.unmuteValueCallbacks()compass.unmuteValueCallbacks()compass.unmuteValueCallbacks()compass→unmuteValueCallbacks()compass.unmuteValueCallbacks()compass.unmuteValueCallbacks()compass.unmuteValueCallbacks()compass.unmuteValueCallbacks()YCompass unmuteValueCallbacks

Re-enables the propagation of every new advertised value to the parent hub.

js
function unmuteValueCallbacks()
cpp
int unmuteValueCallbacks()
m
-(int) unmuteValueCallbacks
pas
LongInt unmuteValueCallbacks(): LongInt
vb
function unmuteValueCallbacks() As Integer
cs
int unmuteValueCallbacks()
java
int unmuteValueCallbacks()
uwp
async Task<int> unmuteValueCallbacks()
py
unmuteValueCallbacks()
php
function unmuteValueCallbacks()
ts
async unmuteValueCallbacks(): Promise<number>
es
async unmuteValueCallbacks()
dnp
int unmuteValueCallbacks()
cp
int unmuteValueCallbacks()
cmd
YCompass target unmuteValueCallbacks

This function reverts the effect of a previous call to muteValueCallbacks(). Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

compass→wait_async()compass.wait_async()compass.wait_async()compass.wait_async()

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

js
function wait_async(callback, context)
ts
wait_async(callback: Function, context: object)
es
wait_async(callback, context)

The callback function can therefore freely issue synchronous or asynchronous commands, without risking to block the JavaScript VM.

Parameters :

callbackcallback function that is invoked when all pending commands on the module are completed. The callback function receives two arguments: the caller-specific context object and the receiving function object.
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing.

24.8. Class YGyro

Gyroscope control interface, available for instance in the Yocto-3D-V2

The YGyro class allows you to read and configure Yoctopuce gyroscopes. It inherits from YSensor class the core functions to read measurements, to register callback functions, and to access the autonomous datalogger. This class adds the possibility to access x, y and z components of the rotation vector separately, as well as the possibility to deal with quaternion-based orientation estimates.

In order to use the functions described here, you should include:

js
<script type='text/javascript' src='yocto_gyro.js'></script>
cpp
#include "yocto_gyro.h"
m
#import "yocto_gyro.h"
pas
uses yocto_gyro;
vb
yocto_gyro.vb
cs
yocto_gyro.cs
java
import com.yoctopuce.YoctoAPI.YGyro;
uwp
import com.yoctopuce.YoctoAPI.YGyro;
py
from yocto_gyro import *
php
require_once('yocto_gyro.php');
ts
in HTML: import { YGyro } from '../../dist/esm/yocto_gyro.js';
in Node.js: import { YGyro } from 'yoctolib-cjs/yocto_gyro.js';
es
in HTML: <script src="../../lib/yocto_gyro.js"></script>
in node.js: require('yoctolib-es2017/yocto_gyro.js');
dnp
import YoctoProxyAPI.YGyroProxy
cp
#include "yocto_gyro_proxy.h"
vi
YGyro.vi
ml
import YoctoProxyAPI.YGyroProxy
Global functions
YGyro.FindGyro(func)

Retrieves a gyroscope for a given identifier.

YGyro.FindGyroInContext(yctx, func)

Retrieves a gyroscope for a given identifier in a YAPI context.

YGyro.FirstGyro()

Starts the enumeration of gyroscopes currently accessible.

YGyro.FirstGyroInContext(yctx)

Starts the enumeration of gyroscopes currently accessible.

YGyro.GetSimilarFunctions()

Enumerates all functions of type Gyro available on the devices currently reachable by the library, and returns their unique hardware ID.

YGyro properties
gyro→AdvMode [writable]

Measuring mode used for the advertised value pushed to the parent hub.

gyro→AdvertisedValue [read-only]

Short string representing the current state of the function.

gyro→Bandwidth [writable]

Measure update frequency, measured in Hz.

gyro→FriendlyName [read-only]

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

gyro→FunctionId [read-only]

Hardware identifier of the sensor, without reference to the module.

gyro→HardwareId [read-only]

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

gyro→IsOnline [read-only]

Checks if the function is currently reachable.

gyro→LogFrequency [writable]

Datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

gyro→LogicalName [writable]

Logical name of the function.

gyro→ReportFrequency [writable]

Timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

gyro→Resolution [writable]

Resolution of the measured values.

gyro→SerialNumber [read-only]

Serial number of the module, as set by the factory.

YGyro methods
gyro→calibrateFromPoints(rawValues, refValues)

Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.

gyro→clearCache()

Invalidates the cache.

gyro→describe()

Returns a short text that describes unambiguously the instance of the gyroscope in the form TYPE(NAME)=SERIAL.FUNCTIONID.

gyro→get_advMode()

Returns the measuring mode used for the advertised value pushed to the parent hub.

gyro→get_advertisedValue()

Returns the current value of the gyroscope (no more than 6 characters).

gyro→get_bandwidth()

Returns the measure update frequency, measured in Hz.

gyro→get_currentRawValue()

Returns the uncalibrated, unrounded raw value returned by the sensor, in degrees per second, as a floating point number.

gyro→get_currentValue()

Returns the current value of the angular velocity, in degrees per second, as a floating point number.

gyro→get_dataLogger()

Returns the YDatalogger object of the device hosting the sensor.

gyro→get_errorMessage()

Returns the error message of the latest error with the gyroscope.

gyro→get_errorType()

Returns the numerical error code of the latest error with the gyroscope.

gyro→get_friendlyName()

Returns a global identifier of the gyroscope in the format MODULE_NAME.FUNCTION_NAME.

gyro→get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

gyro→get_functionId()

Returns the hardware identifier of the gyroscope, without reference to the module.

gyro→get_hardwareId()

Returns the unique hardware identifier of the gyroscope in the form SERIAL.FUNCTIONID.

gyro→get_heading()

Returns the estimated heading angle, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

gyro→get_highestValue()

Returns the maximal value observed for the angular velocity since the device was started.

gyro→get_logFrequency()

Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

gyro→get_logicalName()

Returns the logical name of the gyroscope.

gyro→get_lowestValue()

Returns the minimal value observed for the angular velocity since the device was started.

gyro→get_module()

Gets the YModule object for the device on which the function is located.

gyro→get_module_async(callback, context)

Gets the YModule object for the device on which the function is located (asynchronous version).

gyro→get_pitch()

Returns the estimated pitch angle, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

gyro→get_quaternionW()

Returns the w component (real part) of the quaternion describing the device estimated orientation, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

gyro→get_quaternionX()

Returns the x component of the quaternion describing the device estimated orientation, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

gyro→get_quaternionY()

Returns the y component of the quaternion describing the device estimated orientation, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

gyro→get_quaternionZ()

Returns the x component of the quaternion describing the device estimated orientation, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

gyro→get_recordedData(startTime, endTime)

Retrieves a YDataSet object holding historical data for this sensor, for a specified time interval.

gyro→get_reportFrequency()

Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

gyro→get_resolution()

Returns the resolution of the measured values.

gyro→get_roll()

Returns the estimated roll angle, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

gyro→get_sensorState()

Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.

gyro→get_serialNumber()

Returns the serial number of the module, as set by the factory.

gyro→get_unit()

Returns the measuring unit for the angular velocity.

gyro→get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

gyro→get_xValue()

Returns the angular velocity around the X axis of the device, as a floating point number.

gyro→get_yValue()

Returns the angular velocity around the Y axis of the device, as a floating point number.

gyro→get_zValue()

Returns the angular velocity around the Z axis of the device, as a floating point number.

gyro→isOnline()

Checks if the gyroscope is currently reachable, without raising any error.

gyro→isOnline_async(callback, context)

Checks if the gyroscope is currently reachable, without raising any error (asynchronous version).

gyro→isReadOnly()

Test if the function is readOnly.

gyro→isSensorReady()

Checks if the sensor is currently able to provide an up-to-date measure.

gyro→load(msValidity)

Preloads the gyroscope cache with a specified validity duration.

gyro→loadAttribute(attrName)

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

gyro→loadCalibrationPoints(rawValues, refValues)

Retrieves error correction data points previously entered using the method calibrateFromPoints.

gyro→load_async(msValidity, callback, context)

Preloads the gyroscope cache with a specified validity duration (asynchronous version).

gyro→muteValueCallbacks()

Disables the propagation of every new advertised value to the parent hub.

gyro→nextGyro()

Continues the enumeration of gyroscopes started using yFirstGyro().

gyro→registerAnglesCallback(callback)

Registers a callback function that will be invoked each time that the estimated device orientation has changed.

gyro→registerQuaternionCallback(callback)

Registers a callback function that will be invoked each time that the estimated device orientation has changed.

gyro→registerTimedReportCallback(callback)

Registers the callback function that is invoked on every periodic timed notification.

gyro→registerValueCallback(callback)

Registers the callback function that is invoked on every change of advertised value.

gyro→set_advMode(newval)

Changes the measuring mode used for the advertised value pushed to the parent hub.

gyro→set_bandwidth(newval)

Changes the measure update frequency, measured in Hz.

gyro→set_highestValue(newval)

Changes the recorded maximal value observed.

gyro→set_logFrequency(newval)

Changes the datalogger recording frequency for this function.

gyro→set_logicalName(newval)

Changes the logical name of the gyroscope.

gyro→set_lowestValue(newval)

Changes the recorded minimal value observed.

gyro→set_reportFrequency(newval)

Changes the timed value notification frequency for this function.

gyro→set_resolution(newval)

Changes the resolution of the measured physical values.

gyro→set_userData(data)

Stores a user context provided as argument in the userData attribute of the function.

gyro→startDataLogger()

Starts the data logger on the device.

gyro→stopDataLogger()

Stops the datalogger on the device.

gyro→unmuteValueCallbacks()

Re-enables the propagation of every new advertised value to the parent hub.

gyro→wait_async(callback, context)

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

YGyro.FindGyro()
YGyro.FindGyro()
yFindGyro()YGyro::FindGyro()[YGyro FindGyro: ]yFindGyro()YGyro.FindGyro()YGyro.FindGyro()YGyro.FindGyro()YGyro.FindGyro()YGyro.FindGyro()YGyro::FindGyro()YGyro.FindGyro()YGyro.FindGyro()YGyro.FindGyro()YGyro.FindGyro()

Retrieves a gyroscope for a given identifier.

js
function yFindGyro(func)
cpp
YGyro* FindGyro(string func)
m
+(YGyro*) FindGyro: (NSString*) func
pas
TYGyro yFindGyro(func: string): TYGyro
vb
function FindGyro(ByVal func As String) As YGyro
cs
static YGyro FindGyro(string func)
java
static YGyro FindGyro(String func)
uwp
static YGyro FindGyro(string func)
py
FindGyro(func)
php
function FindGyro($func)
ts
static FindGyro(func: string): YGyro
es
static FindGyro(func)
dnp
static YGyroProxy FindGyro(string func)
cp
static YGyroProxy * FindGyro(string func)

The identifier can be specified using several formats:

This function does not require that the gyroscope is online at the time it is invoked. The returned object is nevertheless valid. Use the method YGyro.isOnline() to test if the gyroscope is indeed online at a given time. In case of ambiguity when looking for a gyroscope by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

If a call to this object's is_online() method returns FALSE although you are certain that the matching device is plugged, make sure that you did call registerHub() at application initialization time.

Parameters :

funca string that uniquely characterizes the gyroscope, for instance Y3DMK002.gyro.

Returns :

a YGyro object allowing you to drive the gyroscope.

YGyro.FindGyroInContext()
YGyro.FindGyroInContext()
YGyro.FindGyroInContext()YGyro.FindGyroInContext()YGyro.FindGyroInContext()YGyro.FindGyroInContext()

Retrieves a gyroscope for a given identifier in a YAPI context.

java
static YGyro FindGyroInContext(YAPIContext yctx, String func)
uwp
static YGyro FindGyroInContext(YAPIContext yctx, string func)
ts
static FindGyroInContext(yctx: YAPIContext, func: string): YGyro
es
static FindGyroInContext(yctx, func)

The identifier can be specified using several formats:

This function does not require that the gyroscope is online at the time it is invoked. The returned object is nevertheless valid. Use the method YGyro.isOnline() to test if the gyroscope is indeed online at a given time. In case of ambiguity when looking for a gyroscope by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

Parameters :

yctxa YAPI context
funca string that uniquely characterizes the gyroscope, for instance Y3DMK002.gyro.

Returns :

a YGyro object allowing you to drive the gyroscope.

YGyro.FirstGyro()
YGyro.FirstGyro()
yFirstGyro()YGyro::FirstGyro()[YGyro FirstGyro]yFirstGyro()YGyro.FirstGyro()YGyro.FirstGyro()YGyro.FirstGyro()YGyro.FirstGyro()YGyro.FirstGyro()YGyro::FirstGyro()YGyro.FirstGyro()YGyro.FirstGyro()

Starts the enumeration of gyroscopes currently accessible.

js
function yFirstGyro()
cpp
YGyro * FirstGyro()
m
+(YGyro*) FirstGyro
pas
TYGyro yFirstGyro(): TYGyro
vb
function FirstGyro() As YGyro
cs
static YGyro FirstGyro()
java
static YGyro FirstGyro()
uwp
static YGyro FirstGyro()
py
FirstGyro()
php
function FirstGyro()
ts
static FirstGyro(): YGyro | null
es
static FirstGyro()

Use the method YGyro.nextGyro() to iterate on next gyroscopes.

Returns :

a pointer to a YGyro object, corresponding to the first gyro currently online, or a null pointer if there are none.

YGyro.FirstGyroInContext()
YGyro.FirstGyroInContext()
YGyro.FirstGyroInContext()YGyro.FirstGyroInContext()YGyro.FirstGyroInContext()YGyro.FirstGyroInContext()

Starts the enumeration of gyroscopes currently accessible.

java
static YGyro FirstGyroInContext(YAPIContext yctx)
uwp
static YGyro FirstGyroInContext(YAPIContext yctx)
ts
static FirstGyroInContext(yctx: YAPIContext): YGyro | null
es
static FirstGyroInContext(yctx)

Use the method YGyro.nextGyro() to iterate on next gyroscopes.

Parameters :

yctxa YAPI context.

Returns :

a pointer to a YGyro object, corresponding to the first gyro currently online, or a null pointer if there are none.

YGyro.GetSimilarFunctions()
YGyro.GetSimilarFunctions()
YGyro.GetSimilarFunctions()YGyro.GetSimilarFunctions()

Enumerates all functions of type Gyro available on the devices currently reachable by the library, and returns their unique hardware ID.

dnp
static new string[] GetSimilarFunctions()
cp
static vector<string> GetSimilarFunctions()

Each of these IDs can be provided as argument to the method YGyro.FindGyro to obtain an object that can control the corresponding device.

Returns :

an array of strings, each string containing the unique hardwareId of a device function currently connected.

gyro→AdvModegyro.AdvMode

Measuring mode used for the advertised value pushed to the parent hub.

dnp
int AdvMode

Writable. Remember to call the saveToFlash() method of the module if the modification must be kept.

gyro→AdvertisedValuegyro.AdvertisedValue

Short string representing the current state of the function.

dnp
string AdvertisedValue

gyro→Bandwidthgyro.Bandwidth

Measure update frequency, measured in Hz.

dnp
int Bandwidth

Writable. When the frequency is lower, the device performs averaging. Remember to call the saveToFlash() method of the module if the modification must be kept.

gyro→FriendlyNamegyro.FriendlyName

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

dnp
string FriendlyName

The returned string uses the logical names of the module and of the function if they are defined, otherwise the serial number of the module and the hardware identifier of the function (for example: MyCustomName.relay1)

gyro→FunctionIdgyro.FunctionId

Hardware identifier of the sensor, without reference to the module.

dnp
string FunctionId

For example relay1

gyro→HardwareIdgyro.HardwareId

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

dnp
string HardwareId

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the function (for example RELAYLO1-123456.relay1).

gyro→IsOnlinegyro.IsOnline

Checks if the function is currently reachable.

dnp
bool IsOnline

If there is a cached value for the function in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the function.

gyro→LogFrequencygyro.LogFrequency

Datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

dnp
string LogFrequency

Writable. Changes the datalogger recording frequency for this function. The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (eg. "4/h"). To disable recording for this function, use the value "OFF". Note that setting the datalogger recording frequency to a greater value than the sensor native sampling frequency is useless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

gyro→LogicalNamegyro.LogicalName

Logical name of the function.

dnp
string LogicalName

Writable. You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

gyro→ReportFrequencygyro.ReportFrequency

Timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

dnp
string ReportFrequency

Writable. Changes the timed value notification frequency for this function. The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (e.g. "4/h"). To disable timed value notifications for this function, use the value "OFF". Note that setting the timed value notification frequency to a greater value than the sensor native sampling frequency is unless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

gyro→Resolutiongyro.Resolution

Resolution of the measured values.

dnp
double Resolution

The resolution corresponds to the numerical precision of the measures, which is not always the same as the actual precision of the sensor. Remember to call the saveToFlash() method of the module if the modification must be kept.

Writable. Changes the resolution of the measured physical values. The resolution corresponds to the numerical precision when displaying value. It does not change the precision of the measure itself. Remember to call the saveToFlash() method of the module if the modification must be kept.

gyro→SerialNumbergyro.SerialNumber

Serial number of the module, as set by the factory.

dnp
string SerialNumber

gyro→calibrateFromPoints()gyro.calibrateFromPoints()gyro→calibrateFromPoints()[gyro calibrateFromPoints: ]gyro.calibrateFromPoints()gyro.calibrateFromPoints()gyro.calibrateFromPoints()gyro.calibrateFromPoints()gyro.calibrateFromPoints()gyro.calibrateFromPoints()gyro→calibrateFromPoints()gyro.calibrateFromPoints()gyro.calibrateFromPoints()gyro.calibrateFromPoints()gyro.calibrateFromPoints()YGyro calibrateFromPoints

Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.

js
function calibrateFromPoints(rawValues, refValues)
cpp
int calibrateFromPoints(vector<double> rawValues,
  vector<double> refValues)
m
-(int) calibrateFromPoints: (NSMutableArray*) rawValues
  : (NSMutableArray*) refValues
pas
LongInt calibrateFromPoints(rawValues: TDoubleArray,
  refValues: TDoubleArray): LongInt
vb
procedure calibrateFromPoints(ByVal rawValues As List(Of)
cs
int calibrateFromPoints(List<double> rawValues,
  List<double> refValues)
java
int calibrateFromPoints(ArrayList<Double> rawValues,
  ArrayList<Double> refValues)
uwp
async Task<int> calibrateFromPoints(List<double> rawValues,
  List<double> refValues)
py
calibrateFromPoints(rawValues, refValues)
php
function calibrateFromPoints($rawValues, $refValues)
ts
async calibrateFromPoints(rawValues: number[], refValues: number[]): Promise<number>
es
async calibrateFromPoints(rawValues, refValues)
dnp
int calibrateFromPoints(double[] rawValues,
  double[] refValues)
cp
int calibrateFromPoints(vector<double> rawValues,
  vector<double> refValues)
cmd
YGyro target calibrateFromPoints rawValues refValues

It is possible to configure up to five correction points. Correction points must be provided in ascending order, and be in the range of the sensor. The device will automatically perform a linear interpolation of the error correction between specified points. Remember to call the saveToFlash() method of the module if the modification must be kept.

For more information on advanced capabilities to refine the calibration of sensors, please contact support@yoctopuce.com.

Parameters :

rawValuesarray of floating point numbers, corresponding to the raw values returned by the sensor for the correction points.
refValuesarray of floating point numbers, corresponding to the corrected values for the correction points.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→clearCache()gyro.clearCache()gyro→clearCache()[gyro clearCache]gyro.clearCache()gyro.clearCache()gyro.clearCache()gyro.clearCache()gyro.clearCache()gyro→clearCache()gyro.clearCache()gyro.clearCache()

Invalidates the cache.

js
function clearCache()
cpp
void clearCache()
m
-(void) clearCache
pas
clearCache()
vb
procedure clearCache()
cs
void clearCache()
java
void clearCache()
py
clearCache()
php
function clearCache()
ts
async clearCache(): Promise<void>
es
async clearCache()

Invalidates the cache of the gyroscope attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.

gyro→describe()gyro.describe()gyro→describe()[gyro describe]gyro.describe()gyro.describe()gyro.describe()gyro.describe()gyro.describe()gyro→describe()gyro.describe()gyro.describe()

Returns a short text that describes unambiguously the instance of the gyroscope in the form TYPE(NAME)=SERIAL.FUNCTIONID.

js
function describe()
cpp
string describe()
m
-(NSString*) describe
pas
string describe(): string
vb
function describe() As String
cs
string describe()
java
String describe()
py
describe()
php
function describe()
ts
async describe(): Promise<string>
es
async describe()

More precisely, TYPE is the type of the function, NAME it the name used for the first access to the function, SERIAL is the serial number of the module if the module is connected or "unresolved", and FUNCTIONID is the hardware identifier of the function if the module is connected. For example, this method returns Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1 if the module is already connected or Relay(BadCustomeName.relay1)=unresolved if the module has not yet been connected. This method does not trigger any USB or TCP transaction and can therefore be used in a debugger.

Returns :

a string that describes the gyroscope (ex: Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1)

gyro→get_advMode()
gyro→advMode()
gyro.get_advMode()gyro→get_advMode()[gyro advMode]gyro.get_advMode()gyro.get_advMode()gyro.get_advMode()gyro.get_advMode()gyro.get_advMode()gyro.get_advMode()gyro→get_advMode()gyro.get_advMode()gyro.get_advMode()gyro.get_advMode()gyro.get_advMode()YGyro get_advMode

Returns the measuring mode used for the advertised value pushed to the parent hub.

js
function get_advMode()
cpp
Y_ADVMODE_enum get_advMode()
m
-(Y_ADVMODE_enum) advMode
pas
Integer get_advMode(): Integer
vb
function get_advMode() As Integer
cs
int get_advMode()
java
int get_advMode()
uwp
async Task<int> get_advMode()
py
get_advMode()
php
function get_advMode()
ts
async get_advMode(): Promise<YSensor_AdvMode>
es
async get_advMode()
dnp
int get_advMode()
cp
int get_advMode()
cmd
YGyro target get_advMode

Returns :

a value among YGyro.ADVMODE_IMMEDIATE, YGyro.ADVMODE_PERIOD_AVG, YGyro.ADVMODE_PERIOD_MIN and YGyro.ADVMODE_PERIOD_MAX corresponding to the measuring mode used for the advertised value pushed to the parent hub

On failure, throws an exception or returns YGyro.ADVMODE_INVALID.

gyro→get_advertisedValue()
gyro→advertisedValue()
gyro.get_advertisedValue()gyro→get_advertisedValue()[gyro advertisedValue]gyro.get_advertisedValue()gyro.get_advertisedValue()gyro.get_advertisedValue()gyro.get_advertisedValue()gyro.get_advertisedValue()gyro.get_advertisedValue()gyro→get_advertisedValue()gyro.get_advertisedValue()gyro.get_advertisedValue()gyro.get_advertisedValue()gyro.get_advertisedValue()YGyro get_advertisedValue

Returns the current value of the gyroscope (no more than 6 characters).

js
function get_advertisedValue()
cpp
string get_advertisedValue()
m
-(NSString*) advertisedValue
pas
string get_advertisedValue(): string
vb
function get_advertisedValue() As String
cs
string get_advertisedValue()
java
String get_advertisedValue()
uwp
async Task<string> get_advertisedValue()
py
get_advertisedValue()
php
function get_advertisedValue()
ts
async get_advertisedValue(): Promise<string>
es
async get_advertisedValue()
dnp
string get_advertisedValue()
cp
string get_advertisedValue()
cmd
YGyro target get_advertisedValue

Returns :

a string corresponding to the current value of the gyroscope (no more than 6 characters).

On failure, throws an exception or returns YGyro.ADVERTISEDVALUE_INVALID.

gyro→get_bandwidth()
gyro→bandwidth()
gyro.get_bandwidth()gyro→get_bandwidth()[gyro bandwidth]gyro.get_bandwidth()gyro.get_bandwidth()gyro.get_bandwidth()gyro.get_bandwidth()gyro.get_bandwidth()gyro.get_bandwidth()gyro→get_bandwidth()gyro.get_bandwidth()gyro.get_bandwidth()gyro.get_bandwidth()gyro.get_bandwidth()YGyro get_bandwidth

Returns the measure update frequency, measured in Hz.

js
function get_bandwidth()
cpp
int get_bandwidth()
m
-(int) bandwidth
pas
LongInt get_bandwidth(): LongInt
vb
function get_bandwidth() As Integer
cs
int get_bandwidth()
java
int get_bandwidth()
uwp
async Task<int> get_bandwidth()
py
get_bandwidth()
php
function get_bandwidth()
ts
async get_bandwidth(): Promise<number>
es
async get_bandwidth()
dnp
int get_bandwidth()
cp
int get_bandwidth()
cmd
YGyro target get_bandwidth

Returns :

an integer corresponding to the measure update frequency, measured in Hz

On failure, throws an exception or returns YGyro.BANDWIDTH_INVALID.

gyro→get_currentRawValue()
gyro→currentRawValue()
gyro.get_currentRawValue()gyro→get_currentRawValue()[gyro currentRawValue]gyro.get_currentRawValue()gyro.get_currentRawValue()gyro.get_currentRawValue()gyro.get_currentRawValue()gyro.get_currentRawValue()gyro.get_currentRawValue()gyro→get_currentRawValue()gyro.get_currentRawValue()gyro.get_currentRawValue()gyro.get_currentRawValue()gyro.get_currentRawValue()YGyro get_currentRawValue

Returns the uncalibrated, unrounded raw value returned by the sensor, in degrees per second, as a floating point number.

js
function get_currentRawValue()
cpp
double get_currentRawValue()
m
-(double) currentRawValue
pas
double get_currentRawValue(): double
vb
function get_currentRawValue() As Double
cs
double get_currentRawValue()
java
double get_currentRawValue()
uwp
async Task<double> get_currentRawValue()
py
get_currentRawValue()
php
function get_currentRawValue()
ts
async get_currentRawValue(): Promise<number>
es
async get_currentRawValue()
dnp
double get_currentRawValue()
cp
double get_currentRawValue()
cmd
YGyro target get_currentRawValue

Returns :

a floating point number corresponding to the uncalibrated, unrounded raw value returned by the sensor, in degrees per second, as a floating point number

On failure, throws an exception or returns YGyro.CURRENTRAWVALUE_INVALID.

gyro→get_currentValue()
gyro→currentValue()
gyro.get_currentValue()gyro→get_currentValue()[gyro currentValue]gyro.get_currentValue()gyro.get_currentValue()gyro.get_currentValue()gyro.get_currentValue()gyro.get_currentValue()gyro.get_currentValue()gyro→get_currentValue()gyro.get_currentValue()gyro.get_currentValue()gyro.get_currentValue()gyro.get_currentValue()YGyro get_currentValue

Returns the current value of the angular velocity, in degrees per second, as a floating point number.

js
function get_currentValue()
cpp
double get_currentValue()
m
-(double) currentValue
pas
double get_currentValue(): double
vb
function get_currentValue() As Double
cs
double get_currentValue()
java
double get_currentValue()
uwp
async Task<double> get_currentValue()
py
get_currentValue()
php
function get_currentValue()
ts
async get_currentValue(): Promise<number>
es
async get_currentValue()
dnp
double get_currentValue()
cp
double get_currentValue()
cmd
YGyro target get_currentValue

Note that a get_currentValue() call will *not* start a measure in the device, it will just return the last measure that occurred in the device. Indeed, internally, each Yoctopuce devices is continuously making measurements at a hardware specific frequency.

If continuously calling get_currentValue() leads you to performances issues, then you might consider to switch to callback programming model. Check the "advanced programming" chapter in in your device user manual for more information.

Returns :

a floating point number corresponding to the current value of the angular velocity, in degrees per second, as a floating point number

On failure, throws an exception or returns YGyro.CURRENTVALUE_INVALID.

gyro→get_dataLogger()
gyro→dataLogger()
gyro.get_dataLogger()gyro→get_dataLogger()[gyro dataLogger]gyro.get_dataLogger()gyro.get_dataLogger()gyro.get_dataLogger()gyro.get_dataLogger()gyro.get_dataLogger()gyro.get_dataLogger()gyro→get_dataLogger()gyro.get_dataLogger()gyro.get_dataLogger()gyro.get_dataLogger()gyro.get_dataLogger()

Returns the YDatalogger object of the device hosting the sensor.

js
function get_dataLogger()
cpp
YDataLogger* get_dataLogger()
m
-(YDataLogger*) dataLogger
pas
TYDataLogger get_dataLogger(): TYDataLogger
vb
function get_dataLogger() As YDataLogger
cs
YDataLogger get_dataLogger()
java
YDataLogger get_dataLogger()
uwp
async Task<YDataLogger> get_dataLogger()
py
get_dataLogger()
php
function get_dataLogger()
ts
async get_dataLogger(): Promise<YDataLogger | null>
es
async get_dataLogger()
dnp
YDataLoggerProxy get_dataLogger()
cp
YDataLoggerProxy* get_dataLogger()

This method returns an object that can control global parameters of the data logger. The returned object should not be freed.

Returns :

an YDatalogger object, or null on error.

gyro→get_errorMessage()
gyro→errorMessage()
gyro.get_errorMessage()gyro→get_errorMessage()[gyro errorMessage]gyro.get_errorMessage()gyro.get_errorMessage()gyro.get_errorMessage()gyro.get_errorMessage()gyro.get_errorMessage()gyro→get_errorMessage()gyro.get_errorMessage()gyro.get_errorMessage()

Returns the error message of the latest error with the gyroscope.

js
function get_errorMessage()
cpp
string get_errorMessage()
m
-(NSString*) errorMessage
pas
string get_errorMessage(): string
vb
function get_errorMessage() As String
cs
string get_errorMessage()
java
String get_errorMessage()
py
get_errorMessage()
php
function get_errorMessage()
ts
get_errorMessage(): string
es
get_errorMessage()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a string corresponding to the latest error message that occured while using the gyroscope object

gyro→get_errorType()
gyro→errorType()
gyro.get_errorType()gyro→get_errorType()[gyro errorType]gyro.get_errorType()gyro.get_errorType()gyro.get_errorType()gyro.get_errorType()gyro.get_errorType()gyro→get_errorType()gyro.get_errorType()gyro.get_errorType()

Returns the numerical error code of the latest error with the gyroscope.

js
function get_errorType()
cpp
YRETCODE get_errorType()
m
-(YRETCODE) errorType
pas
YRETCODE get_errorType(): YRETCODE
vb
function get_errorType() As YRETCODE
cs
YRETCODE get_errorType()
java
int get_errorType()
py
get_errorType()
php
function get_errorType()
ts
get_errorType(): number
es
get_errorType()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a number corresponding to the code of the latest error that occurred while using the gyroscope object

gyro→get_friendlyName()
gyro→friendlyName()
gyro.get_friendlyName()gyro→get_friendlyName()[gyro friendlyName]gyro.get_friendlyName()gyro.get_friendlyName()gyro.get_friendlyName()gyro→get_friendlyName()gyro.get_friendlyName()gyro.get_friendlyName()gyro.get_friendlyName()gyro.get_friendlyName()

Returns a global identifier of the gyroscope in the format MODULE_NAME.FUNCTION_NAME.

js
function get_friendlyName()
cpp
string get_friendlyName()
m
-(NSString*) friendlyName
cs
string get_friendlyName()
java
String get_friendlyName()
py
get_friendlyName()
php
function get_friendlyName()
ts
async get_friendlyName(): Promise<string>
es
async get_friendlyName()
dnp
string get_friendlyName()
cp
string get_friendlyName()

The returned string uses the logical names of the module and of the gyroscope if they are defined, otherwise the serial number of the module and the hardware identifier of the gyroscope (for example: MyCustomName.relay1)

Returns :

a string that uniquely identifies the gyroscope using logical names (ex: MyCustomName.relay1)

On failure, throws an exception or returns YGyro.FRIENDLYNAME_INVALID.

gyro→get_functionDescriptor()
gyro→functionDescriptor()
gyro.get_functionDescriptor()gyro→get_functionDescriptor()[gyro functionDescriptor]gyro.get_functionDescriptor()gyro.get_functionDescriptor()gyro.get_functionDescriptor()gyro.get_functionDescriptor()gyro.get_functionDescriptor()gyro→get_functionDescriptor()gyro.get_functionDescriptor()gyro.get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

js
function get_functionDescriptor()
cpp
YFUN_DESCR get_functionDescriptor()
m
-(YFUN_DESCR) functionDescriptor
pas
YFUN_DESCR get_functionDescriptor(): YFUN_DESCR
vb
function get_functionDescriptor() As YFUN_DESCR
cs
YFUN_DESCR get_functionDescriptor()
java
String get_functionDescriptor()
py
get_functionDescriptor()
php
function get_functionDescriptor()
ts
async get_functionDescriptor(): Promise<string>
es
async get_functionDescriptor()

This identifier can be used to test if two instances of YFunction reference the same physical function on the same physical device.

Returns :

an identifier of type YFUN_DESCR.

If the function has never been contacted, the returned value is Y$CLASSNAME$.FUNCTIONDESCRIPTOR_INVALID.

gyro→get_functionId()
gyro→functionId()
gyro.get_functionId()gyro→get_functionId()[gyro functionId]gyro.get_functionId()gyro.get_functionId()gyro.get_functionId()gyro.get_functionId()gyro→get_functionId()gyro.get_functionId()gyro.get_functionId()gyro.get_functionId()gyro.get_functionId()

Returns the hardware identifier of the gyroscope, without reference to the module.

js
function get_functionId()
cpp
string get_functionId()
m
-(NSString*) functionId
vb
function get_functionId() As String
cs
string get_functionId()
java
String get_functionId()
py
get_functionId()
php
function get_functionId()
ts
async get_functionId(): Promise<string>
es
async get_functionId()
dnp
string get_functionId()
cp
string get_functionId()

For example relay1

Returns :

a string that identifies the gyroscope (ex: relay1)

On failure, throws an exception or returns YGyro.FUNCTIONID_INVALID.

gyro→get_hardwareId()
gyro→hardwareId()
gyro.get_hardwareId()gyro→get_hardwareId()[gyro hardwareId]gyro.get_hardwareId()gyro.get_hardwareId()gyro.get_hardwareId()gyro.get_hardwareId()gyro→get_hardwareId()gyro.get_hardwareId()gyro.get_hardwareId()gyro.get_hardwareId()gyro.get_hardwareId()

Returns the unique hardware identifier of the gyroscope in the form SERIAL.FUNCTIONID.

js
function get_hardwareId()
cpp
string get_hardwareId()
m
-(NSString*) hardwareId
vb
function get_hardwareId() As String
cs
string get_hardwareId()
java
String get_hardwareId()
py
get_hardwareId()
php
function get_hardwareId()
ts
async get_hardwareId(): Promise<string>
es
async get_hardwareId()
dnp
string get_hardwareId()
cp
string get_hardwareId()

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the gyroscope (for example RELAYLO1-123456.relay1).

Returns :

a string that uniquely identifies the gyroscope (ex: RELAYLO1-123456.relay1)

On failure, throws an exception or returns YGyro.HARDWAREID_INVALID.

gyro→get_heading()
gyro→heading()
gyro.get_heading()gyro→get_heading()[gyro heading]gyro.get_heading()gyro.get_heading()gyro.get_heading()gyro.get_heading()gyro.get_heading()gyro.get_heading()gyro→get_heading()gyro.get_heading()gyro.get_heading()gyro.get_heading()gyro.get_heading()YGyro get_heading

Returns the estimated heading angle, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

js
function get_heading()
cpp
double get_heading()
m
-(double) heading
pas
double get_heading(): double
vb
function get_heading() As Double
cs
double get_heading()
java
double get_heading()
uwp
async Task<double> get_heading()
py
get_heading()
php
function get_heading()
ts
async get_heading(): Promise<number>
es
async get_heading()
dnp
double get_heading()
cp
double get_heading()
cmd
YGyro target get_heading

The axis corresponding to the heading can be mapped to any of the device X, Y or Z physical directions using methods of the class YRefFrame.

Returns :

a floating-point number corresponding to heading in degrees, between 0 and 360.

gyro→get_highestValue()
gyro→highestValue()
gyro.get_highestValue()gyro→get_highestValue()[gyro highestValue]gyro.get_highestValue()gyro.get_highestValue()gyro.get_highestValue()gyro.get_highestValue()gyro.get_highestValue()gyro.get_highestValue()gyro→get_highestValue()gyro.get_highestValue()gyro.get_highestValue()gyro.get_highestValue()gyro.get_highestValue()YGyro get_highestValue

Returns the maximal value observed for the angular velocity since the device was started.

js
function get_highestValue()
cpp
double get_highestValue()
m
-(double) highestValue
pas
double get_highestValue(): double
vb
function get_highestValue() As Double
cs
double get_highestValue()
java
double get_highestValue()
uwp
async Task<double> get_highestValue()
py
get_highestValue()
php
function get_highestValue()
ts
async get_highestValue(): Promise<number>
es
async get_highestValue()
dnp
double get_highestValue()
cp
double get_highestValue()
cmd
YGyro target get_highestValue

Can be reset to an arbitrary value thanks to set_highestValue().

Returns :

a floating point number corresponding to the maximal value observed for the angular velocity since the device was started

On failure, throws an exception or returns YGyro.HIGHESTVALUE_INVALID.

gyro→get_logFrequency()
gyro→logFrequency()
gyro.get_logFrequency()gyro→get_logFrequency()[gyro logFrequency]gyro.get_logFrequency()gyro.get_logFrequency()gyro.get_logFrequency()gyro.get_logFrequency()gyro.get_logFrequency()gyro.get_logFrequency()gyro→get_logFrequency()gyro.get_logFrequency()gyro.get_logFrequency()gyro.get_logFrequency()gyro.get_logFrequency()YGyro get_logFrequency

Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.

js
function get_logFrequency()
cpp
string get_logFrequency()
m
-(NSString*) logFrequency
pas
string get_logFrequency(): string
vb
function get_logFrequency() As String
cs
string get_logFrequency()
java
String get_logFrequency()
uwp
async Task<string> get_logFrequency()
py
get_logFrequency()
php
function get_logFrequency()
ts
async get_logFrequency(): Promise<string>
es
async get_logFrequency()
dnp
string get_logFrequency()
cp
string get_logFrequency()
cmd
YGyro target get_logFrequency

Returns :

a string corresponding to the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory

On failure, throws an exception or returns YGyro.LOGFREQUENCY_INVALID.

gyro→get_logicalName()
gyro→logicalName()
gyro.get_logicalName()gyro→get_logicalName()[gyro logicalName]gyro.get_logicalName()gyro.get_logicalName()gyro.get_logicalName()gyro.get_logicalName()gyro.get_logicalName()gyro.get_logicalName()gyro→get_logicalName()gyro.get_logicalName()gyro.get_logicalName()gyro.get_logicalName()gyro.get_logicalName()YGyro get_logicalName

Returns the logical name of the gyroscope.

js
function get_logicalName()
cpp
string get_logicalName()
m
-(NSString*) logicalName
pas
string get_logicalName(): string
vb
function get_logicalName() As String
cs
string get_logicalName()
java
String get_logicalName()
uwp
async Task<string> get_logicalName()
py
get_logicalName()
php
function get_logicalName()
ts
async get_logicalName(): Promise<string>
es
async get_logicalName()
dnp
string get_logicalName()
cp
string get_logicalName()
cmd
YGyro target get_logicalName

Returns :

a string corresponding to the logical name of the gyroscope.

On failure, throws an exception or returns YGyro.LOGICALNAME_INVALID.

gyro→get_lowestValue()
gyro→lowestValue()
gyro.get_lowestValue()gyro→get_lowestValue()[gyro lowestValue]gyro.get_lowestValue()gyro.get_lowestValue()gyro.get_lowestValue()gyro.get_lowestValue()gyro.get_lowestValue()gyro.get_lowestValue()gyro→get_lowestValue()gyro.get_lowestValue()gyro.get_lowestValue()gyro.get_lowestValue()gyro.get_lowestValue()YGyro get_lowestValue

Returns the minimal value observed for the angular velocity since the device was started.

js
function get_lowestValue()
cpp
double get_lowestValue()
m
-(double) lowestValue
pas
double get_lowestValue(): double
vb
function get_lowestValue() As Double
cs
double get_lowestValue()
java
double get_lowestValue()
uwp
async Task<double> get_lowestValue()
py
get_lowestValue()
php
function get_lowestValue()
ts
async get_lowestValue(): Promise<number>
es
async get_lowestValue()
dnp
double get_lowestValue()
cp
double get_lowestValue()
cmd
YGyro target get_lowestValue

Can be reset to an arbitrary value thanks to set_lowestValue().

Returns :

a floating point number corresponding to the minimal value observed for the angular velocity since the device was started

On failure, throws an exception or returns YGyro.LOWESTVALUE_INVALID.

gyro→get_module()
gyro→module()
gyro.get_module()gyro→get_module()[gyro module]gyro.get_module()gyro.get_module()gyro.get_module()gyro.get_module()gyro.get_module()gyro→get_module()gyro.get_module()gyro.get_module()gyro.get_module()gyro.get_module()

Gets the YModule object for the device on which the function is located.

js
function get_module()
cpp
YModule * get_module()
m
-(YModule*) module
pas
TYModule get_module(): TYModule
vb
function get_module() As YModule
cs
YModule get_module()
java
YModule get_module()
py
get_module()
php
function get_module()
ts
async get_module(): Promise<YModule>
es
async get_module()
dnp
YModuleProxy get_module()
cp
YModuleProxy * get_module()

If the function cannot be located on any module, the returned instance of YModule is not shown as on-line.

Returns :

an instance of YModule

gyro→get_module_async()
gyro→module_async()
gyro.get_module_async()

Gets the YModule object for the device on which the function is located (asynchronous version).

js
function get_module_async(callback, context)

If the function cannot be located on any module, the returned YModule object does not show as on-line.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking Firefox JavaScript VM that does not implement context switching during blocking I/O calls. See the documentation section on asynchronous JavasSript calls for more details.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the requested YModule object
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

gyro→get_pitch()
gyro→pitch()
gyro.get_pitch()gyro→get_pitch()[gyro pitch]gyro.get_pitch()gyro.get_pitch()gyro.get_pitch()gyro.get_pitch()gyro.get_pitch()gyro.get_pitch()gyro→get_pitch()gyro.get_pitch()gyro.get_pitch()gyro.get_pitch()gyro.get_pitch()YGyro get_pitch

Returns the estimated pitch angle, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

js
function get_pitch()
cpp
double get_pitch()
m
-(double) pitch
pas
double get_pitch(): double
vb
function get_pitch() As Double
cs
double get_pitch()
java
double get_pitch()
uwp
async Task<double> get_pitch()
py
get_pitch()
php
function get_pitch()
ts
async get_pitch(): Promise<number>
es
async get_pitch()
dnp
double get_pitch()
cp
double get_pitch()
cmd
YGyro target get_pitch

The axis corresponding to the pitch angle can be mapped to any of the device X, Y or Z physical directions using methods of the class YRefFrame.

Returns :

a floating-point number corresponding to pitch angle in degrees, between -90 and +90.

gyro→get_quaternionW()
gyro→quaternionW()
gyro.get_quaternionW()gyro→get_quaternionW()[gyro quaternionW]gyro.get_quaternionW()gyro.get_quaternionW()gyro.get_quaternionW()gyro.get_quaternionW()gyro.get_quaternionW()gyro.get_quaternionW()gyro→get_quaternionW()gyro.get_quaternionW()gyro.get_quaternionW()gyro.get_quaternionW()gyro.get_quaternionW()YGyro get_quaternionW

Returns the w component (real part) of the quaternion describing the device estimated orientation, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

js
function get_quaternionW()
cpp
double get_quaternionW()
m
-(double) quaternionW
pas
double get_quaternionW(): double
vb
function get_quaternionW() As Double
cs
double get_quaternionW()
java
double get_quaternionW()
uwp
async Task<double> get_quaternionW()
py
get_quaternionW()
php
function get_quaternionW()
ts
async get_quaternionW(): Promise<number>
es
async get_quaternionW()
dnp
double get_quaternionW()
cp
double get_quaternionW()
cmd
YGyro target get_quaternionW

Returns :

a floating-point number corresponding to the w component of the quaternion.

gyro→get_quaternionX()
gyro→quaternionX()
gyro.get_quaternionX()gyro→get_quaternionX()[gyro quaternionX]gyro.get_quaternionX()gyro.get_quaternionX()gyro.get_quaternionX()gyro.get_quaternionX()gyro.get_quaternionX()gyro.get_quaternionX()gyro→get_quaternionX()gyro.get_quaternionX()gyro.get_quaternionX()gyro.get_quaternionX()gyro.get_quaternionX()YGyro get_quaternionX

Returns the x component of the quaternion describing the device estimated orientation, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

js
function get_quaternionX()
cpp
double get_quaternionX()
m
-(double) quaternionX
pas
double get_quaternionX(): double
vb
function get_quaternionX() As Double
cs
double get_quaternionX()
java
double get_quaternionX()
uwp
async Task<double> get_quaternionX()
py
get_quaternionX()
php
function get_quaternionX()
ts
async get_quaternionX(): Promise<number>
es
async get_quaternionX()
dnp
double get_quaternionX()
cp
double get_quaternionX()
cmd
YGyro target get_quaternionX

The x component is mostly correlated with rotations on the roll axis.

Returns :

a floating-point number corresponding to the x component of the quaternion.

gyro→get_quaternionY()
gyro→quaternionY()
gyro.get_quaternionY()gyro→get_quaternionY()[gyro quaternionY]gyro.get_quaternionY()gyro.get_quaternionY()gyro.get_quaternionY()gyro.get_quaternionY()gyro.get_quaternionY()gyro.get_quaternionY()gyro→get_quaternionY()gyro.get_quaternionY()gyro.get_quaternionY()gyro.get_quaternionY()gyro.get_quaternionY()YGyro get_quaternionY

Returns the y component of the quaternion describing the device estimated orientation, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

js
function get_quaternionY()
cpp
double get_quaternionY()
m
-(double) quaternionY
pas
double get_quaternionY(): double
vb
function get_quaternionY() As Double
cs
double get_quaternionY()
java
double get_quaternionY()
uwp
async Task<double> get_quaternionY()
py
get_quaternionY()
php
function get_quaternionY()
ts
async get_quaternionY(): Promise<number>
es
async get_quaternionY()
dnp
double get_quaternionY()
cp
double get_quaternionY()
cmd
YGyro target get_quaternionY

The y component is mostly correlated with rotations on the pitch axis.

Returns :

a floating-point number corresponding to the y component of the quaternion.

gyro→get_quaternionZ()
gyro→quaternionZ()
gyro.get_quaternionZ()gyro→get_quaternionZ()[gyro quaternionZ]gyro.get_quaternionZ()gyro.get_quaternionZ()gyro.get_quaternionZ()gyro.get_quaternionZ()gyro.get_quaternionZ()gyro.get_quaternionZ()gyro→get_quaternionZ()gyro.get_quaternionZ()gyro.get_quaternionZ()gyro.get_quaternionZ()gyro.get_quaternionZ()YGyro get_quaternionZ

Returns the x component of the quaternion describing the device estimated orientation, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

js
function get_quaternionZ()
cpp
double get_quaternionZ()
m
-(double) quaternionZ
pas
double get_quaternionZ(): double
vb
function get_quaternionZ() As Double
cs
double get_quaternionZ()
java
double get_quaternionZ()
uwp
async Task<double> get_quaternionZ()
py
get_quaternionZ()
php
function get_quaternionZ()
ts
async get_quaternionZ(): Promise<number>
es
async get_quaternionZ()
dnp
double get_quaternionZ()
cp
double get_quaternionZ()
cmd
YGyro target get_quaternionZ

The x component is mostly correlated with changes of heading.

Returns :

a floating-point number corresponding to the z component of the quaternion.

gyro→get_recordedData()
gyro→recordedData()
gyro.get_recordedData()gyro→get_recordedData()[gyro recordedData: ]gyro.get_recordedData()gyro.get_recordedData()gyro.get_recordedData()gyro.get_recordedData()gyro.get_recordedData()gyro.get_recordedData()gyro→get_recordedData()gyro.get_recordedData()gyro.get_recordedData()gyro.get_recordedData()gyro.get_recordedData()YGyro get_recordedData

Retrieves a YDataSet object holding historical data for this sensor, for a specified time interval.

js
function get_recordedData(startTime, endTime)
cpp
YDataSet get_recordedData(double startTime, double endTime)
m
-(YDataSet*) recordedData: (double) startTime
  : (double) endTime
pas
TYDataSet get_recordedData(startTime: double, endTime: double): TYDataSet
vb
function get_recordedData(ByVal startTime As Double,
  ByVal endTime As Double) As YDataSet
cs
YDataSet get_recordedData(double startTime, double endTime)
java
YDataSet get_recordedData(double startTime, double endTime)
uwp
async Task<YDataSet> get_recordedData(double startTime,
  double endTime)
py
get_recordedData(startTime, endTime)
php
function get_recordedData($startTime, $endTime)
ts
async get_recordedData(startTime: number, endTime: number): Promise<YDataSet>
es
async get_recordedData(startTime, endTime)
dnp
YDataSetProxy get_recordedData(double startTime,
  double endTime)
cp
YDataSetProxy* get_recordedData(double startTime,
  double endTime)
cmd
YGyro target get_recordedData startTime endTime

The measures will be retrieved from the data logger, which must have been turned on at the desired time. See the documentation of the YDataSet class for information on how to get an overview of the recorded data, and how to load progressively a large set of measures from the data logger.

This function only works if the device uses a recent firmware, as YDataSet objects are not supported by firmwares older than version 13000.

Parameters :

startTimethe start of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without initial limit.
endTimethe end of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without ending limit.

Returns :

an instance of YDataSet, providing access to historical data. Past measures can be loaded progressively using methods from the YDataSet object.

gyro→get_reportFrequency()
gyro→reportFrequency()
gyro.get_reportFrequency()gyro→get_reportFrequency()[gyro reportFrequency]gyro.get_reportFrequency()gyro.get_reportFrequency()gyro.get_reportFrequency()gyro.get_reportFrequency()gyro.get_reportFrequency()gyro.get_reportFrequency()gyro→get_reportFrequency()gyro.get_reportFrequency()gyro.get_reportFrequency()gyro.get_reportFrequency()gyro.get_reportFrequency()YGyro get_reportFrequency

Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.

js
function get_reportFrequency()
cpp
string get_reportFrequency()
m
-(NSString*) reportFrequency
pas
string get_reportFrequency(): string
vb
function get_reportFrequency() As String
cs
string get_reportFrequency()
java
String get_reportFrequency()
uwp
async Task<string> get_reportFrequency()
py
get_reportFrequency()
php
function get_reportFrequency()
ts
async get_reportFrequency(): Promise<string>
es
async get_reportFrequency()
dnp
string get_reportFrequency()
cp
string get_reportFrequency()
cmd
YGyro target get_reportFrequency

Returns :

a string corresponding to the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function

On failure, throws an exception or returns YGyro.REPORTFREQUENCY_INVALID.

gyro→get_resolution()
gyro→resolution()
gyro.get_resolution()gyro→get_resolution()[gyro resolution]gyro.get_resolution()gyro.get_resolution()gyro.get_resolution()gyro.get_resolution()gyro.get_resolution()gyro.get_resolution()gyro→get_resolution()gyro.get_resolution()gyro.get_resolution()gyro.get_resolution()gyro.get_resolution()YGyro get_resolution

Returns the resolution of the measured values.

js
function get_resolution()
cpp
double get_resolution()
m
-(double) resolution
pas
double get_resolution(): double
vb
function get_resolution() As Double
cs
double get_resolution()
java
double get_resolution()
uwp
async Task<double> get_resolution()
py
get_resolution()
php
function get_resolution()
ts
async get_resolution(): Promise<number>
es
async get_resolution()
dnp
double get_resolution()
cp
double get_resolution()
cmd
YGyro target get_resolution

The resolution corresponds to the numerical precision of the measures, which is not always the same as the actual precision of the sensor. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

a floating point number corresponding to the resolution of the measured values

On failure, throws an exception or returns YGyro.RESOLUTION_INVALID.

gyro→get_roll()
gyro→roll()
gyro.get_roll()gyro→get_roll()[gyro roll]gyro.get_roll()gyro.get_roll()gyro.get_roll()gyro.get_roll()gyro.get_roll()gyro.get_roll()gyro→get_roll()gyro.get_roll()gyro.get_roll()gyro.get_roll()gyro.get_roll()YGyro get_roll

Returns the estimated roll angle, based on the integration of gyroscopic measures combined with acceleration and magnetic field measurements.

js
function get_roll()
cpp
double get_roll()
m
-(double) roll
pas
double get_roll(): double
vb
function get_roll() As Double
cs
double get_roll()
java
double get_roll()
uwp
async Task<double> get_roll()
py
get_roll()
php
function get_roll()
ts
async get_roll(): Promise<number>
es
async get_roll()
dnp
double get_roll()
cp
double get_roll()
cmd
YGyro target get_roll

The axis corresponding to the roll angle can be mapped to any of the device X, Y or Z physical directions using methods of the class YRefFrame.

Returns :

a floating-point number corresponding to roll angle in degrees, between -180 and +180.

gyro→get_sensorState()
gyro→sensorState()
gyro.get_sensorState()gyro→get_sensorState()[gyro sensorState]gyro.get_sensorState()gyro.get_sensorState()gyro.get_sensorState()gyro.get_sensorState()gyro.get_sensorState()gyro.get_sensorState()gyro→get_sensorState()gyro.get_sensorState()gyro.get_sensorState()gyro.get_sensorState()gyro.get_sensorState()YGyro get_sensorState

Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.

js
function get_sensorState()
cpp
int get_sensorState()
m
-(int) sensorState
pas
LongInt get_sensorState(): LongInt
vb
function get_sensorState() As Integer
cs
int get_sensorState()
java
int get_sensorState()
uwp
async Task<int> get_sensorState()
py
get_sensorState()
php
function get_sensorState()
ts
async get_sensorState(): Promise<number>
es
async get_sensorState()
dnp
int get_sensorState()
cp
int get_sensorState()
cmd
YGyro target get_sensorState

Returns :

an integer corresponding to the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now

On failure, throws an exception or returns YGyro.SENSORSTATE_INVALID.

gyro→get_serialNumber()
gyro→serialNumber()
gyro.get_serialNumber()gyro→get_serialNumber()[gyro serialNumber]gyro.get_serialNumber()gyro.get_serialNumber()gyro.get_serialNumber()gyro.get_serialNumber()gyro.get_serialNumber()gyro.get_serialNumber()gyro→get_serialNumber()gyro.get_serialNumber()gyro.get_serialNumber()gyro.get_serialNumber()gyro.get_serialNumber()YGyro get_serialNumber

Returns the serial number of the module, as set by the factory.

js
function get_serialNumber()
cpp
string get_serialNumber()
m
-(NSString*) serialNumber
pas
string get_serialNumber(): string
vb
function get_serialNumber() As String
cs
string get_serialNumber()
java
String get_serialNumber()
uwp
async Task<string> get_serialNumber()
py
get_serialNumber()
php
function get_serialNumber()
ts
async get_serialNumber(): Promise<string>
es
async get_serialNumber()
dnp
string get_serialNumber()
cp
string get_serialNumber()
cmd
YGyro target get_serialNumber

Returns :

a string corresponding to the serial number of the module, as set by the factory.

On failure, throws an exception or returns YFunction.SERIALNUMBER_INVALID.

gyro→get_unit()
gyro→unit()
gyro.get_unit()gyro→get_unit()[gyro unit]gyro.get_unit()gyro.get_unit()gyro.get_unit()gyro.get_unit()gyro.get_unit()gyro.get_unit()gyro→get_unit()gyro.get_unit()gyro.get_unit()gyro.get_unit()gyro.get_unit()YGyro get_unit

Returns the measuring unit for the angular velocity.

js
function get_unit()
cpp
string get_unit()
m
-(NSString*) unit
pas
string get_unit(): string
vb
function get_unit() As String
cs
string get_unit()
java
String get_unit()
uwp
async Task<string> get_unit()
py
get_unit()
php
function get_unit()
ts
async get_unit(): Promise<string>
es
async get_unit()
dnp
string get_unit()
cp
string get_unit()
cmd
YGyro target get_unit

Returns :

a string corresponding to the measuring unit for the angular velocity

On failure, throws an exception or returns YGyro.UNIT_INVALID.

gyro→get_userData()
gyro→userData()
gyro.get_userData()gyro→get_userData()[gyro userData]gyro.get_userData()gyro.get_userData()gyro.get_userData()gyro.get_userData()gyro.get_userData()gyro→get_userData()gyro.get_userData()gyro.get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

js
function get_userData()
cpp
void * get_userData()
m
-(id) userData
pas
Tobject get_userData(): Tobject
vb
function get_userData() As Object
cs
object get_userData()
java
Object get_userData()
py
get_userData()
php
function get_userData()
ts
async get_userData(): Promise<object|null>
es
async get_userData()

This attribute is never touched directly by the API, and is at disposal of the caller to store a context.

Returns :

the object stored previously by the caller.

gyro→get_xValue()
gyro→xValue()
gyro.get_xValue()gyro→get_xValue()[gyro xValue]gyro.get_xValue()gyro.get_xValue()gyro.get_xValue()gyro.get_xValue()gyro.get_xValue()gyro.get_xValue()gyro→get_xValue()gyro.get_xValue()gyro.get_xValue()gyro.get_xValue()gyro.get_xValue()YGyro get_xValue

Returns the angular velocity around the X axis of the device, as a floating point number.

js
function get_xValue()
cpp
double get_xValue()
m
-(double) xValue
pas
double get_xValue(): double
vb
function get_xValue() As Double
cs
double get_xValue()
java
double get_xValue()
uwp
async Task<double> get_xValue()
py
get_xValue()
php
function get_xValue()
ts
async get_xValue(): Promise<number>
es
async get_xValue()
dnp
double get_xValue()
cp
double get_xValue()
cmd
YGyro target get_xValue

Returns :

a floating point number corresponding to the angular velocity around the X axis of the device, as a floating point number

On failure, throws an exception or returns YGyro.XVALUE_INVALID.

gyro→get_yValue()
gyro→yValue()
gyro.get_yValue()gyro→get_yValue()[gyro yValue]gyro.get_yValue()gyro.get_yValue()gyro.get_yValue()gyro.get_yValue()gyro.get_yValue()gyro.get_yValue()gyro→get_yValue()gyro.get_yValue()gyro.get_yValue()gyro.get_yValue()gyro.get_yValue()YGyro get_yValue

Returns the angular velocity around the Y axis of the device, as a floating point number.

js
function get_yValue()
cpp
double get_yValue()
m
-(double) yValue
pas
double get_yValue(): double
vb
function get_yValue() As Double
cs
double get_yValue()
java
double get_yValue()
uwp
async Task<double> get_yValue()
py
get_yValue()
php
function get_yValue()
ts
async get_yValue(): Promise<number>
es
async get_yValue()
dnp
double get_yValue()
cp
double get_yValue()
cmd
YGyro target get_yValue

Returns :

a floating point number corresponding to the angular velocity around the Y axis of the device, as a floating point number

On failure, throws an exception or returns YGyro.YVALUE_INVALID.

gyro→get_zValue()
gyro→zValue()
gyro.get_zValue()gyro→get_zValue()[gyro zValue]gyro.get_zValue()gyro.get_zValue()gyro.get_zValue()gyro.get_zValue()gyro.get_zValue()gyro.get_zValue()gyro→get_zValue()gyro.get_zValue()gyro.get_zValue()gyro.get_zValue()gyro.get_zValue()YGyro get_zValue

Returns the angular velocity around the Z axis of the device, as a floating point number.

js
function get_zValue()
cpp
double get_zValue()
m
-(double) zValue
pas
double get_zValue(): double
vb
function get_zValue() As Double
cs
double get_zValue()
java
double get_zValue()
uwp
async Task<double> get_zValue()
py
get_zValue()
php
function get_zValue()
ts
async get_zValue(): Promise<number>
es
async get_zValue()
dnp
double get_zValue()
cp
double get_zValue()
cmd
YGyro target get_zValue

Returns :

a floating point number corresponding to the angular velocity around the Z axis of the device, as a floating point number

On failure, throws an exception or returns YGyro.ZVALUE_INVALID.

gyro→isOnline()gyro.isOnline()gyro→isOnline()[gyro isOnline]gyro.isOnline()gyro.isOnline()gyro.isOnline()gyro.isOnline()gyro.isOnline()gyro→isOnline()gyro.isOnline()gyro.isOnline()gyro.isOnline()gyro.isOnline()

Checks if the gyroscope is currently reachable, without raising any error.

js
function isOnline()
cpp
bool isOnline()
m
-(BOOL) isOnline
pas
boolean isOnline(): boolean
vb
function isOnline() As Boolean
cs
bool isOnline()
java
boolean isOnline()
py
isOnline()
php
function isOnline()
ts
async isOnline(): Promise<boolean>
es
async isOnline()
dnp
bool isOnline()
cp
bool isOnline()

If there is a cached value for the gyroscope in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the gyroscope.

Returns :

true if the gyroscope can be reached, and false otherwise

gyro→isOnline_async()gyro.isOnline_async()

Checks if the gyroscope is currently reachable, without raising any error (asynchronous version).

js
function isOnline_async(callback, context)

If there is a cached value for the gyroscope in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the requested function.

This asynchronous version exists only in Javascript. It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the boolean result
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

gyro→isReadOnly()gyro→isReadOnly()[gyro isReadOnly]gyro.isReadOnly()gyro.isReadOnly()gyro.isReadOnly()gyro.isReadOnly()gyro.isReadOnly()gyro.isReadOnly()gyro→isReadOnly()gyro.isReadOnly()gyro.isReadOnly()gyro.isReadOnly()gyro.isReadOnly()YGyro isReadOnly

Test if the function is readOnly.

cpp
bool isReadOnly()
m
-(bool) isReadOnly
pas
boolean isReadOnly(): boolean
vb
function isReadOnly() As Boolean
cs
bool isReadOnly()
java
boolean isReadOnly()
uwp
async Task<bool> isReadOnly()
py
isReadOnly()
php
function isReadOnly()
ts
async isReadOnly(): Promise<boolean>
es
async isReadOnly()
dnp
bool isReadOnly()
cp
bool isReadOnly()
cmd
YGyro target isReadOnly

Return true if the function is write protected or that the function is not available.

Returns :

true if the function is readOnly or not online.

gyro→isSensorReady()YGyro isSensorReady

Checks if the sensor is currently able to provide an up-to-date measure.

cmd
YGyro target isSensorReady

Returns false if the device is unreachable, or if the sensor does not have a current measure to transmit. No exception is raised if there is an error while trying to contact the device hosting $THEFUNCTION$.

Returns :

true if the sensor can provide an up-to-date measure, and false otherwise

gyro→load()gyro.load()gyro→load()[gyro load: ]gyro.load()gyro.load()gyro.load()gyro.load()gyro.load()gyro→load()gyro.load()gyro.load()

Preloads the gyroscope cache with a specified validity duration.

js
function load(msValidity)
cpp
YRETCODE load(int msValidity)
m
-(YRETCODE) load: (u64) msValidity
pas
YRETCODE load(msValidity: u64): YRETCODE
vb
function load(ByVal msValidity As Long) As YRETCODE
cs
YRETCODE load(ulong msValidity)
java
int load(long msValidity)
py
load(msValidity)
php
function load($msValidity)
ts
async load(msValidity: number): Promise<number>
es
async load(msValidity)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

Parameters :

msValidityan integer corresponding to the validity attributed to the loaded function parameters, in milliseconds

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→loadAttribute()gyro.loadAttribute()gyro→loadAttribute()[gyro loadAttribute: ]gyro.loadAttribute()gyro.loadAttribute()gyro.loadAttribute()gyro.loadAttribute()gyro.loadAttribute()gyro.loadAttribute()gyro→loadAttribute()gyro.loadAttribute()gyro.loadAttribute()gyro.loadAttribute()gyro.loadAttribute()

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

js
function loadAttribute(attrName)
cpp
string loadAttribute(string attrName)
m
-(NSString*) loadAttribute: (NSString*) attrName
pas
string loadAttribute(attrName: string): string
vb
function loadAttribute(ByVal attrName As String) As String
cs
string loadAttribute(string attrName)
java
String loadAttribute(String attrName)
uwp
async Task<string> loadAttribute(string attrName)
py
loadAttribute(attrName)
php
function loadAttribute($attrName)
ts
async loadAttribute(attrName: string): Promise<string>
es
async loadAttribute(attrName)
dnp
string loadAttribute(string attrName)
cp
string loadAttribute(string attrName)

Parameters :

attrNamethe name of the requested attribute

Returns :

a string with the value of the the attribute

On failure, throws an exception or returns an empty string.

gyro→loadCalibrationPoints()gyro.loadCalibrationPoints()gyro→loadCalibrationPoints()[gyro loadCalibrationPoints: ]gyro.loadCalibrationPoints()gyro.loadCalibrationPoints()gyro.loadCalibrationPoints()gyro.loadCalibrationPoints()gyro.loadCalibrationPoints()gyro.loadCalibrationPoints()gyro→loadCalibrationPoints()gyro.loadCalibrationPoints()gyro.loadCalibrationPoints()YGyro loadCalibrationPoints

Retrieves error correction data points previously entered using the method calibrateFromPoints.

js
function loadCalibrationPoints(rawValues, refValues)
cpp
int loadCalibrationPoints(vector<double> rawValues,
  vector<double> refValues)
m
-(int) loadCalibrationPoints: (NSMutableArray*) rawValues
  : (NSMutableArray*) refValues
pas
LongInt loadCalibrationPoints(var rawValues: TDoubleArray,
  var refValues: TDoubleArray): LongInt
vb
procedure loadCalibrationPoints(ByVal rawValues As List(Of)
cs
int loadCalibrationPoints(List<double> rawValues,
  List<double> refValues)
java
int loadCalibrationPoints(ArrayList<Double> rawValues,
  ArrayList<Double> refValues)
uwp
async Task<int> loadCalibrationPoints(List<double> rawValues,
  List<double> refValues)
py
loadCalibrationPoints(rawValues, refValues)
php
function loadCalibrationPoints(&$rawValues, &$refValues)
ts
async loadCalibrationPoints(rawValues: number[], refValues: number[]): Promise<number>
es
async loadCalibrationPoints(rawValues, refValues)
cmd
YGyro target loadCalibrationPoints rawValues refValues

Parameters :

rawValuesarray of floating point numbers, that will be filled by the function with the raw sensor values for the correction points.
refValuesarray of floating point numbers, that will be filled by the function with the desired values for the correction points.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→load_async()gyro.load_async()

Preloads the gyroscope cache with a specified validity duration (asynchronous version).

js
function load_async(msValidity, callback, context)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking the JavaScript virtual machine.

Parameters :

msValidityan integer corresponding to the validity of the loaded function parameters, in milliseconds
callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the error code (or YAPI.SUCCESS)
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

gyro→muteValueCallbacks()gyro.muteValueCallbacks()gyro→muteValueCallbacks()[gyro muteValueCallbacks]gyro.muteValueCallbacks()gyro.muteValueCallbacks()gyro.muteValueCallbacks()gyro.muteValueCallbacks()gyro.muteValueCallbacks()gyro.muteValueCallbacks()gyro→muteValueCallbacks()gyro.muteValueCallbacks()gyro.muteValueCallbacks()gyro.muteValueCallbacks()gyro.muteValueCallbacks()YGyro muteValueCallbacks

Disables the propagation of every new advertised value to the parent hub.

js
function muteValueCallbacks()
cpp
int muteValueCallbacks()
m
-(int) muteValueCallbacks
pas
LongInt muteValueCallbacks(): LongInt
vb
function muteValueCallbacks() As Integer
cs
int muteValueCallbacks()
java
int muteValueCallbacks()
uwp
async Task<int> muteValueCallbacks()
py
muteValueCallbacks()
php
function muteValueCallbacks()
ts
async muteValueCallbacks(): Promise<number>
es
async muteValueCallbacks()
dnp
int muteValueCallbacks()
cp
int muteValueCallbacks()
cmd
YGyro target muteValueCallbacks

You can use this function to save bandwidth and CPU on computers with limited resources, or to prevent unwanted invocations of the HTTP callback. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→nextGyro()gyro.nextGyro()gyro→nextGyro()[gyro nextGyro]gyro.nextGyro()gyro.nextGyro()gyro.nextGyro()gyro.nextGyro()gyro.nextGyro()gyro.nextGyro()gyro→nextGyro()gyro.nextGyro()gyro.nextGyro()

Continues the enumeration of gyroscopes started using yFirstGyro().

js
function nextGyro()
cpp
YGyro * nextGyro()
m
-(nullable YGyro*) nextGyro
pas
TYGyro nextGyro(): TYGyro
vb
function nextGyro() As YGyro
cs
YGyro nextGyro()
java
YGyro nextGyro()
uwp
YGyro nextGyro()
py
nextGyro()
php
function nextGyro()
ts
nextGyro(): YGyro | null
es
nextGyro()

Caution: You can't make any assumption about the returned gyroscopes order. If you want to find a specific a gyroscope, use Gyro.findGyro() and a hardwareID or a logical name.

Returns :

a pointer to a YGyro object, corresponding to a gyroscope currently online, or a null pointer if there are no more gyroscopes to enumerate.

gyro→registerAnglesCallback()gyro.registerAnglesCallback()gyro→registerAnglesCallback()[gyro registerAnglesCallback: ]gyro.registerAnglesCallback()gyro.registerAnglesCallback()gyro.registerAnglesCallback()gyro.registerAnglesCallback()gyro.registerAnglesCallback()gyro.registerAnglesCallback()gyro→registerAnglesCallback()gyro.registerAnglesCallback()gyro.registerAnglesCallback()

Registers a callback function that will be invoked each time that the estimated device orientation has changed.

js
function registerAnglesCallback(callback)
cpp
int registerAnglesCallback(YAnglesCallback callback)
m
-(int) registerAnglesCallback: (YAnglesCallback _Nullable) callback
pas
LongInt registerAnglesCallback(callback: TYAnglesCallback): LongInt
vb
function registerAnglesCallback(ByVal callback As YAnglesCallback) As Integer
cs
int registerAnglesCallback(YAnglesCallback callback)
java
int registerAnglesCallback(YAnglesCallback callback)
uwp
async Task<int> registerAnglesCallback(YAnglesCallback callback)
py
registerAnglesCallback(callback)
php
function registerAnglesCallback($callback)
ts
async registerAnglesCallback(callback: YAnglesCallback | null): Promise<number>
es
async registerAnglesCallback(callback)

The call frequency is typically around 95Hz during a move. The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to invoke, or a null pointer. The callback function should take four arguments: the YGyro object of the turning device, and the floating point values of the three angles roll, pitch and heading in degrees (as floating-point numbers).

gyro→registerQuaternionCallback()gyro.registerQuaternionCallback()gyro→registerQuaternionCallback()[gyro registerQuaternionCallback: ]gyro.registerQuaternionCallback()gyro.registerQuaternionCallback()gyro.registerQuaternionCallback()gyro.registerQuaternionCallback()gyro.registerQuaternionCallback()gyro.registerQuaternionCallback()gyro→registerQuaternionCallback()gyro.registerQuaternionCallback()gyro.registerQuaternionCallback()

Registers a callback function that will be invoked each time that the estimated device orientation has changed.

js
function registerQuaternionCallback(callback)
cpp
int registerQuaternionCallback(YQuatCallback callback)
m
-(int) registerQuaternionCallback: (YQuatCallback _Nullable) callback
pas
LongInt registerQuaternionCallback(callback: TYQuatCallback): LongInt
vb
function registerQuaternionCallback(ByVal callback As YQuatCallback) As Integer
cs
int registerQuaternionCallback(YQuatCallback callback)
java
int registerQuaternionCallback(YQuatCallback callback)
uwp
async Task<int> registerQuaternionCallback(YQuatCallback callback)
py
registerQuaternionCallback(callback)
php
function registerQuaternionCallback($callback)
ts
async registerQuaternionCallback(callback: YQuatCallback | null): Promise<number>
es
async registerQuaternionCallback(callback)

The call frequency is typically around 95Hz during a move. The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to invoke, or a null pointer. The callback function should take five arguments: the YGyro object of the turning device, and the floating point values of the four components w, x, y and z (as floating-point numbers).

gyro→registerTimedReportCallback()gyro.registerTimedReportCallback()gyro→registerTimedReportCallback()[gyro registerTimedReportCallback: ]gyro.registerTimedReportCallback()gyro.registerTimedReportCallback()gyro.registerTimedReportCallback()gyro.registerTimedReportCallback()gyro.registerTimedReportCallback()gyro.registerTimedReportCallback()gyro→registerTimedReportCallback()gyro.registerTimedReportCallback()gyro.registerTimedReportCallback()

Registers the callback function that is invoked on every periodic timed notification.

js
function registerTimedReportCallback(callback)
cpp
int registerTimedReportCallback(YGyroTimedReportCallback callback)
m
-(int) registerTimedReportCallback: (YGyroTimedReportCallback _Nullable) callback
pas
LongInt registerTimedReportCallback(callback: TYGyroTimedReportCallback): LongInt
vb
function registerTimedReportCallback(ByVal callback As YGyroTimedReportCallback) As Integer
cs
int registerTimedReportCallback(TimedReportCallback callback)
java
int registerTimedReportCallback(TimedReportCallback callback)
uwp
async Task<int> registerTimedReportCallback(TimedReportCallback callback)
py
registerTimedReportCallback(callback)
php
function registerTimedReportCallback($callback)
ts
async registerTimedReportCallback(callback: YGyroTimedReportCallback | null): Promise<number>
es
async registerTimedReportCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and an YMeasure object describing the new advertised value.

gyro→registerValueCallback()gyro.registerValueCallback()gyro→registerValueCallback()[gyro registerValueCallback: ]gyro.registerValueCallback()gyro.registerValueCallback()gyro.registerValueCallback()gyro.registerValueCallback()gyro.registerValueCallback()gyro.registerValueCallback()gyro→registerValueCallback()gyro.registerValueCallback()gyro.registerValueCallback()

Registers the callback function that is invoked on every change of advertised value.

js
function registerValueCallback(callback)
cpp
int registerValueCallback(YGyroValueCallback callback)
m
-(int) registerValueCallback: (YGyroValueCallback _Nullable) callback
pas
LongInt registerValueCallback(callback: TYGyroValueCallback): LongInt
vb
function registerValueCallback(ByVal callback As YGyroValueCallback) As Integer
cs
int registerValueCallback(ValueCallback callback)
java
int registerValueCallback(UpdateCallback callback)
uwp
async Task<int> registerValueCallback(ValueCallback callback)
py
registerValueCallback(callback)
php
function registerValueCallback($callback)
ts
async registerValueCallback(callback: YGyroValueCallback | null): Promise<number>
es
async registerValueCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and the character string describing the new advertised value.

gyro→set_advMode()
gyro→setAdvMode()
gyro.set_advMode()gyro→set_advMode()[gyro setAdvMode: ]gyro.set_advMode()gyro.set_advMode()gyro.set_advMode()gyro.set_advMode()gyro.set_advMode()gyro.set_advMode()gyro→set_advMode()gyro.set_advMode()gyro.set_advMode()gyro.set_advMode()gyro.set_advMode()YGyro set_advMode

Changes the measuring mode used for the advertised value pushed to the parent hub.

js
function set_advMode(newval)
cpp
int set_advMode(Y_ADVMODE_enum newval)
m
-(int) setAdvMode: (Y_ADVMODE_enum) newval
pas
integer set_advMode(newval: Integer): integer
vb
function set_advMode(ByVal newval As Integer) As Integer
cs
int set_advMode(int newval)
java
int set_advMode(int newval)
uwp
async Task<int> set_advMode(int newval)
py
set_advMode(newval)
php
function set_advMode($newval)
ts
async set_advMode(newval: YSensor_AdvMode): Promise<number>
es
async set_advMode(newval)
dnp
int set_advMode(int newval)
cp
int set_advMode(int newval)
cmd
YGyro target set_advMode newval

Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala value among YGyro.ADVMODE_IMMEDIATE, YGyro.ADVMODE_PERIOD_AVG, YGyro.ADVMODE_PERIOD_MIN and YGyro.ADVMODE_PERIOD_MAX corresponding to the measuring mode used for the advertised value pushed to the parent hub

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→set_bandwidth()
gyro→setBandwidth()
gyro.set_bandwidth()gyro→set_bandwidth()[gyro setBandwidth: ]gyro.set_bandwidth()gyro.set_bandwidth()gyro.set_bandwidth()gyro.set_bandwidth()gyro.set_bandwidth()gyro.set_bandwidth()gyro→set_bandwidth()gyro.set_bandwidth()gyro.set_bandwidth()gyro.set_bandwidth()gyro.set_bandwidth()YGyro set_bandwidth

Changes the measure update frequency, measured in Hz.

js
function set_bandwidth(newval)
cpp
int set_bandwidth(int newval)
m
-(int) setBandwidth: (int) newval
pas
integer set_bandwidth(newval: LongInt): integer
vb
function set_bandwidth(ByVal newval As Integer) As Integer
cs
int set_bandwidth(int newval)
java
int set_bandwidth(int newval)
uwp
async Task<int> set_bandwidth(int newval)
py
set_bandwidth(newval)
php
function set_bandwidth($newval)
ts
async set_bandwidth(newval: number): Promise<number>
es
async set_bandwidth(newval)
dnp
int set_bandwidth(int newval)
cp
int set_bandwidth(int newval)
cmd
YGyro target set_bandwidth newval

When the frequency is lower, the device performs averaging. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvalan integer corresponding to the measure update frequency, measured in Hz

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→set_highestValue()
gyro→setHighestValue()
gyro.set_highestValue()gyro→set_highestValue()[gyro setHighestValue: ]gyro.set_highestValue()gyro.set_highestValue()gyro.set_highestValue()gyro.set_highestValue()gyro.set_highestValue()gyro.set_highestValue()gyro→set_highestValue()gyro.set_highestValue()gyro.set_highestValue()gyro.set_highestValue()gyro.set_highestValue()YGyro set_highestValue

Changes the recorded maximal value observed.

js
function set_highestValue(newval)
cpp
int set_highestValue(double newval)
m
-(int) setHighestValue: (double) newval
pas
integer set_highestValue(newval: double): integer
vb
function set_highestValue(ByVal newval As Double) As Integer
cs
int set_highestValue(double newval)
java
int set_highestValue(double newval)
uwp
async Task<int> set_highestValue(double newval)
py
set_highestValue(newval)
php
function set_highestValue($newval)
ts
async set_highestValue(newval: number): Promise<number>
es
async set_highestValue(newval)
dnp
int set_highestValue(double newval)
cp
int set_highestValue(double newval)
cmd
YGyro target set_highestValue newval

Can be used to reset the value returned by get_lowestValue().

Parameters :

newvala floating point number corresponding to the recorded maximal value observed

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→set_logFrequency()
gyro→setLogFrequency()
gyro.set_logFrequency()gyro→set_logFrequency()[gyro setLogFrequency: ]gyro.set_logFrequency()gyro.set_logFrequency()gyro.set_logFrequency()gyro.set_logFrequency()gyro.set_logFrequency()gyro.set_logFrequency()gyro→set_logFrequency()gyro.set_logFrequency()gyro.set_logFrequency()gyro.set_logFrequency()gyro.set_logFrequency()YGyro set_logFrequency

Changes the datalogger recording frequency for this function.

js
function set_logFrequency(newval)
cpp
int set_logFrequency(string newval)
m
-(int) setLogFrequency: (NSString*) newval
pas
integer set_logFrequency(newval: string): integer
vb
function set_logFrequency(ByVal newval As String) As Integer
cs
int set_logFrequency(string newval)
java
int set_logFrequency(String newval)
uwp
async Task<int> set_logFrequency(string newval)
py
set_logFrequency(newval)
php
function set_logFrequency($newval)
ts
async set_logFrequency(newval: string): Promise<number>
es
async set_logFrequency(newval)
dnp
int set_logFrequency(string newval)
cp
int set_logFrequency(string newval)
cmd
YGyro target set_logFrequency newval

The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (eg. "4/h"). To disable recording for this function, use the value "OFF". Note that setting the datalogger recording frequency to a greater value than the sensor native sampling frequency is useless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the datalogger recording frequency for this function

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→set_logicalName()
gyro→setLogicalName()
gyro.set_logicalName()gyro→set_logicalName()[gyro setLogicalName: ]gyro.set_logicalName()gyro.set_logicalName()gyro.set_logicalName()gyro.set_logicalName()gyro.set_logicalName()gyro.set_logicalName()gyro→set_logicalName()gyro.set_logicalName()gyro.set_logicalName()gyro.set_logicalName()gyro.set_logicalName()YGyro set_logicalName

Changes the logical name of the gyroscope.

js
function set_logicalName(newval)
cpp
int set_logicalName(string newval)
m
-(int) setLogicalName: (NSString*) newval
pas
integer set_logicalName(newval: string): integer
vb
function set_logicalName(ByVal newval As String) As Integer
cs
int set_logicalName(string newval)
java
int set_logicalName(String newval)
uwp
async Task<int> set_logicalName(string newval)
py
set_logicalName(newval)
php
function set_logicalName($newval)
ts
async set_logicalName(newval: string): Promise<number>
es
async set_logicalName(newval)
dnp
int set_logicalName(string newval)
cp
int set_logicalName(string newval)
cmd
YGyro target set_logicalName newval

You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the logical name of the gyroscope.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→set_lowestValue()
gyro→setLowestValue()
gyro.set_lowestValue()gyro→set_lowestValue()[gyro setLowestValue: ]gyro.set_lowestValue()gyro.set_lowestValue()gyro.set_lowestValue()gyro.set_lowestValue()gyro.set_lowestValue()gyro.set_lowestValue()gyro→set_lowestValue()gyro.set_lowestValue()gyro.set_lowestValue()gyro.set_lowestValue()gyro.set_lowestValue()YGyro set_lowestValue

Changes the recorded minimal value observed.

js
function set_lowestValue(newval)
cpp
int set_lowestValue(double newval)
m
-(int) setLowestValue: (double) newval
pas
integer set_lowestValue(newval: double): integer
vb
function set_lowestValue(ByVal newval As Double) As Integer
cs
int set_lowestValue(double newval)
java
int set_lowestValue(double newval)
uwp
async Task<int> set_lowestValue(double newval)
py
set_lowestValue(newval)
php
function set_lowestValue($newval)
ts
async set_lowestValue(newval: number): Promise<number>
es
async set_lowestValue(newval)
dnp
int set_lowestValue(double newval)
cp
int set_lowestValue(double newval)
cmd
YGyro target set_lowestValue newval

Can be used to reset the value returned by get_lowestValue().

Parameters :

newvala floating point number corresponding to the recorded minimal value observed

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→set_reportFrequency()
gyro→setReportFrequency()
gyro.set_reportFrequency()gyro→set_reportFrequency()[gyro setReportFrequency: ]gyro.set_reportFrequency()gyro.set_reportFrequency()gyro.set_reportFrequency()gyro.set_reportFrequency()gyro.set_reportFrequency()gyro.set_reportFrequency()gyro→set_reportFrequency()gyro.set_reportFrequency()gyro.set_reportFrequency()gyro.set_reportFrequency()gyro.set_reportFrequency()YGyro set_reportFrequency

Changes the timed value notification frequency for this function.

js
function set_reportFrequency(newval)
cpp
int set_reportFrequency(string newval)
m
-(int) setReportFrequency: (NSString*) newval
pas
integer set_reportFrequency(newval: string): integer
vb
function set_reportFrequency(ByVal newval As String) As Integer
cs
int set_reportFrequency(string newval)
java
int set_reportFrequency(String newval)
uwp
async Task<int> set_reportFrequency(string newval)
py
set_reportFrequency(newval)
php
function set_reportFrequency($newval)
ts
async set_reportFrequency(newval: string): Promise<number>
es
async set_reportFrequency(newval)
dnp
int set_reportFrequency(string newval)
cp
int set_reportFrequency(string newval)
cmd
YGyro target set_reportFrequency newval

The frequency can be specified as samples per second, as sample per minute (for instance "15/m") or in samples per hour (e.g. "4/h"). To disable timed value notifications for this function, use the value "OFF". Note that setting the timed value notification frequency to a greater value than the sensor native sampling frequency is unless, and even counterproductive: those two frequencies are not related. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the timed value notification frequency for this function

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→set_resolution()
gyro→setResolution()
gyro.set_resolution()gyro→set_resolution()[gyro setResolution: ]gyro.set_resolution()gyro.set_resolution()gyro.set_resolution()gyro.set_resolution()gyro.set_resolution()gyro.set_resolution()gyro→set_resolution()gyro.set_resolution()gyro.set_resolution()gyro.set_resolution()gyro.set_resolution()YGyro set_resolution

Changes the resolution of the measured physical values.

js
function set_resolution(newval)
cpp
int set_resolution(double newval)
m
-(int) setResolution: (double) newval
pas
integer set_resolution(newval: double): integer
vb
function set_resolution(ByVal newval As Double) As Integer
cs
int set_resolution(double newval)
java
int set_resolution(double newval)
uwp
async Task<int> set_resolution(double newval)
py
set_resolution(newval)
php
function set_resolution($newval)
ts
async set_resolution(newval: number): Promise<number>
es
async set_resolution(newval)
dnp
int set_resolution(double newval)
cp
int set_resolution(double newval)
cmd
YGyro target set_resolution newval

The resolution corresponds to the numerical precision when displaying value. It does not change the precision of the measure itself. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala floating point number corresponding to the resolution of the measured physical values

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→set_userData()
gyro→setUserData()
gyro.set_userData()gyro→set_userData()[gyro setUserData: ]gyro.set_userData()gyro.set_userData()gyro.set_userData()gyro.set_userData()gyro.set_userData()gyro→set_userData()gyro.set_userData()gyro.set_userData()

Stores a user context provided as argument in the userData attribute of the function.

js
function set_userData(data)
cpp
void set_userData(void * data)
m
-(void) setUserData: (id) data
pas
set_userData(data: Tobject)
vb
procedure set_userData(ByVal data As Object)
cs
void set_userData(object data)
java
void set_userData(Object data)
py
set_userData(data)
php
function set_userData($data)
ts
async set_userData(data: object|null): Promise<void>
es
async set_userData(data)

This attribute is never touched by the API, and is at disposal of the caller to store a context.

Parameters :

dataany kind of object to be stored

gyro→startDataLogger()gyro.startDataLogger()gyro→startDataLogger()[gyro startDataLogger]gyro.startDataLogger()gyro.startDataLogger()gyro.startDataLogger()gyro.startDataLogger()gyro.startDataLogger()gyro.startDataLogger()gyro→startDataLogger()gyro.startDataLogger()gyro.startDataLogger()gyro.startDataLogger()gyro.startDataLogger()YGyro startDataLogger

Starts the data logger on the device.

js
function startDataLogger()
cpp
int startDataLogger()
m
-(int) startDataLogger
pas
LongInt startDataLogger(): LongInt
vb
function startDataLogger() As Integer
cs
int startDataLogger()
java
int startDataLogger()
uwp
async Task<int> startDataLogger()
py
startDataLogger()
php
function startDataLogger()
ts
async startDataLogger(): Promise<number>
es
async startDataLogger()
dnp
int startDataLogger()
cp
int startDataLogger()
cmd
YGyro target startDataLogger

Note that the data logger will only save the measures on this sensor if the logFrequency is not set to "OFF".

Returns :

YAPI.SUCCESS if the call succeeds.

gyro→stopDataLogger()gyro.stopDataLogger()gyro→stopDataLogger()[gyro stopDataLogger]gyro.stopDataLogger()gyro.stopDataLogger()gyro.stopDataLogger()gyro.stopDataLogger()gyro.stopDataLogger()gyro.stopDataLogger()gyro→stopDataLogger()gyro.stopDataLogger()gyro.stopDataLogger()gyro.stopDataLogger()gyro.stopDataLogger()YGyro stopDataLogger

Stops the datalogger on the device.

js
function stopDataLogger()
cpp
int stopDataLogger()
m
-(int) stopDataLogger
pas
LongInt stopDataLogger(): LongInt
vb
function stopDataLogger() As Integer
cs
int stopDataLogger()
java
int stopDataLogger()
uwp
async Task<int> stopDataLogger()
py
stopDataLogger()
php
function stopDataLogger()
ts
async stopDataLogger(): Promise<number>
es
async stopDataLogger()
dnp
int stopDataLogger()
cp
int stopDataLogger()
cmd
YGyro target stopDataLogger

Returns :

YAPI.SUCCESS if the call succeeds.

gyro→unmuteValueCallbacks()gyro.unmuteValueCallbacks()gyro→unmuteValueCallbacks()[gyro unmuteValueCallbacks]gyro.unmuteValueCallbacks()gyro.unmuteValueCallbacks()gyro.unmuteValueCallbacks()gyro.unmuteValueCallbacks()gyro.unmuteValueCallbacks()gyro.unmuteValueCallbacks()gyro→unmuteValueCallbacks()gyro.unmuteValueCallbacks()gyro.unmuteValueCallbacks()gyro.unmuteValueCallbacks()gyro.unmuteValueCallbacks()YGyro unmuteValueCallbacks

Re-enables the propagation of every new advertised value to the parent hub.

js
function unmuteValueCallbacks()
cpp
int unmuteValueCallbacks()
m
-(int) unmuteValueCallbacks
pas
LongInt unmuteValueCallbacks(): LongInt
vb
function unmuteValueCallbacks() As Integer
cs
int unmuteValueCallbacks()
java
int unmuteValueCallbacks()
uwp
async Task<int> unmuteValueCallbacks()
py
unmuteValueCallbacks()
php
function unmuteValueCallbacks()
ts
async unmuteValueCallbacks(): Promise<number>
es
async unmuteValueCallbacks()
dnp
int unmuteValueCallbacks()
cp
int unmuteValueCallbacks()
cmd
YGyro target unmuteValueCallbacks

This function reverts the effect of a previous call to muteValueCallbacks(). Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

gyro→wait_async()gyro.wait_async()gyro.wait_async()gyro.wait_async()

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

js
function wait_async(callback, context)
ts
wait_async(callback: Function, context: object)
es
wait_async(callback, context)

The callback function can therefore freely issue synchronous or asynchronous commands, without risking to block the JavaScript VM.

Parameters :

callbackcallback function that is invoked when all pending commands on the module are completed. The callback function receives two arguments: the caller-specific context object and the receiving function object.
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing.

24.9. Class YDataLogger

DataLogger control interface, available on most Yoctopuce sensors.

A non-volatile memory for storing ongoing measured data is available on most Yoctopuce sensors. Recording can happen automatically, without requiring a permanent connection to a computer. The YDataLogger class controls the global parameters of the internal data logger. Recording control (start/stop) as well as data retreival is done at sensor objects level.

In order to use the functions described here, you should include:

js
<script type='text/javascript' src='yocto_module.js'></script>
cpp
#include "yocto_module.h"
m
#import "yocto_module.h"
pas
uses yocto_module;
vb
yocto_module.vb
cs
yocto_module.cs
java
import com.yoctopuce.YoctoAPI.YDataLogger;
uwp
import com.yoctopuce.YoctoAPI.YDataLogger;
py
from yocto_module import *
php
require_once('yocto_module.php');
ts
in HTML: import { YDataLogger } from '../../dist/esm/yocto_module.js';
in Node.js: import { YDataLogger } from 'yoctolib-cjs/yocto_module.js';
es
in HTML: <script src="../../lib/yocto_module.js"></script>
in node.js: require('yoctolib-es2017/yocto_module.js');
dnp
import YoctoProxyAPI.YDataLoggerProxy
cp
#include "yocto_module_proxy.h"
vi
YDataLogger.vi
ml
import YoctoProxyAPI.YDataLoggerProxy
Global functions
YDataLogger.FindDataLogger(func)

Retrieves a data logger for a given identifier.

YDataLogger.FindDataLoggerInContext(yctx, func)

Retrieves a data logger for a given identifier in a YAPI context.

YDataLogger.FirstDataLogger()

Starts the enumeration of data loggers currently accessible.

YDataLogger.FirstDataLoggerInContext(yctx)

Starts the enumeration of data loggers currently accessible.

YDataLogger.GetSimilarFunctions()

Enumerates all functions of type DataLogger available on the devices currently reachable by the library, and returns their unique hardware ID.

YDataLogger properties
datalogger→AdvertisedValue [read-only]

Short string representing the current state of the function.

datalogger→AutoStart [writable]

Default activation state of the data logger on power up.

datalogger→BeaconDriven [writable]

True if the data logger is synchronised with the localization beacon.

datalogger→FriendlyName [read-only]

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

datalogger→FunctionId [read-only]

Hardware identifier of the data logger, without reference to the module.

datalogger→HardwareId [read-only]

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

datalogger→IsOnline [read-only]

Checks if the function is currently reachable.

datalogger→LogicalName [writable]

Logical name of the function.

datalogger→Recording [writable]

Current activation state of the data logger.

datalogger→SerialNumber [read-only]

Serial number of the module, as set by the factory.

YDataLogger methods
datalogger→clearCache()

Invalidates the cache.

datalogger→describe()

Returns a short text that describes unambiguously the instance of the data logger in the form TYPE(NAME)=SERIAL.FUNCTIONID.

datalogger→forgetAllDataStreams()

Clears the data logger memory and discards all recorded data streams.

datalogger→get_advertisedValue()

Returns the current value of the data logger (no more than 6 characters).

datalogger→get_autoStart()

Returns the default activation state of the data logger on power up.

datalogger→get_beaconDriven()

Returns true if the data logger is synchronised with the localization beacon.

datalogger→get_currentRunIndex()

Returns the current run number, corresponding to the number of times the module was powered on with the dataLogger enabled at some point.

datalogger→get_dataSets()

Returns a list of YDataSet objects that can be used to retrieve all measures stored by the data logger.

datalogger→get_dataStreams(v)

Builds a list of all data streams hold by the data logger (legacy method).

datalogger→get_errorMessage()

Returns the error message of the latest error with the data logger.

datalogger→get_errorType()

Returns the numerical error code of the latest error with the data logger.

datalogger→get_friendlyName()

Returns a global identifier of the data logger in the format MODULE_NAME.FUNCTION_NAME.

datalogger→get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

datalogger→get_functionId()

Returns the hardware identifier of the data logger, without reference to the module.

datalogger→get_hardwareId()

Returns the unique hardware identifier of the data logger in the form SERIAL.FUNCTIONID.

datalogger→get_logicalName()

Returns the logical name of the data logger.

datalogger→get_module()

Gets the YModule object for the device on which the function is located.

datalogger→get_module_async(callback, context)

Gets the YModule object for the device on which the function is located (asynchronous version).

datalogger→get_recording()

Returns the current activation state of the data logger.

datalogger→get_serialNumber()

Returns the serial number of the module, as set by the factory.

datalogger→get_timeUTC()

Returns the Unix timestamp for current UTC time, if known.

datalogger→get_usage()

Returns the percentage of datalogger memory in use.

datalogger→get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

datalogger→isOnline()

Checks if the data logger is currently reachable, without raising any error.

datalogger→isOnline_async(callback, context)

Checks if the data logger is currently reachable, without raising any error (asynchronous version).

datalogger→isReadOnly()

Test if the function is readOnly.

datalogger→load(msValidity)

Preloads the data logger cache with a specified validity duration.

datalogger→loadAttribute(attrName)

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

datalogger→load_async(msValidity, callback, context)

Preloads the data logger cache with a specified validity duration (asynchronous version).

datalogger→muteValueCallbacks()

Disables the propagation of every new advertised value to the parent hub.

datalogger→nextDataLogger()

Continues the enumeration of data loggers started using yFirstDataLogger().

datalogger→registerValueCallback(callback)

Registers the callback function that is invoked on every change of advertised value.

datalogger→set_autoStart(newval)

Changes the default activation state of the data logger on power up.

datalogger→set_beaconDriven(newval)

Changes the type of synchronisation of the data logger.

datalogger→set_logicalName(newval)

Changes the logical name of the data logger.

datalogger→set_recording(newval)

Changes the activation state of the data logger to start/stop recording data.

datalogger→set_timeUTC(newval)

Changes the current UTC time reference used for recorded data.

datalogger→set_userData(data)

Stores a user context provided as argument in the userData attribute of the function.

datalogger→unmuteValueCallbacks()

Re-enables the propagation of every new advertised value to the parent hub.

datalogger→wait_async(callback, context)

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

YDataLogger.FindDataLogger()
YDataLogger.FindDataLogger()
yFindDataLogger()YDataLogger::FindDataLogger()[YDataLogger FindDataLogger: ]yFindDataLogger()YDataLogger.FindDataLogger()YDataLogger.FindDataLogger()YDataLogger.FindDataLogger()YDataLogger.FindDataLogger()YDataLogger.FindDataLogger()YDataLogger::FindDataLogger()YDataLogger.FindDataLogger()YDataLogger.FindDataLogger()YDataLogger.FindDataLogger()YDataLogger.FindDataLogger()

Retrieves a data logger for a given identifier.

js
function yFindDataLogger(func)
cpp
YDataLogger* FindDataLogger(string func)
m
+(YDataLogger*) FindDataLogger: (NSString*) func
pas
TYDataLogger yFindDataLogger(func: string): TYDataLogger
vb
function FindDataLogger(ByVal func As String) As YDataLogger
cs
static YDataLogger FindDataLogger(string func)
java
static YDataLogger FindDataLogger(String func)
uwp
static YDataLogger FindDataLogger(string func)
py
FindDataLogger(func)
php
function FindDataLogger($func)
ts
static FindDataLogger(func: string): YDataLogger
es
static FindDataLogger(func)
dnp
static YDataLoggerProxy FindDataLogger(string func)
cp
static YDataLoggerProxy * FindDataLogger(string func)

The identifier can be specified using several formats:

This function does not require that the data logger is online at the time it is invoked. The returned object is nevertheless valid. Use the method YDataLogger.isOnline() to test if the data logger is indeed online at a given time. In case of ambiguity when looking for a data logger by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

If a call to this object's is_online() method returns FALSE although you are certain that the matching device is plugged, make sure that you did call registerHub() at application initialization time.

Parameters :

funca string that uniquely characterizes the data logger, for instance RX420MA1.dataLogger.

Returns :

a YDataLogger object allowing you to drive the data logger.

YDataLogger.FindDataLoggerInContext()
YDataLogger.FindDataLoggerInContext()
YDataLogger.FindDataLoggerInContext()YDataLogger.FindDataLoggerInContext()YDataLogger.FindDataLoggerInContext()YDataLogger.FindDataLoggerInContext()

Retrieves a data logger for a given identifier in a YAPI context.

java
static YDataLogger FindDataLoggerInContext(YAPIContext yctx,
  String func)
uwp
static YDataLogger FindDataLoggerInContext(YAPIContext yctx,
  string func)
ts
static FindDataLoggerInContext(yctx: YAPIContext, func: string): YDataLogger
es
static FindDataLoggerInContext(yctx, func)

The identifier can be specified using several formats:

This function does not require that the data logger is online at the time it is invoked. The returned object is nevertheless valid. Use the method YDataLogger.isOnline() to test if the data logger is indeed online at a given time. In case of ambiguity when looking for a data logger by logical name, no error is notified: the first instance found is returned. The search is performed first by hardware name, then by logical name.

Parameters :

yctxa YAPI context
funca string that uniquely characterizes the data logger, for instance RX420MA1.dataLogger.

Returns :

a YDataLogger object allowing you to drive the data logger.

YDataLogger.FirstDataLogger()
YDataLogger.FirstDataLogger()
yFirstDataLogger()YDataLogger::FirstDataLogger()[YDataLogger FirstDataLogger]yFirstDataLogger()YDataLogger.FirstDataLogger()YDataLogger.FirstDataLogger()YDataLogger.FirstDataLogger()YDataLogger.FirstDataLogger()YDataLogger.FirstDataLogger()YDataLogger::FirstDataLogger()YDataLogger.FirstDataLogger()YDataLogger.FirstDataLogger()

Starts the enumeration of data loggers currently accessible.

js
function yFirstDataLogger()
cpp
YDataLogger * FirstDataLogger()
m
+(YDataLogger*) FirstDataLogger
pas
TYDataLogger yFirstDataLogger(): TYDataLogger
vb
function FirstDataLogger() As YDataLogger
cs
static YDataLogger FirstDataLogger()
java
static YDataLogger FirstDataLogger()
uwp
static YDataLogger FirstDataLogger()
py
FirstDataLogger()
php
function FirstDataLogger()
ts
static FirstDataLogger(): YDataLogger | null
es
static FirstDataLogger()

Use the method YDataLogger.nextDataLogger() to iterate on next data loggers.

Returns :

a pointer to a YDataLogger object, corresponding to the first data logger currently online, or a null pointer if there are none.

YDataLogger.FirstDataLoggerInContext()
YDataLogger.FirstDataLoggerInContext()
YDataLogger.FirstDataLoggerInContext()YDataLogger.FirstDataLoggerInContext()YDataLogger.FirstDataLoggerInContext()YDataLogger.FirstDataLoggerInContext()

Starts the enumeration of data loggers currently accessible.

java
static YDataLogger FirstDataLoggerInContext(YAPIContext yctx)
uwp
static YDataLogger FirstDataLoggerInContext(YAPIContext yctx)
ts
static FirstDataLoggerInContext(yctx: YAPIContext): YDataLogger | null
es
static FirstDataLoggerInContext(yctx)

Use the method YDataLogger.nextDataLogger() to iterate on next data loggers.

Parameters :

yctxa YAPI context.

Returns :

a pointer to a YDataLogger object, corresponding to the first data logger currently online, or a null pointer if there are none.

YDataLogger.GetSimilarFunctions()
YDataLogger.GetSimilarFunctions()
YDataLogger.GetSimilarFunctions()YDataLogger.GetSimilarFunctions()

Enumerates all functions of type DataLogger available on the devices currently reachable by the library, and returns their unique hardware ID.

dnp
static new string[] GetSimilarFunctions()
cp
static vector<string> GetSimilarFunctions()

Each of these IDs can be provided as argument to the method YDataLogger.FindDataLogger to obtain an object that can control the corresponding device.

Returns :

an array of strings, each string containing the unique hardwareId of a device function currently connected.

datalogger→AdvertisedValuedatalogger.AdvertisedValue

Short string representing the current state of the function.

dnp
string AdvertisedValue

datalogger→AutoStartdatalogger.AutoStart

Default activation state of the data logger on power up.

dnp
int AutoStart

Writable. Do not forget to call the saveToFlash() method of the module to save the configuration change. Note: if the device doesn't have any time source at his disposal when starting up, it will wait for ~8 seconds before automatically starting to record with an arbitrary timestamp

datalogger→BeaconDrivendatalogger.BeaconDriven

True if the data logger is synchronised with the localization beacon.

dnp
int BeaconDriven

Writable. Changes the type of synchronisation of the data logger. Remember to call the saveToFlash() method of the module if the modification must be kept.

datalogger→FriendlyNamedatalogger.FriendlyName

Global identifier of the function in the format MODULE_NAME.FUNCTION_NAME.

dnp
string FriendlyName

The returned string uses the logical names of the module and of the function if they are defined, otherwise the serial number of the module and the hardware identifier of the function (for example: MyCustomName.relay1)

datalogger→FunctionIddatalogger.FunctionId

Hardware identifier of the data logger, without reference to the module.

dnp
string FunctionId

For example relay1

datalogger→HardwareIddatalogger.HardwareId

Unique hardware identifier of the function in the form SERIAL.FUNCTIONID.

dnp
string HardwareId

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the function (for example RELAYLO1-123456.relay1).

datalogger→IsOnlinedatalogger.IsOnline

Checks if the function is currently reachable.

dnp
bool IsOnline

If there is a cached value for the function in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the function.

datalogger→LogicalNamedatalogger.LogicalName

Logical name of the function.

dnp
string LogicalName

Writable. You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

datalogger→Recordingdatalogger.Recording

Current activation state of the data logger.

dnp
int Recording

Writable. Changes the activation state of the data logger to start/stop recording data.

datalogger→SerialNumberdatalogger.SerialNumber

Serial number of the module, as set by the factory.

dnp
string SerialNumber

datalogger→clearCache()datalogger.clearCache()datalogger→clearCache()[datalogger clearCache]datalogger.clearCache()datalogger.clearCache()datalogger.clearCache()datalogger.clearCache()datalogger.clearCache()datalogger→clearCache()datalogger.clearCache()datalogger.clearCache()

Invalidates the cache.

js
function clearCache()
cpp
void clearCache()
m
-(void) clearCache
pas
clearCache()
vb
procedure clearCache()
cs
void clearCache()
java
void clearCache()
py
clearCache()
php
function clearCache()
ts
async clearCache(): Promise<void>
es
async clearCache()

Invalidates the cache of the data logger attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.

datalogger→describe()datalogger.describe()datalogger→describe()[datalogger describe]datalogger.describe()datalogger.describe()datalogger.describe()datalogger.describe()datalogger.describe()datalogger→describe()datalogger.describe()datalogger.describe()

Returns a short text that describes unambiguously the instance of the data logger in the form TYPE(NAME)=SERIAL.FUNCTIONID.

js
function describe()
cpp
string describe()
m
-(NSString*) describe
pas
string describe(): string
vb
function describe() As String
cs
string describe()
java
String describe()
py
describe()
php
function describe()
ts
async describe(): Promise<string>
es
async describe()

More precisely, TYPE is the type of the function, NAME it the name used for the first access to the function, SERIAL is the serial number of the module if the module is connected or "unresolved", and FUNCTIONID is the hardware identifier of the function if the module is connected. For example, this method returns Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1 if the module is already connected or Relay(BadCustomeName.relay1)=unresolved if the module has not yet been connected. This method does not trigger any USB or TCP transaction and can therefore be used in a debugger.

Returns :

a string that describes the data logger (ex: Relay(MyCustomName.relay1)=RELAYLO1-123456.relay1)

datalogger→forgetAllDataStreams()datalogger.forgetAllDataStreams()datalogger→forgetAllDataStreams()[datalogger forgetAllDataStreams]datalogger.forgetAllDataStreams()datalogger.forgetAllDataStreams()datalogger.forgetAllDataStreams()datalogger.forgetAllDataStreams()datalogger.forgetAllDataStreams()datalogger.forgetAllDataStreams()datalogger→forgetAllDataStreams()datalogger.forgetAllDataStreams()datalogger.forgetAllDataStreams()datalogger.forgetAllDataStreams()datalogger.forgetAllDataStreams()YDataLogger forgetAllDataStreams

Clears the data logger memory and discards all recorded data streams.

js
function forgetAllDataStreams()
cpp
int forgetAllDataStreams()
m
-(int) forgetAllDataStreams
pas
LongInt forgetAllDataStreams(): LongInt
vb
function forgetAllDataStreams() As Integer
cs
int forgetAllDataStreams()
java
int forgetAllDataStreams()
uwp
async Task<int> forgetAllDataStreams()
py
forgetAllDataStreams()
php
function forgetAllDataStreams()
ts
async forgetAllDataStreams(): Promise<number>
es
async forgetAllDataStreams()
dnp
int forgetAllDataStreams()
cp
int forgetAllDataStreams()
cmd
YDataLogger target forgetAllDataStreams

This method also resets the current run index to zero.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

datalogger→get_advertisedValue()
datalogger→advertisedValue()
datalogger.get_advertisedValue()datalogger→get_advertisedValue()[datalogger advertisedValue]datalogger.get_advertisedValue()datalogger.get_advertisedValue()datalogger.get_advertisedValue()datalogger.get_advertisedValue()datalogger.get_advertisedValue()datalogger.get_advertisedValue()datalogger→get_advertisedValue()datalogger.get_advertisedValue()datalogger.get_advertisedValue()datalogger.get_advertisedValue()datalogger.get_advertisedValue()YDataLogger get_advertisedValue

Returns the current value of the data logger (no more than 6 characters).

js
function get_advertisedValue()
cpp
string get_advertisedValue()
m
-(NSString*) advertisedValue
pas
string get_advertisedValue(): string
vb
function get_advertisedValue() As String
cs
string get_advertisedValue()
java
String get_advertisedValue()
uwp
async Task<string> get_advertisedValue()
py
get_advertisedValue()
php
function get_advertisedValue()
ts
async get_advertisedValue(): Promise<string>
es
async get_advertisedValue()
dnp
string get_advertisedValue()
cp
string get_advertisedValue()
cmd
YDataLogger target get_advertisedValue

Returns :

a string corresponding to the current value of the data logger (no more than 6 characters).

On failure, throws an exception or returns YDataLogger.ADVERTISEDVALUE_INVALID.

datalogger→get_autoStart()
datalogger→autoStart()
datalogger.get_autoStart()datalogger→get_autoStart()[datalogger autoStart]datalogger.get_autoStart()datalogger.get_autoStart()datalogger.get_autoStart()datalogger.get_autoStart()datalogger.get_autoStart()datalogger.get_autoStart()datalogger→get_autoStart()datalogger.get_autoStart()datalogger.get_autoStart()datalogger.get_autoStart()datalogger.get_autoStart()YDataLogger get_autoStart

Returns the default activation state of the data logger on power up.

js
function get_autoStart()
cpp
Y_AUTOSTART_enum get_autoStart()
m
-(Y_AUTOSTART_enum) autoStart
pas
Integer get_autoStart(): Integer
vb
function get_autoStart() As Integer
cs
int get_autoStart()
java
int get_autoStart()
uwp
async Task<int> get_autoStart()
py
get_autoStart()
php
function get_autoStart()
ts
async get_autoStart(): Promise<YDataLogger_AutoStart>
es
async get_autoStart()
dnp
int get_autoStart()
cp
int get_autoStart()
cmd
YDataLogger target get_autoStart

Returns :

either YDataLogger.AUTOSTART_OFF or YDataLogger.AUTOSTART_ON, according to the default activation state of the data logger on power up

On failure, throws an exception or returns YDataLogger.AUTOSTART_INVALID.

datalogger→get_beaconDriven()
datalogger→beaconDriven()
datalogger.get_beaconDriven()datalogger→get_beaconDriven()[datalogger beaconDriven]datalogger.get_beaconDriven()datalogger.get_beaconDriven()datalogger.get_beaconDriven()datalogger.get_beaconDriven()datalogger.get_beaconDriven()datalogger.get_beaconDriven()datalogger→get_beaconDriven()datalogger.get_beaconDriven()datalogger.get_beaconDriven()datalogger.get_beaconDriven()datalogger.get_beaconDriven()YDataLogger get_beaconDriven

Returns true if the data logger is synchronised with the localization beacon.

js
function get_beaconDriven()
cpp
Y_BEACONDRIVEN_enum get_beaconDriven()
m
-(Y_BEACONDRIVEN_enum) beaconDriven
pas
Integer get_beaconDriven(): Integer
vb
function get_beaconDriven() As Integer
cs
int get_beaconDriven()
java
int get_beaconDriven()
uwp
async Task<int> get_beaconDriven()
py
get_beaconDriven()
php
function get_beaconDriven()
ts
async get_beaconDriven(): Promise<YDataLogger_BeaconDriven>
es
async get_beaconDriven()
dnp
int get_beaconDriven()
cp
int get_beaconDriven()
cmd
YDataLogger target get_beaconDriven

Returns :

either YDataLogger.BEACONDRIVEN_OFF or YDataLogger.BEACONDRIVEN_ON, according to true if the data logger is synchronised with the localization beacon

On failure, throws an exception or returns YDataLogger.BEACONDRIVEN_INVALID.

datalogger→get_currentRunIndex()
datalogger→currentRunIndex()
datalogger.get_currentRunIndex()datalogger→get_currentRunIndex()[datalogger currentRunIndex]datalogger.get_currentRunIndex()datalogger.get_currentRunIndex()datalogger.get_currentRunIndex()datalogger.get_currentRunIndex()datalogger.get_currentRunIndex()datalogger.get_currentRunIndex()datalogger→get_currentRunIndex()datalogger.get_currentRunIndex()datalogger.get_currentRunIndex()datalogger.get_currentRunIndex()datalogger.get_currentRunIndex()YDataLogger get_currentRunIndex

Returns the current run number, corresponding to the number of times the module was powered on with the dataLogger enabled at some point.

js
function get_currentRunIndex()
cpp
int get_currentRunIndex()
m
-(int) currentRunIndex
pas
LongInt get_currentRunIndex(): LongInt
vb
function get_currentRunIndex() As Integer
cs
int get_currentRunIndex()
java
int get_currentRunIndex()
uwp
async Task<int> get_currentRunIndex()
py
get_currentRunIndex()
php
function get_currentRunIndex()
ts
async get_currentRunIndex(): Promise<number>
es
async get_currentRunIndex()
dnp
int get_currentRunIndex()
cp
int get_currentRunIndex()
cmd
YDataLogger target get_currentRunIndex

Returns :

an integer corresponding to the current run number, corresponding to the number of times the module was powered on with the dataLogger enabled at some point

On failure, throws an exception or returns YDataLogger.CURRENTRUNINDEX_INVALID.

datalogger→get_dataSets()
datalogger→dataSets()
datalogger.get_dataSets()datalogger→get_dataSets()[datalogger dataSets]datalogger.get_dataSets()datalogger.get_dataSets()datalogger.get_dataSets()datalogger.get_dataSets()datalogger.get_dataSets()datalogger.get_dataSets()datalogger→get_dataSets()datalogger.get_dataSets()datalogger.get_dataSets()datalogger.get_dataSets()YDataLogger get_dataSets

Returns a list of YDataSet objects that can be used to retrieve all measures stored by the data logger.

js
function get_dataSets()
cpp
vector<YDataSet> get_dataSets()
m
-(NSMutableArray*) dataSets
pas
TYDataSetArray get_dataSets(): TYDataSetArray
vb
function get_dataSets() As List
cs
List<YDataSet> get_dataSets()
java
ArrayList<YDataSet> get_dataSets()
uwp
async Task<List<YDataSet>> get_dataSets()
py
get_dataSets()
php
function get_dataSets()
ts
async get_dataSets(): Promise<YDataSet[]
es
async get_dataSets()
dnp
YDataSetProxy[] get_dataSets()
cmd
YDataLogger target get_dataSets

This function only works if the device uses a recent firmware, as YDataSet objects are not supported by firmwares older than version 13000.

Returns :

a list of YDataSet object.

On failure, throws an exception or returns an empty list.

datalogger→get_dataStreams()
datalogger→dataStreams()

Builds a list of all data streams hold by the data logger (legacy method).

The caller must pass by reference an empty array to hold DataStream objects, and the function fills it with objects describing available data sequences.

This is the old way to retrieve data from the DataLogger. For new applications, you should rather use get_dataSets() method, or call directly get_recordedData() on the sensor object.

Parameters :

van array of DataStream objects to be filled in

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

datalogger→get_errorMessage()
datalogger→errorMessage()
datalogger.get_errorMessage()datalogger→get_errorMessage()[datalogger errorMessage]datalogger.get_errorMessage()datalogger.get_errorMessage()datalogger.get_errorMessage()datalogger.get_errorMessage()datalogger.get_errorMessage()datalogger→get_errorMessage()datalogger.get_errorMessage()datalogger.get_errorMessage()

Returns the error message of the latest error with the data logger.

js
function get_errorMessage()
cpp
string get_errorMessage()
m
-(NSString*) errorMessage
pas
string get_errorMessage(): string
vb
function get_errorMessage() As String
cs
string get_errorMessage()
java
String get_errorMessage()
py
get_errorMessage()
php
function get_errorMessage()
ts
get_errorMessage(): string
es
get_errorMessage()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a string corresponding to the latest error message that occured while using the data logger object

datalogger→get_errorType()
datalogger→errorType()
datalogger.get_errorType()datalogger→get_errorType()[datalogger errorType]datalogger.get_errorType()datalogger.get_errorType()datalogger.get_errorType()datalogger.get_errorType()datalogger.get_errorType()datalogger→get_errorType()datalogger.get_errorType()datalogger.get_errorType()

Returns the numerical error code of the latest error with the data logger.

js
function get_errorType()
cpp
YRETCODE get_errorType()
m
-(YRETCODE) errorType
pas
YRETCODE get_errorType(): YRETCODE
vb
function get_errorType() As YRETCODE
cs
YRETCODE get_errorType()
java
int get_errorType()
py
get_errorType()
php
function get_errorType()
ts
get_errorType(): number
es
get_errorType()

This method is mostly useful when using the Yoctopuce library with exceptions disabled.

Returns :

a number corresponding to the code of the latest error that occurred while using the data logger object

datalogger→get_friendlyName()
datalogger→friendlyName()
datalogger.get_friendlyName()datalogger→get_friendlyName()[datalogger friendlyName]datalogger.get_friendlyName()datalogger.get_friendlyName()datalogger.get_friendlyName()datalogger→get_friendlyName()datalogger.get_friendlyName()datalogger.get_friendlyName()datalogger.get_friendlyName()datalogger.get_friendlyName()

Returns a global identifier of the data logger in the format MODULE_NAME.FUNCTION_NAME.

js
function get_friendlyName()
cpp
string get_friendlyName()
m
-(NSString*) friendlyName
cs
string get_friendlyName()
java
String get_friendlyName()
py
get_friendlyName()
php
function get_friendlyName()
ts
async get_friendlyName(): Promise<string>
es
async get_friendlyName()
dnp
string get_friendlyName()
cp
string get_friendlyName()

The returned string uses the logical names of the module and of the data logger if they are defined, otherwise the serial number of the module and the hardware identifier of the data logger (for example: MyCustomName.relay1)

Returns :

a string that uniquely identifies the data logger using logical names (ex: MyCustomName.relay1)

On failure, throws an exception or returns YDataLogger.FRIENDLYNAME_INVALID.

datalogger→get_functionDescriptor()
datalogger→functionDescriptor()
datalogger.get_functionDescriptor()datalogger→get_functionDescriptor()[datalogger functionDescriptor]datalogger.get_functionDescriptor()datalogger.get_functionDescriptor()datalogger.get_functionDescriptor()datalogger.get_functionDescriptor()datalogger.get_functionDescriptor()datalogger→get_functionDescriptor()datalogger.get_functionDescriptor()datalogger.get_functionDescriptor()

Returns a unique identifier of type YFUN_DESCR corresponding to the function.

js
function get_functionDescriptor()
cpp
YFUN_DESCR get_functionDescriptor()
m
-(YFUN_DESCR) functionDescriptor
pas
YFUN_DESCR get_functionDescriptor(): YFUN_DESCR
vb
function get_functionDescriptor() As YFUN_DESCR
cs
YFUN_DESCR get_functionDescriptor()
java
String get_functionDescriptor()
py
get_functionDescriptor()
php
function get_functionDescriptor()
ts
async get_functionDescriptor(): Promise<string>
es
async get_functionDescriptor()

This identifier can be used to test if two instances of YFunction reference the same physical function on the same physical device.

Returns :

an identifier of type YFUN_DESCR.

If the function has never been contacted, the returned value is Y$CLASSNAME$.FUNCTIONDESCRIPTOR_INVALID.

datalogger→get_functionId()
datalogger→functionId()
datalogger.get_functionId()datalogger→get_functionId()[datalogger functionId]datalogger.get_functionId()datalogger.get_functionId()datalogger.get_functionId()datalogger.get_functionId()datalogger→get_functionId()datalogger.get_functionId()datalogger.get_functionId()datalogger.get_functionId()datalogger.get_functionId()

Returns the hardware identifier of the data logger, without reference to the module.

js
function get_functionId()
cpp
string get_functionId()
m
-(NSString*) functionId
vb
function get_functionId() As String
cs
string get_functionId()
java
String get_functionId()
py
get_functionId()
php
function get_functionId()
ts
async get_functionId(): Promise<string>
es
async get_functionId()
dnp
string get_functionId()
cp
string get_functionId()

For example relay1

Returns :

a string that identifies the data logger (ex: relay1)

On failure, throws an exception or returns YDataLogger.FUNCTIONID_INVALID.

datalogger→get_hardwareId()
datalogger→hardwareId()
datalogger.get_hardwareId()datalogger→get_hardwareId()[datalogger hardwareId]datalogger.get_hardwareId()datalogger.get_hardwareId()datalogger.get_hardwareId()datalogger.get_hardwareId()datalogger→get_hardwareId()datalogger.get_hardwareId()datalogger.get_hardwareId()datalogger.get_hardwareId()datalogger.get_hardwareId()

Returns the unique hardware identifier of the data logger in the form SERIAL.FUNCTIONID.

js
function get_hardwareId()
cpp
string get_hardwareId()
m
-(NSString*) hardwareId
vb
function get_hardwareId() As String
cs
string get_hardwareId()
java
String get_hardwareId()
py
get_hardwareId()
php
function get_hardwareId()
ts
async get_hardwareId(): Promise<string>
es
async get_hardwareId()
dnp
string get_hardwareId()
cp
string get_hardwareId()

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the data logger (for example RELAYLO1-123456.relay1).

Returns :

a string that uniquely identifies the data logger (ex: RELAYLO1-123456.relay1)

On failure, throws an exception or returns YDataLogger.HARDWAREID_INVALID.

datalogger→get_logicalName()
datalogger→logicalName()
datalogger.get_logicalName()datalogger→get_logicalName()[datalogger logicalName]datalogger.get_logicalName()datalogger.get_logicalName()datalogger.get_logicalName()datalogger.get_logicalName()datalogger.get_logicalName()datalogger.get_logicalName()datalogger→get_logicalName()datalogger.get_logicalName()datalogger.get_logicalName()datalogger.get_logicalName()datalogger.get_logicalName()YDataLogger get_logicalName

Returns the logical name of the data logger.

js
function get_logicalName()
cpp
string get_logicalName()
m
-(NSString*) logicalName
pas
string get_logicalName(): string
vb
function get_logicalName() As String
cs
string get_logicalName()
java
String get_logicalName()
uwp
async Task<string> get_logicalName()
py
get_logicalName()
php
function get_logicalName()
ts
async get_logicalName(): Promise<string>
es
async get_logicalName()
dnp
string get_logicalName()
cp
string get_logicalName()
cmd
YDataLogger target get_logicalName

Returns :

a string corresponding to the logical name of the data logger.

On failure, throws an exception or returns YDataLogger.LOGICALNAME_INVALID.

datalogger→get_module()
datalogger→module()
datalogger.get_module()datalogger→get_module()[datalogger module]datalogger.get_module()datalogger.get_module()datalogger.get_module()datalogger.get_module()datalogger.get_module()datalogger→get_module()datalogger.get_module()datalogger.get_module()datalogger.get_module()datalogger.get_module()

Gets the YModule object for the device on which the function is located.

js
function get_module()
cpp
YModule * get_module()
m
-(YModule*) module
pas
TYModule get_module(): TYModule
vb
function get_module() As YModule
cs
YModule get_module()
java
YModule get_module()
py
get_module()
php
function get_module()
ts
async get_module(): Promise<YModule>
es
async get_module()
dnp
YModuleProxy get_module()
cp
YModuleProxy * get_module()

If the function cannot be located on any module, the returned instance of YModule is not shown as on-line.

Returns :

an instance of YModule

datalogger→get_module_async()
datalogger→module_async()
datalogger.get_module_async()

Gets the YModule object for the device on which the function is located (asynchronous version).

js
function get_module_async(callback, context)

If the function cannot be located on any module, the returned YModule object does not show as on-line.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking Firefox JavaScript VM that does not implement context switching during blocking I/O calls. See the documentation section on asynchronous JavasSript calls for more details.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the requested YModule object
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

datalogger→get_recording()
datalogger→recording()
datalogger.get_recording()datalogger→get_recording()[datalogger recording]datalogger.get_recording()datalogger.get_recording()datalogger.get_recording()datalogger.get_recording()datalogger.get_recording()datalogger.get_recording()datalogger→get_recording()datalogger.get_recording()datalogger.get_recording()datalogger.get_recording()datalogger.get_recording()YDataLogger get_recording

Returns the current activation state of the data logger.

js
function get_recording()
cpp
Y_RECORDING_enum get_recording()
m
-(Y_RECORDING_enum) recording
pas
Integer get_recording(): Integer
vb
function get_recording() As Integer
cs
int get_recording()
java
int get_recording()
uwp
async Task<int> get_recording()
py
get_recording()
php
function get_recording()
ts
async get_recording(): Promise<YDataLogger_Recording>
es
async get_recording()
dnp
int get_recording()
cp
int get_recording()
cmd
YDataLogger target get_recording

Returns :

a value among YDataLogger.RECORDING_OFF, YDataLogger.RECORDING_ON and YDataLogger.RECORDING_PENDING corresponding to the current activation state of the data logger

On failure, throws an exception or returns YDataLogger.RECORDING_INVALID.

datalogger→get_serialNumber()
datalogger→serialNumber()
datalogger.get_serialNumber()datalogger→get_serialNumber()[datalogger serialNumber]datalogger.get_serialNumber()datalogger.get_serialNumber()datalogger.get_serialNumber()datalogger.get_serialNumber()datalogger.get_serialNumber()datalogger.get_serialNumber()datalogger→get_serialNumber()datalogger.get_serialNumber()datalogger.get_serialNumber()datalogger.get_serialNumber()datalogger.get_serialNumber()YDataLogger get_serialNumber

Returns the serial number of the module, as set by the factory.

js
function get_serialNumber()
cpp
string get_serialNumber()
m
-(NSString*) serialNumber
pas
string get_serialNumber(): string
vb
function get_serialNumber() As String
cs
string get_serialNumber()
java
String get_serialNumber()
uwp
async Task<string> get_serialNumber()
py
get_serialNumber()
php
function get_serialNumber()
ts
async get_serialNumber(): Promise<string>
es
async get_serialNumber()
dnp
string get_serialNumber()
cp
string get_serialNumber()
cmd
YDataLogger target get_serialNumber

Returns :

a string corresponding to the serial number of the module, as set by the factory.

On failure, throws an exception or returns YFunction.SERIALNUMBER_INVALID.

datalogger→get_timeUTC()
datalogger→timeUTC()
datalogger.get_timeUTC()datalogger→get_timeUTC()[datalogger timeUTC]datalogger.get_timeUTC()datalogger.get_timeUTC()datalogger.get_timeUTC()datalogger.get_timeUTC()datalogger.get_timeUTC()datalogger.get_timeUTC()datalogger→get_timeUTC()datalogger.get_timeUTC()datalogger.get_timeUTC()datalogger.get_timeUTC()datalogger.get_timeUTC()YDataLogger get_timeUTC

Returns the Unix timestamp for current UTC time, if known.

js
function get_timeUTC()
cpp
s64 get_timeUTC()
m
-(s64) timeUTC
pas
int64 get_timeUTC(): int64
vb
function get_timeUTC() As Long
cs
long get_timeUTC()
java
long get_timeUTC()
uwp
async Task<long> get_timeUTC()
py
get_timeUTC()
php
function get_timeUTC()
ts
async get_timeUTC(): Promise<number>
es
async get_timeUTC()
dnp
long get_timeUTC()
cp
s64 get_timeUTC()
cmd
YDataLogger target get_timeUTC

Returns :

an integer corresponding to the Unix timestamp for current UTC time, if known

On failure, throws an exception or returns YDataLogger.TIMEUTC_INVALID.

datalogger→get_usage()
datalogger→usage()
datalogger.get_usage()datalogger→get_usage()[datalogger usage]datalogger.get_usage()datalogger.get_usage()datalogger.get_usage()datalogger.get_usage()datalogger.get_usage()datalogger.get_usage()datalogger→get_usage()datalogger.get_usage()datalogger.get_usage()datalogger.get_usage()datalogger.get_usage()YDataLogger get_usage

Returns the percentage of datalogger memory in use.

js
function get_usage()
cpp
int get_usage()
m
-(int) usage
pas
LongInt get_usage(): LongInt
vb
function get_usage() As Integer
cs
int get_usage()
java
int get_usage()
uwp
async Task<int> get_usage()
py
get_usage()
php
function get_usage()
ts
async get_usage(): Promise<number>
es
async get_usage()
dnp
int get_usage()
cp
int get_usage()
cmd
YDataLogger target get_usage

Returns :

an integer corresponding to the percentage of datalogger memory in use

On failure, throws an exception or returns YDataLogger.USAGE_INVALID.

datalogger→get_userData()
datalogger→userData()
datalogger.get_userData()datalogger→get_userData()[datalogger userData]datalogger.get_userData()datalogger.get_userData()datalogger.get_userData()datalogger.get_userData()datalogger.get_userData()datalogger→get_userData()datalogger.get_userData()datalogger.get_userData()

Returns the value of the userData attribute, as previously stored using method set_userData.

js
function get_userData()
cpp
void * get_userData()
m
-(id) userData
pas
Tobject get_userData(): Tobject
vb
function get_userData() As Object
cs
object get_userData()
java
Object get_userData()
py
get_userData()
php
function get_userData()
ts
async get_userData(): Promise<object|null>
es
async get_userData()

This attribute is never touched directly by the API, and is at disposal of the caller to store a context.

Returns :

the object stored previously by the caller.

datalogger→isOnline()datalogger.isOnline()datalogger→isOnline()[datalogger isOnline]datalogger.isOnline()datalogger.isOnline()datalogger.isOnline()datalogger.isOnline()datalogger.isOnline()datalogger→isOnline()datalogger.isOnline()datalogger.isOnline()datalogger.isOnline()datalogger.isOnline()

Checks if the data logger is currently reachable, without raising any error.

js
function isOnline()
cpp
bool isOnline()
m
-(BOOL) isOnline
pas
boolean isOnline(): boolean
vb
function isOnline() As Boolean
cs
bool isOnline()
java
boolean isOnline()
py
isOnline()
php
function isOnline()
ts
async isOnline(): Promise<boolean>
es
async isOnline()
dnp
bool isOnline()
cp
bool isOnline()

If there is a cached value for the data logger in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the data logger.

Returns :

true if the data logger can be reached, and false otherwise

datalogger→isOnline_async()datalogger.isOnline_async()

Checks if the data logger is currently reachable, without raising any error (asynchronous version).

js
function isOnline_async(callback, context)

If there is a cached value for the data logger in cache, that has not yet expired, the device is considered reachable. No exception is raised if there is an error while trying to contact the device hosting the requested function.

This asynchronous version exists only in Javascript. It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine.

Parameters :

callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the boolean result
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

datalogger→isReadOnly()datalogger→isReadOnly()[datalogger isReadOnly]datalogger.isReadOnly()datalogger.isReadOnly()datalogger.isReadOnly()datalogger.isReadOnly()datalogger.isReadOnly()datalogger.isReadOnly()datalogger→isReadOnly()datalogger.isReadOnly()datalogger.isReadOnly()datalogger.isReadOnly()datalogger.isReadOnly()YDataLogger isReadOnly

Test if the function is readOnly.

cpp
bool isReadOnly()
m
-(bool) isReadOnly
pas
boolean isReadOnly(): boolean
vb
function isReadOnly() As Boolean
cs
bool isReadOnly()
java
boolean isReadOnly()
uwp
async Task<bool> isReadOnly()
py
isReadOnly()
php
function isReadOnly()
ts
async isReadOnly(): Promise<boolean>
es
async isReadOnly()
dnp
bool isReadOnly()
cp
bool isReadOnly()
cmd
YDataLogger target isReadOnly

Return true if the function is write protected or that the function is not available.

Returns :

true if the function is readOnly or not online.

datalogger→load()datalogger.load()datalogger→load()[datalogger load: ]datalogger.load()datalogger.load()datalogger.load()datalogger.load()datalogger.load()datalogger→load()datalogger.load()datalogger.load()

Preloads the data logger cache with a specified validity duration.

js
function load(msValidity)
cpp
YRETCODE load(int msValidity)
m
-(YRETCODE) load: (u64) msValidity
pas
YRETCODE load(msValidity: u64): YRETCODE
vb
function load(ByVal msValidity As Long) As YRETCODE
cs
YRETCODE load(ulong msValidity)
java
int load(long msValidity)
py
load(msValidity)
php
function load($msValidity)
ts
async load(msValidity: number): Promise<number>
es
async load(msValidity)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

Parameters :

msValidityan integer corresponding to the validity attributed to the loaded function parameters, in milliseconds

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

datalogger→loadAttribute()datalogger.loadAttribute()datalogger→loadAttribute()[datalogger loadAttribute: ]datalogger.loadAttribute()datalogger.loadAttribute()datalogger.loadAttribute()datalogger.loadAttribute()datalogger.loadAttribute()datalogger.loadAttribute()datalogger→loadAttribute()datalogger.loadAttribute()datalogger.loadAttribute()datalogger.loadAttribute()datalogger.loadAttribute()

Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.

js
function loadAttribute(attrName)
cpp
string loadAttribute(string attrName)
m
-(NSString*) loadAttribute: (NSString*) attrName
pas
string loadAttribute(attrName: string): string
vb
function loadAttribute(ByVal attrName As String) As String
cs
string loadAttribute(string attrName)
java
String loadAttribute(String attrName)
uwp
async Task<string> loadAttribute(string attrName)
py
loadAttribute(attrName)
php
function loadAttribute($attrName)
ts
async loadAttribute(attrName: string): Promise<string>
es
async loadAttribute(attrName)
dnp
string loadAttribute(string attrName)
cp
string loadAttribute(string attrName)

Parameters :

attrNamethe name of the requested attribute

Returns :

a string with the value of the the attribute

On failure, throws an exception or returns an empty string.

datalogger→load_async()datalogger.load_async()

Preloads the data logger cache with a specified validity duration (asynchronous version).

js
function load_async(msValidity, callback, context)

By default, whenever accessing a device, all function attributes are kept in cache for the standard duration (5 ms). This method can be used to temporarily mark the cache as valid for a longer period, in order to reduce network traffic for instance.

This asynchronous version exists only in JavaScript. It uses a callback instead of a return value in order to avoid blocking the JavaScript virtual machine.

Parameters :

msValidityan integer corresponding to the validity of the loaded function parameters, in milliseconds
callbackcallback function that is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the receiving function object and the error code (or YAPI.SUCCESS)
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing : the result is provided to the callback.

datalogger→muteValueCallbacks()datalogger.muteValueCallbacks()datalogger→muteValueCallbacks()[datalogger muteValueCallbacks]datalogger.muteValueCallbacks()datalogger.muteValueCallbacks()datalogger.muteValueCallbacks()datalogger.muteValueCallbacks()datalogger.muteValueCallbacks()datalogger.muteValueCallbacks()datalogger→muteValueCallbacks()datalogger.muteValueCallbacks()datalogger.muteValueCallbacks()datalogger.muteValueCallbacks()datalogger.muteValueCallbacks()YDataLogger muteValueCallbacks

Disables the propagation of every new advertised value to the parent hub.

js
function muteValueCallbacks()
cpp
int muteValueCallbacks()
m
-(int) muteValueCallbacks
pas
LongInt muteValueCallbacks(): LongInt
vb
function muteValueCallbacks() As Integer
cs
int muteValueCallbacks()
java
int muteValueCallbacks()
uwp
async Task<int> muteValueCallbacks()
py
muteValueCallbacks()
php
function muteValueCallbacks()
ts
async muteValueCallbacks(): Promise<number>
es
async muteValueCallbacks()
dnp
int muteValueCallbacks()
cp
int muteValueCallbacks()
cmd
YDataLogger target muteValueCallbacks

You can use this function to save bandwidth and CPU on computers with limited resources, or to prevent unwanted invocations of the HTTP callback. Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

datalogger→nextDataLogger()datalogger.nextDataLogger()datalogger→nextDataLogger()[datalogger nextDataLogger]datalogger.nextDataLogger()datalogger.nextDataLogger()datalogger.nextDataLogger()datalogger.nextDataLogger()datalogger.nextDataLogger()datalogger.nextDataLogger()datalogger→nextDataLogger()datalogger.nextDataLogger()datalogger.nextDataLogger()

Continues the enumeration of data loggers started using yFirstDataLogger().

js
function nextDataLogger()
cpp
YDataLogger * nextDataLogger()
m
-(nullable YDataLogger*) nextDataLogger
pas
TYDataLogger nextDataLogger(): TYDataLogger
vb
function nextDataLogger() As YDataLogger
cs
YDataLogger nextDataLogger()
java
YDataLogger nextDataLogger()
uwp
YDataLogger nextDataLogger()
py
nextDataLogger()
php
function nextDataLogger()
ts
nextDataLogger(): YDataLogger | null
es
nextDataLogger()

Caution: You can't make any assumption about the returned data loggers order. If you want to find a specific a data logger, use DataLogger.findDataLogger() and a hardwareID or a logical name.

Returns :

a pointer to a YDataLogger object, corresponding to a data logger currently online, or a null pointer if there are no more data loggers to enumerate.

datalogger→registerValueCallback()datalogger.registerValueCallback()datalogger→registerValueCallback()[datalogger registerValueCallback: ]datalogger.registerValueCallback()datalogger.registerValueCallback()datalogger.registerValueCallback()datalogger.registerValueCallback()datalogger.registerValueCallback()datalogger.registerValueCallback()datalogger→registerValueCallback()datalogger.registerValueCallback()datalogger.registerValueCallback()

Registers the callback function that is invoked on every change of advertised value.

js
function registerValueCallback(callback)
cpp
int registerValueCallback(YDataLoggerValueCallback callback)
m
-(int) registerValueCallback: (YDataLoggerValueCallback _Nullable) callback
pas
LongInt registerValueCallback(callback: TYDataLoggerValueCallback): LongInt
vb
function registerValueCallback(ByVal callback As YDataLoggerValueCallback) As Integer
cs
int registerValueCallback(ValueCallback callback)
java
int registerValueCallback(UpdateCallback callback)
uwp
async Task<int> registerValueCallback(ValueCallback callback)
py
registerValueCallback(callback)
php
function registerValueCallback($callback)
ts
async registerValueCallback(callback: YDataLoggerValueCallback | null): Promise<number>
es
async registerValueCallback(callback)

The callback is invoked only during the execution of ySleep or yHandleEvents. This provides control over the time when the callback is triggered. For good responsiveness, remember to call one of these two functions periodically. To unregister a callback, pass a null pointer as argument.

Parameters :

callbackthe callback function to call, or a null pointer. The callback function should take two arguments: the function object of which the value has changed, and the character string describing the new advertised value.

datalogger→set_autoStart()
datalogger→setAutoStart()
datalogger.set_autoStart()datalogger→set_autoStart()[datalogger setAutoStart: ]datalogger.set_autoStart()datalogger.set_autoStart()datalogger.set_autoStart()datalogger.set_autoStart()datalogger.set_autoStart()datalogger.set_autoStart()datalogger→set_autoStart()datalogger.set_autoStart()datalogger.set_autoStart()datalogger.set_autoStart()datalogger.set_autoStart()YDataLogger set_autoStart

Changes the default activation state of the data logger on power up.

js
function set_autoStart(newval)
cpp
int set_autoStart(Y_AUTOSTART_enum newval)
m
-(int) setAutoStart: (Y_AUTOSTART_enum) newval
pas
integer set_autoStart(newval: Integer): integer
vb
function set_autoStart(ByVal newval As Integer) As Integer
cs
int set_autoStart(int newval)
java
int set_autoStart(int newval)
uwp
async Task<int> set_autoStart(int newval)
py
set_autoStart(newval)
php
function set_autoStart($newval)
ts
async set_autoStart(newval: YDataLogger_AutoStart): Promise<number>
es
async set_autoStart(newval)
dnp
int set_autoStart(int newval)
cp
int set_autoStart(int newval)
cmd
YDataLogger target set_autoStart newval

Do not forget to call the saveToFlash() method of the module to save the configuration change. Note: if the device doesn't have any time source at his disposal when starting up, it will wait for ~8 seconds before automatically starting to record with an arbitrary timestamp

Parameters :

newvaleither YDataLogger.AUTOSTART_OFF or YDataLogger.AUTOSTART_ON, according to the default activation state of the data logger on power up

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

datalogger→set_beaconDriven()
datalogger→setBeaconDriven()
datalogger.set_beaconDriven()datalogger→set_beaconDriven()[datalogger setBeaconDriven: ]datalogger.set_beaconDriven()datalogger.set_beaconDriven()datalogger.set_beaconDriven()datalogger.set_beaconDriven()datalogger.set_beaconDriven()datalogger.set_beaconDriven()datalogger→set_beaconDriven()datalogger.set_beaconDriven()datalogger.set_beaconDriven()datalogger.set_beaconDriven()datalogger.set_beaconDriven()YDataLogger set_beaconDriven

Changes the type of synchronisation of the data logger.

js
function set_beaconDriven(newval)
cpp
int set_beaconDriven(Y_BEACONDRIVEN_enum newval)
m
-(int) setBeaconDriven: (Y_BEACONDRIVEN_enum) newval
pas
integer set_beaconDriven(newval: Integer): integer
vb
function set_beaconDriven(ByVal newval As Integer) As Integer
cs
int set_beaconDriven(int newval)
java
int set_beaconDriven(int newval)
uwp
async Task<int> set_beaconDriven(int newval)
py
set_beaconDriven(newval)
php
function set_beaconDriven($newval)
ts
async set_beaconDriven(newval: YDataLogger_BeaconDriven): Promise<number>
es
async set_beaconDriven(newval)
dnp
int set_beaconDriven(int newval)
cp
int set_beaconDriven(int newval)
cmd
YDataLogger target set_beaconDriven newval

Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvaleither YDataLogger.BEACONDRIVEN_OFF or YDataLogger.BEACONDRIVEN_ON, according to the type of synchronisation of the data logger

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

datalogger→set_logicalName()
datalogger→setLogicalName()
datalogger.set_logicalName()datalogger→set_logicalName()[datalogger setLogicalName: ]datalogger.set_logicalName()datalogger.set_logicalName()datalogger.set_logicalName()datalogger.set_logicalName()datalogger.set_logicalName()datalogger.set_logicalName()datalogger→set_logicalName()datalogger.set_logicalName()datalogger.set_logicalName()datalogger.set_logicalName()datalogger.set_logicalName()YDataLogger set_logicalName

Changes the logical name of the data logger.

js
function set_logicalName(newval)
cpp
int set_logicalName(string newval)
m
-(int) setLogicalName: (NSString*) newval
pas
integer set_logicalName(newval: string): integer
vb
function set_logicalName(ByVal newval As String) As Integer
cs
int set_logicalName(string newval)
java
int set_logicalName(String newval)
uwp
async Task<int> set_logicalName(string newval)
py
set_logicalName(newval)
php
function set_logicalName($newval)
ts
async set_logicalName(newval: string): Promise<number>
es
async set_logicalName(newval)
dnp
int set_logicalName(string newval)
cp
int set_logicalName(string newval)
cmd
YDataLogger target set_logicalName newval

You can use yCheckLogicalName() prior to this call to make sure that your parameter is valid. Remember to call the saveToFlash() method of the module if the modification must be kept.

Parameters :

newvala string corresponding to the logical name of the data logger.

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

datalogger→set_recording()
datalogger→setRecording()
datalogger.set_recording()datalogger→set_recording()[datalogger setRecording: ]datalogger.set_recording()datalogger.set_recording()datalogger.set_recording()datalogger.set_recording()datalogger.set_recording()datalogger.set_recording()datalogger→set_recording()datalogger.set_recording()datalogger.set_recording()datalogger.set_recording()datalogger.set_recording()YDataLogger set_recording

Changes the activation state of the data logger to start/stop recording data.

js
function set_recording(newval)
cpp
int set_recording(Y_RECORDING_enum newval)
m
-(int) setRecording: (Y_RECORDING_enum) newval
pas
integer set_recording(newval: Integer): integer
vb
function set_recording(ByVal newval As Integer) As Integer
cs
int set_recording(int newval)
java
int set_recording(int newval)
uwp
async Task<int> set_recording(int newval)
py
set_recording(newval)
php
function set_recording($newval)
ts
async set_recording(newval: YDataLogger_Recording): Promise<number>
es
async set_recording(newval)
dnp
int set_recording(int newval)
cp
int set_recording(int newval)
cmd
YDataLogger target set_recording newval

Parameters :

newvala value among YDataLogger.RECORDING_OFF, YDataLogger.RECORDING_ON and YDataLogger.RECORDING_PENDING corresponding to the activation state of the data logger to start/stop recording data

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

datalogger→set_timeUTC()
datalogger→setTimeUTC()
datalogger.set_timeUTC()datalogger→set_timeUTC()[datalogger setTimeUTC: ]datalogger.set_timeUTC()datalogger.set_timeUTC()datalogger.set_timeUTC()datalogger.set_timeUTC()datalogger.set_timeUTC()datalogger.set_timeUTC()datalogger→set_timeUTC()datalogger.set_timeUTC()datalogger.set_timeUTC()datalogger.set_timeUTC()datalogger.set_timeUTC()YDataLogger set_timeUTC

Changes the current UTC time reference used for recorded data.

js
function set_timeUTC(newval)
cpp
int set_timeUTC(s64 newval)
m
-(int) setTimeUTC: (s64) newval
pas
integer set_timeUTC(newval: int64): integer
vb
function set_timeUTC(ByVal newval As Long) As Integer
cs
int set_timeUTC(long newval)
java
int set_timeUTC(long newval)
uwp
async Task<int> set_timeUTC(long newval)
py
set_timeUTC(newval)
php
function set_timeUTC($newval)
ts
async set_timeUTC(newval: number): Promise<number>
es
async set_timeUTC(newval)
dnp
int set_timeUTC(long newval)
cp
int set_timeUTC(s64 newval)
cmd
YDataLogger target set_timeUTC newval

Parameters :

newvalan integer corresponding to the current UTC time reference used for recorded data

Returns :

YAPI.SUCCESS if the call succeeds.

On failure, throws an exception or returns a negative error code.

datalogger→set_userData()
datalogger→setUserData()
datalogger.set_userData()datalogger→set_userData()[datalogger setUserData: ]datalogger.set_userData()datalogger.set_userData()datalogger.set_userData()datalogger.set_userData()datalogger.set_userData()datalogger→set_userData()datalogger.set_userData()datalogger.set_userData()

Stores a user context provided as argument in the userData attribute of the function.

js
function set_userData(data)
cpp
void set_userData(void * data)
m
-(void) setUserData: (id) data
pas
set_userData(data: Tobject)
vb
procedure set_userData(ByVal data As Object)
cs
void set_userData(object data)
java
void set_userData(Object data)
py
set_userData(data)
php
function set_userData($data)
ts
async set_userData(data: object|null): Promise<void>
es
async set_userData(data)

This attribute is never touched by the API, and is at disposal of the caller to store a context.

Parameters :

dataany kind of object to be stored

datalogger→unmuteValueCallbacks()datalogger.unmuteValueCallbacks()datalogger→unmuteValueCallbacks()[datalogger unmuteValueCallbacks]datalogger.unmuteValueCallbacks()datalogger.unmuteValueCallbacks()datalogger.unmuteValueCallbacks()datalogger.unmuteValueCallbacks()datalogger.unmuteValueCallbacks()datalogger.unmuteValueCallbacks()datalogger→unmuteValueCallbacks()datalogger.unmuteValueCallbacks()datalogger.unmuteValueCallbacks()datalogger.unmuteValueCallbacks()datalogger.unmuteValueCallbacks()YDataLogger unmuteValueCallbacks

Re-enables the propagation of every new advertised value to the parent hub.

js
function unmuteValueCallbacks()
cpp
int unmuteValueCallbacks()
m
-(int) unmuteValueCallbacks
pas
LongInt unmuteValueCallbacks(): LongInt
vb
function unmuteValueCallbacks() As Integer
cs
int unmuteValueCallbacks()
java
int unmuteValueCallbacks()
uwp
async Task<int> unmuteValueCallbacks()
py
unmuteValueCallbacks()
php
function unmuteValueCallbacks()
ts
async unmuteValueCallbacks(): Promise<number>
es
async unmuteValueCallbacks()
dnp
int unmuteValueCallbacks()
cp
int unmuteValueCallbacks()
cmd
YDataLogger target unmuteValueCallbacks

This function reverts the effect of a previous call to muteValueCallbacks(). Remember to call the saveToFlash() method of the module if the modification must be kept.

Returns :

YAPI.SUCCESS when the call succeeds.

On failure, throws an exception or returns a negative error code.

datalogger→wait_async()datalogger.wait_async()datalogger.wait_async()datalogger.wait_async()

Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.

js
function wait_async(callback, context)
ts
wait_async(callback: Function, context: object)
es
wait_async(callback, context)

The callback function can therefore freely issue synchronous or asynchronous commands, without risking to block the JavaScript VM.

Parameters :

callbackcallback function that is invoked when all pending commands on the module are completed. The callback function receives two arguments: the caller-specific context object and the receiving function object.
contextcaller-specific object that is passed as-is to the callback function

Returns :

nothing.

24.10. Class YDataSet

Recorded data sequence, as returned by sensor.get_recordedData()

YDataSet objects make it possible to retrieve a set of recorded measures for a given sensor and a specified time interval. They can be used to load data points with a progress report. When the YDataSet object is instantiated by the sensor.get_recordedData() function, no data is yet loaded from the module. It is only when the loadMore() method is called over and over than data will be effectively loaded from the dataLogger.

A preview of available measures is available using the function get_preview() as soon as loadMore() has been called once. Measures themselves are available using function get_measures() when loaded by subsequent calls to loadMore().

This class can only be used on devices that use a relatively recent firmware, as YDataSet objects are not supported by firmwares older than version 13000.

In order to use the functions described here, you should include:

js
<script type='text/javascript' src='yocto_module.js'></script>
cpp
#include "yocto_module.h"
m
#import "yocto_module.h"
pas
uses yocto_module;
vb
yocto_module.vb
cs
yocto_module.cs
java
import com.yoctopuce.YoctoAPI.YDataSet;
uwp
import com.yoctopuce.YoctoAPI.YDataSet;
py
from yocto_module import *
php
require_once('yocto_module.php');
ts
in HTML: import { YDataSet } from '../../dist/esm/yocto_module.js';
in Node.js: import { YDataSet } from 'yoctolib-cjs/yocto_module.js';
es
in HTML: <script src="../../lib/yocto_module.js"></script>
in node.js: require('yoctolib-es2017/yocto_module.js');
dnp
import YoctoProxyAPI.YDataSetProxy
cp
#include "yocto_module_proxy.h"
ml
import YoctoProxyAPI.YDataSetProxy
Global functions
YDataSet.Init(sensorName, startTime, endTime)

Retrieves a YDataSet object holding historical data for a sensor given by its name or hardware identifier, for a specified time interval.

YDataSet methods
dataset→get_endTimeUTC()

Returns the end time of the dataset, relative to the Jan 1, 1970.

dataset→get_functionId()

Returns the hardware identifier of the function that performed the measure, without reference to the module.

dataset→get_hardwareId()

Returns the unique hardware identifier of the function who performed the measures, in the form SERIAL.FUNCTIONID.

dataset→get_measures()

Returns all measured values currently available for this DataSet, as a list of YMeasure objects.

dataset→get_measuresAt(measure)

Returns the detailed set of measures for the time interval corresponding to a given condensed measures previously returned by get_preview().

dataset→get_measuresAvgAt(index)

Returns the average value observed during the time interval covered by the specified entry in the preview.

dataset→get_measuresEndTimeAt(index)

Returns the end time of the specified entry in the preview, relative to the Jan 1, 1970 UTC (Unix timestamp).

dataset→get_measuresMaxAt(index)

Returns the largest value observed during the time interval covered by the specified entry in the preview.

dataset→get_measuresMinAt(index)

Returns the smallest value observed during the time interval covered by the specified entry in the preview.

dataset→get_measuresRecordCount()

Returns the number of measurements currently loaded for this data set.

dataset→get_measuresStartTimeAt(index)

Returns the start time of the specified entry in the preview, relative to the Jan 1, 1970 UTC (Unix timestamp).

dataset→get_preview()

Returns a condensed version of the measures that can retrieved in this YDataSet, as a list of YMeasure objects.

dataset→get_previewAvgAt(index)

Returns the average value observed during the time interval covered by the specified entry in the preview.

dataset→get_previewEndTimeAt(index)

Returns the end time of the specified entry in the preview, relative to the Jan 1, 1970 UTC (Unix timestamp).

dataset→get_previewMaxAt(index)

Returns the largest value observed during the time interval covered by the specified entry in the preview.

dataset→get_previewMinAt(index)

Returns the smallest value observed during the time interval covered by the specified entry in the preview.

dataset→get_previewRecordCount()

Returns the number of entries in the preview summarizing this data set

dataset→get_previewStartTimeAt(index)

Returns the start time of the specified entry in the preview, relative to the Jan 1, 1970 UTC (Unix timestamp).

dataset→get_progress()

Returns the progress of the downloads of the measures from the data logger, on a scale from 0 to 100.

dataset→get_startTimeUTC()

Returns the start time of the dataset, relative to the Jan 1, 1970.

dataset→get_summary()

Returns an YMeasure object which summarizes the whole YDataSet.

dataset→get_summaryAvg()

Returns the average value observed during the time interval covered by this data set.

dataset→get_summaryEndTime()

Returns the end time of the last measure in the data set, relative to the Jan 1, 1970 UTC (Unix timestamp).

dataset→get_summaryMax()

Returns the largest value observed during the time interval covered by this data set.

dataset→get_summaryMin()

Returns the smallest value observed during the time interval covered by this data set.

dataset→get_summaryStartTime()

Returns the start time of the first measure in the data set, relative to the Jan 1, 1970 UTC (Unix timestamp).

dataset→get_unit()

Returns the measuring unit for the measured value.

dataset→loadMore()

Loads the the next block of measures from the dataLogger, and updates the progress indicator.

dataset→loadMore_async(callback, context)

Loads the the next block of measures from the dataLogger asynchronously.

YDataSet.Init()
YDataSet.Init()

Retrieves a YDataSet object holding historical data for a sensor given by its name or hardware identifier, for a specified time interval.

The measures will be retrieved from the data logger, which must have been turned on at the desired time. Methods of the YDataSet class makes it possible to get an overview of the recorded data, and to load progressively a large set of measures from the data logger.

Parameters :

sensorNamelogical name or hardware identifier of the sensor for which data logger records are requested.
startTimethe start of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without initial limit.
endTimethe end of the desired measure time interval, as a Unix timestamp, i.e. the number of seconds since January 1, 1970 UTC. The special value 0 can be used to include any measure, without ending limit.

Returns :

an instance of YDataSet, providing access to historical data. Past measures can be loaded progressively using methods from the YDataSet object.

dataset→get_endTimeUTC()
dataset→endTimeUTC()
dataset.get_endTimeUTC()dataset→get_endTimeUTC()[dataset endTimeUTC]dataset.get_endTimeUTC()dataset.get_endTimeUTC()dataset.get_endTimeUTC()dataset.get_endTimeUTC()dataset.get_endTimeUTC()dataset.get_endTimeUTC()dataset→get_endTimeUTC()dataset.get_endTimeUTC()dataset.get_endTimeUTC()dataset.get_endTimeUTC()dataset.get_endTimeUTC()

Returns the end time of the dataset, relative to the Jan 1, 1970.

js
function get_endTimeUTC()
cpp
s64 get_endTimeUTC()
m
-(s64) endTimeUTC
pas
int64 get_endTimeUTC(): int64
vb
function get_endTimeUTC() As Long
cs
long get_endTimeUTC()
java
long get_endTimeUTC()
uwp
async Task<long> get_endTimeUTC()
py
get_endTimeUTC()
php
function get_endTimeUTC()
ts
async get_endTimeUTC(): Promise<number>
es
async get_endTimeUTC()
dnp
long get_endTimeUTC()
cp
s64 get_endTimeUTC()

When the YDataSet object is created, the end time is the value passed in parameter to the get_dataSet() function. After the very first call to loadMore(), the end time is updated to reflect the timestamp of the last measure actually found in the dataLogger within the specified range.

DEPRECATED: This method has been replaced by get_summary() which contain more precise informations.

Returns :

an unsigned number corresponding to the number of seconds between the Jan 1, 1970 and the end of this data set (i.e. Unix time representation of the absolute time).

dataset→get_functionId()
dataset→functionId()
dataset.get_functionId()dataset→get_functionId()[dataset functionId]dataset.get_functionId()dataset.get_functionId()dataset.get_functionId()dataset.get_functionId()dataset.get_functionId()dataset.get_functionId()dataset→get_functionId()dataset.get_functionId()dataset.get_functionId()dataset.get_functionId()dataset.get_functionId()

Returns the hardware identifier of the function that performed the measure, without reference to the module.

js
function get_functionId()
cpp
string get_functionId()
m
-(NSString*) functionId
pas
string get_functionId(): string
vb
function get_functionId() As String
cs
string get_functionId()
java
String get_functionId()
uwp
async Task<string> get_functionId()
py
get_functionId()
php
function get_functionId()
ts
async get_functionId(): Promise<string>
es
async get_functionId()
dnp
string get_functionId()
cp
string get_functionId()

For example temperature1.

Returns :

a string that identifies the function (ex: temperature1)

dataset→get_hardwareId()
dataset→hardwareId()
dataset.get_hardwareId()dataset→get_hardwareId()[dataset hardwareId]dataset.get_hardwareId()dataset.get_hardwareId()dataset.get_hardwareId()dataset.get_hardwareId()dataset.get_hardwareId()dataset.get_hardwareId()dataset→get_hardwareId()dataset.get_hardwareId()dataset.get_hardwareId()dataset.get_hardwareId()dataset.get_hardwareId()

Returns the unique hardware identifier of the function who performed the measures, in the form SERIAL.FUNCTIONID.

js
function get_hardwareId()
cpp
string get_hardwareId()
m
-(NSString*) hardwareId
pas
string get_hardwareId(): string
vb
function get_hardwareId() As String
cs
string get_hardwareId()
java
String get_hardwareId()
uwp
async Task<string> get_hardwareId()
py
get_hardwareId()
php
function get_hardwareId()
ts
async get_hardwareId(): Promise<string>
es
async get_hardwareId()
dnp
string get_hardwareId()
cp
string get_hardwareId()

The unique hardware identifier is composed of the device serial number and of the hardware identifier of the function (for example THRMCPL1-123456.temperature1)

Returns :

a string that uniquely identifies the function (ex: THRMCPL1-123456.temperature1)

On failure, throws an exception or returns YDataSet.HARDWAREID_INVALID.

dataset→get_measures()
dataset→measures()
dataset.get_measures()dataset→get_measures()[dataset measures]dataset.get_measures()dataset.get_measures()dataset.get_measures()dataset.get_measures()dataset.get_measures()dataset.get_measures()dataset→get_measures()dataset.get_measures()dataset.get_measures()dataset.get_measures()dataset.get_measures()

Returns all measured values currently available for this DataSet, as a list of YMeasure objects.

js
function get_measures()
cpp
vector<YMeasure> get_measures()
m
-(NSMutableArray*) measures
pas
TYMeasureArray get_measures(): TYMeasureArray
vb
function get_measures() As List
cs
List<YMeasure> get_measures()
java
ArrayList<YMeasure> get_measures()
uwp
async Task<List<YMeasure>> get_measures()
py
get_measures()
php
function get_measures()
ts
async get_measures(): Promise<YMeasure[]
es
async get_measures()
dnp
YMeasure[] get_measures()
cp
vector<YMeasure> get_measures()

Each item includes: - the start of the measure time interval - the end of the measure time interval - the minimal value observed during the time interval - the average value observed during the time interval - the maximal value observed during the time interval

Before calling this method, you should call loadMore() to load data from the device. You may have to call loadMore() several time until all rows are loaded, but you can start looking at available data rows before the load is complete.

The oldest measures are always loaded first, and the most recent measures will be loaded last. As a result, timestamps are normally sorted in ascending order within the measure table, unless there was an unexpected adjustment of the datalogger UTC clock.

Returns :

a table of records, where each record depicts the measured value for a given time interval

On failure, throws an exception or returns an empty array.

dataset→get_measuresAt()
dataset→measuresAt()
dataset.get_measuresAt()dataset→get_measuresAt()[dataset measuresAt: ]dataset.get_measuresAt()dataset.get_measuresAt()dataset.get_measuresAt()dataset.get_measuresAt()dataset.get_measuresAt()dataset.get_measuresAt()dataset→get_measuresAt()dataset.get_measuresAt()dataset.get_measuresAt()dataset.get_measuresAt()dataset.get_measuresAt()

Returns the detailed set of measures for the time interval corresponding to a given condensed measures previously returned by get_preview().

js
function get_measuresAt(measure)
cpp
vector<YMeasure> get_measuresAt(YMeasure measure)
m
-(NSMutableArray*) measuresAt: (YMeasure*) measure
pas
TYMeasureArray get_measuresAt(measure: TYMeasure): TYMeasureArray
vb
function get_measuresAt(ByVal measure As YMeasure) As List
cs
List<YMeasure> get_measuresAt(YMeasure measure)
java
ArrayList<YMeasure> get_measuresAt(YMeasure measure)
uwp
async Task<List<YMeasure>> get_measuresAt(YMeasure measure)
py
get_measuresAt(measure)
php
function get_measuresAt($measure)
ts
async get_measuresAt(measure: YMeasure): Promise<YMeasure[]
es
async get_measuresAt(measure)
dnp
YMeasure[] get_measuresAt(YMeasure measure)
cp
vector<YMeasure> get_measuresAt(YMeasure measure)

The result is provided as a list of YMeasure objects.

Parameters :

measurecondensed measure from the list previously returned by get_preview().

Returns :

a table of records, where each record depicts the measured values during a time interval

On failure, throws an exception or returns an empty array.

dataset→get_measuresAvgAt()
dataset→measuresAvgAt()

Returns the average value observed during the time interval covered by the specified entry in the preview.

Parameters :

indexan integer index in the range [0...MeasuresRecordCount-1].

Returns :

a floating-point number corresponding to the average value observed.

dataset→get_measuresEndTimeAt()
dataset→measuresEndTimeAt()

Returns the end time of the specified entry in the preview, relative to the Jan 1, 1970 UTC (Unix timestamp).

When the recording rate is higher then 1 sample per second, the timestamp may have a fractional part.

Parameters :

indexan integer index in the range [0...MeasuresRecordCount-1].

Returns :

a floating point number corresponding to the number of seconds between the Jan 1, 1970 UTC and the beginning of this measure.

dataset→get_measuresMaxAt()
dataset→measuresMaxAt()

Returns the largest value observed during the time interval covered by the specified entry in the preview.

Parameters :

indexan integer index in the range [0...MeasuresRecordCount-1].

Returns :

a floating-point number corresponding to the largest value observed.

dataset→get_measuresMinAt()
dataset→measuresMinAt()

Returns the smallest value observed during the time interval covered by the specified entry in the preview.

Parameters :

indexan integer index in the range [0...MeasuresRecordCount-1].

Returns :

a floating-point number corresponding to the smallest value observed.

dataset→get_measuresRecordCount()
dataset→measuresRecordCount()

Returns the number of measurements currently loaded for this data set.

The total number of record is only known when the data set is fully loaded, i.e. when loadMore() has been invoked until the progresss indicator returns 100.

Returns :

an integer number corresponding to the number of entries loaded.

dataset→get_measuresStartTimeAt()
dataset→measuresStartTimeAt()

Returns the start time of the specified entry in the preview, relative to the Jan 1, 1970 UTC (Unix timestamp).

When the recording rate is higher then 1 sample per second, the timestamp may have a fractional part.

Parameters :

indexan integer index in the range [0...MeasuresRecordCount-1].

Returns :

a floating point number corresponding to the number of seconds between the Jan 1, 1970 UTC and the beginning of this measure.

dataset→get_preview()
dataset→preview()
dataset.get_preview()dataset→get_preview()[dataset preview]dataset.get_preview()dataset.get_preview()dataset.get_preview()dataset.get_preview()dataset.get_preview()dataset.get_preview()dataset→get_preview()dataset.get_preview()dataset.get_preview()dataset.get_preview()dataset.get_preview()

Returns a condensed version of the measures that can retrieved in this YDataSet, as a list of YMeasure objects.

js
function get_preview()
cpp
vector<YMeasure> get_preview()
m
-(NSMutableArray*) preview
pas
TYMeasureArray get_preview(): TYMeasureArray
vb
function get_preview() As List
cs
List<YMeasure> get_preview()
java
ArrayList<YMeasure> get_preview()
uwp
async Task<List<YMeasure>> get_preview()
py
get_preview()
php
function get_preview()
ts
async get_preview(): Promise<YMeasure[]
es
async get_preview()
dnp
YMeasure[] get_preview()
cp
vector<YMeasure> get_preview()

Each item includes: - the start of a time interval - the end of a time interval - the minimal value observed during the time interval - the average value observed during the time interval - the maximal value observed during the time interval

This preview is available as soon as loadMore() has been called for the first time.

Returns :

a table of records, where each record depicts the measured values during a time interval

On failure, throws an exception or returns an empty array.

dataset→get_previewAvgAt()
dataset→previewAvgAt()

Returns the average value observed during the time interval covered by the specified entry in the preview.

Parameters :

indexan integer index in the range [0...PreviewRecordCount-1].

Returns :

a floating-point number corresponding to the average value observed.

dataset→get_previewEndTimeAt()
dataset→previewEndTimeAt()

Returns the end time of the specified entry in the preview, relative to the Jan 1, 1970 UTC (Unix timestamp).

When the recording rate is higher then 1 sample per second, the timestamp may have a fractional part.

Parameters :

indexan integer index in the range [0...PreviewRecordCount-1].

Returns :

a floating point number corresponding to the number of seconds between the Jan 1, 1970 UTC and the beginning of this measure.

dataset→get_previewMaxAt()
dataset→previewMaxAt()

Returns the largest value observed during the time interval covered by the specified entry in the preview.

Parameters :

indexan integer index in the range [0...PreviewRecordCount-1].

Returns :

a floating-point number corresponding to the largest value observed.

dataset→get_previewMinAt()
dataset→previewMinAt()

Returns the smallest value observed during the time interval covered by the specified entry in the preview.

Parameters :

indexan integer index in the range [0...PreviewRecordCount-1].

Returns :

a floating-point number corresponding to the smallest value observed.

dataset→get_previewRecordCount()
dataset→previewRecordCount()

Returns the number of entries in the preview summarizing this data set

Returns :

an integer number corresponding to the number of entries.

dataset→get_previewStartTimeAt()
dataset→previewStartTimeAt()

Returns the start time of the specified entry in the preview, relative to the Jan 1, 1970 UTC (Unix timestamp).

When the recording rate is higher then 1 sample per second, the timestamp may have a fractional part.

Parameters :

indexan integer index in the range [0...PreviewRecordCount-1].

Returns :

a floating point number corresponding to the number of seconds between the Jan 1, 1970 UTC and the beginning of this measure.

dataset→get_progress()
dataset→progress()
dataset.get_progress()dataset→get_progress()[dataset progress]dataset.get_progress()dataset.get_progress()dataset.get_progress()dataset.get_progress()dataset.get_progress()dataset.get_progress()dataset→get_progress()dataset.get_progress()dataset.get_progress()dataset.get_progress()dataset.get_progress()

Returns the progress of the downloads of the measures from the data logger, on a scale from 0 to 100.

js
function get_progress()
cpp
int get_progress()
m
-(int) progress
pas
LongInt get_progress(): LongInt
vb
function get_progress() As Integer
cs
int get_progress()
java
int get_progress()
uwp
async Task<int> get_progress()
py
get_progress()
php
function get_progress()
ts
async get_progress(): Promise<number>
es
async get_progress()
dnp
int get_progress()
cp
int get_progress()

When the object is instantiated by get_dataSet, the progress is zero. Each time loadMore() is invoked, the progress is updated, to reach the value 100 only once all measures have been loaded.

Returns :

an integer in the range 0 to 100 (percentage of completion).

dataset→get_startTimeUTC()
dataset→startTimeUTC()
dataset.get_startTimeUTC()dataset→get_startTimeUTC()[dataset startTimeUTC]dataset.get_startTimeUTC()dataset.get_startTimeUTC()dataset.get_startTimeUTC()dataset.get_startTimeUTC()dataset.get_startTimeUTC()dataset.get_startTimeUTC()dataset→get_startTimeUTC()dataset.get_startTimeUTC()dataset.get_startTimeUTC()dataset.get_startTimeUTC()dataset.get_startTimeUTC()

Returns the start time of the dataset, relative to the Jan 1, 1970.

js
function get_startTimeUTC()
cpp
s64 get_startTimeUTC()
m
-(s64) startTimeUTC
pas
int64 get_startTimeUTC(): int64
vb
function get_startTimeUTC() As Long
cs
long get_startTimeUTC()
java
long get_startTimeUTC()
uwp
async Task<long> get_startTimeUTC()
py
get_startTimeUTC()
php
function get_startTimeUTC()
ts
async get_startTimeUTC(): Promise<number>
es
async get_startTimeUTC()
dnp
long get_startTimeUTC()
cp
s64 get_startTimeUTC()

When the YDataSet object is created, the start time is the value passed in parameter to the get_dataSet() function. After the very first call to loadMore(), the start time is updated to reflect the timestamp of the first measure actually found in the dataLogger within the specified range.

DEPRECATED: This method has been replaced by get_summary() which contain more precise informations.

Returns :

an unsigned number corresponding to the number of seconds between the Jan 1, 1970 and the beginning of this data set (i.e. Unix time representation of the absolute time).

dataset→get_summary()
dataset→summary()
dataset.get_summary()dataset→get_summary()[dataset summary]dataset.get_summary()dataset.get_summary()dataset.get_summary()dataset.get_summary()dataset.get_summary()dataset.get_summary()dataset→get_summary()dataset.get_summary()dataset.get_summary()dataset.get_summary()dataset.get_summary()

Returns an YMeasure object which summarizes the whole YDataSet.

js
function get_summary()
cpp
YMeasure get_summary()
m
-(YMeasure*) summary
pas
TYMeasure get_summary(): TYMeasure
vb
function get_summary() As YMeasure
cs
YMeasure get_summary()
java
YMeasure get_summary()
uwp
async Task<YMeasure> get_summary()
py
get_summary()
php
function get_summary()
ts
async get_summary(): Promise<YMeasure>
es
async get_summary()
dnp
YMeasure get_summary()
cp
YMeasure get_summary()

In includes the following information: - the start of a time interval - the end of a time interval - the minimal value observed during the time interval - the average value observed during the time interval - the maximal value observed during the time interval

This summary is available as soon as loadMore() has been called for the first time.

Returns :

an YMeasure object

dataset→get_summaryAvg()
dataset→summaryAvg()

Returns the average value observed during the time interval covered by this data set.

Returns :

a floating-point number corresponding to the average value observed.

dataset→get_summaryEndTime()
dataset→summaryEndTime()

Returns the end time of the last measure in the data set, relative to the Jan 1, 1970 UTC (Unix timestamp).

When the recording rate is higher then 1 sample per second, the timestamp may have a fractional part.

Returns :

a floating point number corresponding to the number of seconds between the Jan 1, 1970 UTC and the beginning of this measure.

dataset→get_summaryMax()
dataset→summaryMax()

Returns the largest value observed during the time interval covered by this data set.

Returns :

a floating-point number corresponding to the largest value observed.

dataset→get_summaryMin()
dataset→summaryMin()

Returns the smallest value observed during the time interval covered by this data set.

Returns :

a floating-point number corresponding to the smallest value observed.

dataset→get_summaryStartTime()
dataset→summaryStartTime()

Returns the start time of the first measure in the data set, relative to the Jan 1, 1970 UTC (Unix timestamp).

When the recording rate is higher then 1 sample per second, the timestamp may have a fractional part.

Returns :

a floating point number corresponding to the number of seconds between the Jan 1, 1970 UTC and the beginning of this measure.

dataset→get_unit()
dataset→unit()
dataset.get_unit()dataset→get_unit()[dataset unit]dataset.get_unit()dataset.get_unit()dataset.get_unit()dataset.get_unit()dataset.get_unit()dataset.get_unit()dataset→get_unit()dataset.get_unit()dataset.get_unit()dataset.get_unit()dataset.get_unit()

Returns the measuring unit for the measured value.

js
function get_unit()
cpp
string get_unit()
m
-(NSString*) unit
pas
string get_unit(): string
vb
function get_unit() As String
cs
string get_unit()
java
String get_unit()
uwp
async Task<string> get_unit()
py
get_unit()
php
function get_unit()
ts
async get_unit(): Promise<string>
es
async get_unit()
dnp
string get_unit()
cp
string get_unit()

Returns :

a string that represents a physical unit.

On failure, throws an exception or returns YDataSet.UNIT_INVALID.

dataset→loadMore()dataset.loadMore()dataset→loadMore()[dataset loadMore]dataset.loadMore()dataset.loadMore()dataset.loadMore()dataset.loadMore()dataset.loadMore()dataset.loadMore()dataset→loadMore()dataset.loadMore()dataset.loadMore()dataset.loadMore()dataset.loadMore()

Loads the the next block of measures from the dataLogger, and updates the progress indicator.

js
function loadMore()
cpp
int loadMore()
m
-(int) loadMore
pas
LongInt loadMore(): LongInt
vb
function loadMore() As Integer
cs
int loadMore()
java
int loadMore()
uwp
async Task<int> loadMore()
py
loadMore()
php
function loadMore()
ts
async loadMore(): Promise<number>
es
async loadMore()
dnp
int loadMore()
cp
int loadMore()

Returns :

an integer in the range 0 to 100 (percentage of completion), or a negative error code in case of failure.

On failure, throws an exception or returns a negative error code.

dataset→loadMore_async()dataset.loadMore_async()

Loads the the next block of measures from the dataLogger asynchronously.

js
function loadMore_async(callback, context)

Parameters :

callbackcallback function that is invoked when the w The callback function receives three arguments: - the user-specific context object - the YDataSet object whose loadMore_async was invoked - the load result: either the progress indicator (0...100), or a negative error code in case of failure.
contextuser-specific object that is passed as-is to the callback function

Returns :

nothing.

24.11. Class YMeasure

Measured value, returned in particular by the methods of the YDataSet class.

YMeasure objects are used within the API to represent a value measured at a specified time. These objects are used in particular in conjunction with the YDataSet class, but also for sensors periodic timed reports (see sensor.registerTimedReportCallback).

In order to use the functions described here, you should include:

js
<script type='text/javascript' src='yocto_module.js'></script>
cpp
#include "yocto_module.h"
m
#import "yocto_module.h"
pas
uses yocto_module;
vb
yocto_module.vb
cs
yocto_module.cs
java
import com.yoctopuce.YoctoAPI.YMeasure;
uwp
import com.yoctopuce.YoctoAPI.YMeasure;
py
from yocto_module import *
php
require_once('yocto_module.php');
ts
in HTML: import { YMeasure } from '../../dist/esm/yocto_module.js';
in Node.js: import { YMeasure } from 'yoctolib-cjs/yocto_module.js';
es
in HTML: <script src="../../lib/yocto_module.js"></script>
in node.js: require('yoctolib-es2017/yocto_module.js');
YMeasure methods
measure→get_averageValue()

Returns the average value observed during the time interval covered by this measure.

measure→get_endTimeUTC()

Returns the end time of the measure, relative to the Jan 1, 1970 UTC (Unix timestamp).

measure→get_maxValue()

Returns the largest value observed during the time interval covered by this measure.

measure→get_minValue()

Returns the smallest value observed during the time interval covered by this measure.

measure→get_startTimeUTC()

Returns the start time of the measure, relative to the Jan 1, 1970 UTC (Unix timestamp).

measure→get_averageValue()
measure→averageValue()
measure.get_averageValue()measure→get_averageValue()[measure averageValue]measure.get_averageValue()measure.get_averageValue()measure.get_averageValue()measure.get_averageValue()measure.get_averageValue()measure.get_averageValue()measure→get_averageValue()measure.get_averageValue()measure.get_averageValue()

Returns the average value observed during the time interval covered by this measure.

js
function get_averageValue()
cpp
double get_averageValue()
m
-(double) averageValue
pas
double get_averageValue(): double
vb
function get_averageValue() As Double
cs
double get_averageValue()
java
double get_averageValue()
uwp
double get_averageValue()
py
get_averageValue()
php
function get_averageValue()
ts
get_averageValue(): number
es
get_averageValue()

Returns :

a floating-point number corresponding to the average value observed.

measure→get_endTimeUTC()
measure→endTimeUTC()
measure.get_endTimeUTC()measure→get_endTimeUTC()[measure endTimeUTC]measure.get_endTimeUTC()measure.get_endTimeUTC()measure.get_endTimeUTC()measure.get_endTimeUTC()measure.get_endTimeUTC()measure.get_endTimeUTC()measure→get_endTimeUTC()measure.get_endTimeUTC()measure.get_endTimeUTC()

Returns the end time of the measure, relative to the Jan 1, 1970 UTC (Unix timestamp).

js
function get_endTimeUTC()
cpp
double get_endTimeUTC()
m
-(double) endTimeUTC
pas
double get_endTimeUTC(): double
vb
function get_endTimeUTC() As Double
cs
double get_endTimeUTC()
java
double get_endTimeUTC()
uwp
double get_endTimeUTC()
py
get_endTimeUTC()
php
function get_endTimeUTC()
ts
get_endTimeUTC(): number
es
get_endTimeUTC()

When the recording rate is higher than 1 sample per second, the timestamp may have a fractional part.

Returns :

a floating point number corresponding to the number of seconds between the Jan 1, 1970 UTC and the end of this measure.

measure→get_maxValue()
measure→maxValue()
measure.get_maxValue()measure→get_maxValue()[measure maxValue]measure.get_maxValue()measure.get_maxValue()measure.get_maxValue()measure.get_maxValue()measure.get_maxValue()measure.get_maxValue()measure→get_maxValue()measure.get_maxValue()measure.get_maxValue()

Returns the largest value observed during the time interval covered by this measure.

js
function get_maxValue()
cpp
double get_maxValue()
m
-(double) maxValue
pas
double get_maxValue(): double
vb
function get_maxValue() As Double
cs
double get_maxValue()
java
double get_maxValue()
uwp
double get_maxValue()
py
get_maxValue()
php
function get_maxValue()
ts
get_maxValue(): number
es
get_maxValue()

Returns :

a floating-point number corresponding to the largest value observed.

measure→get_minValue()
measure→minValue()
measure.get_minValue()measure→get_minValue()[measure minValue]measure.get_minValue()measure.get_minValue()measure.get_minValue()measure.get_minValue()measure.get_minValue()measure.get_minValue()measure→get_minValue()measure.get_minValue()measure.get_minValue()

Returns the smallest value observed during the time interval covered by this measure.

js
function get_minValue()
cpp
double get_minValue()
m
-(double) minValue
pas
double get_minValue(): double
vb
function get_minValue() As Double
cs
double get_minValue()
java
double get_minValue()
uwp
double get_minValue()
py
get_minValue()
php
function get_minValue()
ts
get_minValue(): number
es
get_minValue()

Returns :

a floating-point number corresponding to the smallest value observed.

measure→get_startTimeUTC()
measure→startTimeUTC()
measure.get_startTimeUTC()measure→get_startTimeUTC()[measure startTimeUTC]measure.get_startTimeUTC()measure.get_startTimeUTC()measure.get_startTimeUTC()measure.get_startTimeUTC()measure.get_startTimeUTC()measure.get_startTimeUTC()measure→get_startTimeUTC()measure.get_startTimeUTC()measure.get_startTimeUTC()

Returns the start time of the measure, relative to the Jan 1, 1970 UTC (Unix timestamp).

js
function get_startTimeUTC()
cpp
double get_startTimeUTC()
m
-(double) startTimeUTC
pas
double get_startTimeUTC(): double
vb
function get_startTimeUTC() As Double
cs
double get_startTimeUTC()
java
double get_startTimeUTC()
uwp
double get_startTimeUTC()
py
get_startTimeUTC()
php
function get_startTimeUTC()
ts
get_startTimeUTC(): number
es
get_startTimeUTC()

When the recording rate is higher then 1 sample per second, the timestamp may have a fractional part.

Returns :

a floating point number corresponding to the number of seconds between the Jan 1, 1970 UTC and the beginning of this measure.

25. Troubleshooting

25.1. Where to start?

If it is the first time that you use a Yoctopuce module and you do not really know where to start, have a look at the Yoctopuce blog. There is a section dedicated to beginners 62.

25.2. Programming examples don't seem to work

Most of Yoctopuce API programming examples are command line programs and require some parameters to work properly. You have to start them from your operating system command prompt, or configure your IDE to run them with the proper parameters. 63.

25.3. Linux and USB

To work correctly under Linux, the the library needs to have write access to all the Yoctopuce USB peripherals. However, by default under Linux, USB privileges of the non-root users are limited to read access. To avoid having to run the VirtualHub as root, you need to create a new udev rule to authorize one or several users to have write access to the Yoctopuce peripherals.

To add a new udev rule to your installation, you must add a file with a name following the "##-arbitraryName.rules" format, in the "/etc/udev/rules.d" directory. When the system is starting, udev reads all the files with a ".rules" extension in this directory, respecting the alphabetical order (for example, the "51-custom.rules" file is interpreted AFTER the "50-udev-default.rules" file).

The "50-udev-default" file contains the system default udev rules. To modify the default behavior, you therefore need to create a file with a name that starts with a number larger than 50, that will override the system default rules. Note that to add a rule, you need a root access on the system.

In the udev_conf directory of the VirtualHub for Linux64 archive, there are two rule examples which you can use as a basis.

Example 1: 51-yoctopuce.rules

This rule provides all the users with read and write access to the Yoctopuce USB peripherals. Access rights for all other peripherals are not modified. If this scenario suits you, you only need to copy the "51-yoctopuce_all.rules" file into the "/etc/udev/rules.d" directory and to restart your system.

# udev rules to allow write access to all users # for Yoctopuce USB devices SUBSYSTEM=="usb", ATTR{idVendor}=="24e0", MODE="0666"

Example 2: 51-yoctopuce_group.rules

This rule authorizes the "yoctogroup" group to have read and write access to Yoctopuce USB peripherals. Access rights for all other peripherals are not modified. If this scenario suits you, you only need to copy the "51-yoctopuce_group.rules" file into the "/etc/udev/rules.d" directory and restart your system.

# udev rules to allow write access to all users of "yoctogroup" # for Yoctopuce USB devices SUBSYSTEM=="usb", ATTR{idVendor}=="24e0", MODE="0664", GROUP="yoctogroup"

25.4. ARM Platforms: HF and EL

There are two main flavors of executable on ARM: HF (Hard Float) binaries, and EL (EABI Little Endian) binaries. These two families are not compatible at all. The compatibility of a given ARM platform with of one of these two families depends on the hardware and on the OS build. ArmHL and ArmEL compatibility problems are quite difficult to detect. Most of the time, the OS itself is unable to make a difference between an HF and an EL executable and will return meaningless messages when you try to use the wrong type of binary.

All pre-compiled Yoctopuce binaries are provided in both formats, as two separate ArmHF et ArmEL executables. If you do not know what family your ARM platform belongs to, just try one executable from each family.

25.5. Powered module but invisible for the OS

If your Yocto-3D-V2 is connected by USB, if its blue led is on, but if the operating system cannot see the module, check that you are using a true USB cable with data wires, and not a charging cable. Charging cables have only power wires.

25.6. Another process named xxx is already using yAPI

If when initializing the Yoctopuce API, you obtain the "Another process named xxx is already using yAPI" error message, it means that another application is already using Yoctopuce USB modules. On a single machine only one process can access Yoctopuce modules by USB at a time. You can easily work around this limitation by using a VirtualHub and the network mode 65.

25.7. Disconnections, erratic behavior

If you Yocto-3D-V2 behaves erratically and/or disconnects itself from the USB bus without apparent reason, check that it is correctly powered. Avoid cables with a length above 2 meters. If needed, insert a powered USB hub 66 67.

25.8. Registering a VirtualHub disconnect an other one

If, when performing a call to RegisterHub() with an VirtualHub address, an other previously registered VirtualHub disconnects, make sure the machine running theses VirtualHubs don't have the same Hostname. Same Hostname can happen very easily when the operating system is installed from a monolithic image, Raspberry-PI are the best example. The Yoctopuce API uses serial numbers to communicate with devices and VirtualHub serial number are created on the fly based the hostname of the machine running the VirtualHub.

25.9. Dropped commands

If, after sending a bunch of commands to a Yoctopuce device, you are under the impression that the last ones have been ignored, typical example is a quick and dirty program meant to configure a device, make sure you used a YAPI.FreeAPI() at the end of the program. Commands are sent to Yoctopuce modules asynchronously thanks to a background thread. When the main program terminates, that thread is killed no matter if some command are left to be sent. However API.FreeAPI() will wait until there is no more commands to send before freeing the API resources and returning.

25.10. Damaged device

Yoctopuce strives to reduce the production of electronic waste. If you believe that your Yocto-3D-V2 is not working anymore, start by contacting Yoctopuce support by e-mail to diagnose the failure. Even if you know that the device was damaged by mistake, Yoctopuce engineers might be able to repair it, and thus avoid creating electronic waste.

Waste Electrical and Electronic Equipment (WEEE) If you really want to get rid of your Yocto-3D-V2, do not throw it away in a trash bin but bring it to your local WEEE recycling point. In this way, it will be disposed properly by a specialized WEEE recycling center.



26. Characteristics

You can find below a summary of the main technical characteristics of your Yocto-3D-V2 module.

Product IDY3DMK002
Hardware release
USB connectormicro-B
Width20 mm
Length51 mm
Weight4 g
SensorBNO055
Gyroscopic attitude estimation100 Hz
Measuring range (Accel.)16 g
Measuring range (Gyro)2000 °/s
Measuring range (Magn.)13 gauss
Sensitivity0.1 °
Sensitivity (Accel.)0.001 g
Sensitivity (Gyro)0.1 °/s
Sensitivity (Magn.)0.01 gauss
Protection class, according to IEC 61140class III
Normal operating temperature5...40 °C
Extended operating temperature-30...85 °C
RoHS complianceRoHS III (2011/65/UE+2015/863)
USB Vendor ID0x24E0
USB Device ID0x006A
Suggested enclosureYoctoBox-3D-Black
Harmonized tariff code9032.9000
Made inSwitzerland

These specifications are for the current hardware revision. Specifications for earlier revisions may differ.

The extended temperature range is defined based on components specifications and has been tested during a limited duration (1h). When using the device in harsh environments for a long period of time, we strongly advise to run extensive tests before going to production.

27. Index

A
Accelerometer
advertisedValue
AdvertisedValue
advMode
AdvMode
API
autoStart
AutoStart
axis
B
bandwidth
Bandwidth
beacon
Beacon
beaconDriven
BeaconDriven
bearing
Bearing
C
calibrateFromPoints
calibrateToZero
calibrationParam
cancel3DCalibration
checkFirmware
CheckLogicalName
clearCache
clearHistory
ClearHTTPCallbackCacheDir
Compass
currentRawValue
currentRunIndex
currentValue
D
DataLogger
describe
DisableExceptions
download
E
EnableExceptions
EnableUSBHost
F
FindAccelerometer
FindAccelerometerInContext
FindCompass
FindCompassInContext
FindDataLogger
FindDataLoggerInContext
FindGyro
FindGyroInContext
FindMagnetometer
FindMagnetometerInContext
FindModule
FindModuleInContext
FindRefFrame
FindRefFrameInContext
FindTilt
FindTiltInContext
firmwareRelease
FirmwareRelease
FirstAccelerometer
FirstAccelerometerInContext
FirstCompass
FirstCompassInContext
FirstDataLogger
FirstDataLoggerInContext
FirstGyro
FirstGyroInContext
FirstMagnetometer
FirstMagnetometerInContext
FirstModule
FirstRefFrame
FirstRefFrameInContext
FirstTilt
FirstTiltInContext
forgetAllDataStreams
FreeAPI
FriendlyName
functionBaseType
functionCount
FunctionId
functionId
functionName
functionType
functionValue
fusionMode
FusionMode
G
get_3DCalibrationHint
get_3DCalibrationLogMsg
get_3DCalibrationProgress
get_3DCalibrationStage
get_3DCalibrationStageProgress
get_advertisedValue
get_advMode
get_allSettings
get_autoStart
get_averageValue
get_bandwidth
get_beacon
get_beaconDriven
get_bearing
get_calibrationState
get_currentRawValue
get_currentRunIndex
get_currentValue
get_dataLogger
get_dataSets
get_dataStreams
get_endTimeUTC
get_errorMessage
get_errorType
get_firmwareRelease
get_friendlyName
get_functionDescriptor
get_functionId
get_functionIds
get_fusionMode
get_hardwareId
get_heading
get_highestValue
get_icon2d
get_lastLogs
get_logFrequency
get_logicalName
get_lowestValue
get_luminosity
get_magneticHeading
get_maxValue
get_measureQuality
get_measures
get_measuresAt
get_measuresAvgAt
get_measuresEndTimeAt
get_measuresMaxAt
get_measuresMinAt
get_measuresRecordCount
get_measuresStartTimeAt
get_minValue
get_module
get_module_async
get_mountOrientation
get_mountPosition
get_parentHub
get_persistentSettings
get_pitch
get_preview
get_previewAvgAt
get_previewEndTimeAt
get_previewMaxAt
get_previewMinAt
get_previewRecordCount
get_previewStartTimeAt
get_productId
get_productName
get_productRelease
get_progress
get_quaternionW
get_quaternionX
get_quaternionY
get_quaternionZ
get_rebootCountdown
get_recordedData
get_recording
get_reportFrequency
get_resolution
get_roll
get_sensorState
get_serialNumber
get_startTimeUTC
get_subDevices
get_summary
get_summaryAvg
get_summaryEndTime
get_summaryMax
get_summaryMin
get_summaryStartTime
get_timeUTC
get_unit
get_upTime
get_url
get_usage
get_usbCurrent
get_userData
get_userVar
get_xValue
get_yValue
get_zValue
GetAPIVersion
GetCacheValidity
GetDeviceListValidity
GetDllArchitecture
GetDllPath
GetLog
GetNetworkTimeout
GetSimilarFunctions
GetTickCount
Gyro
H
HandleEvents
HardwareId
hasFunction
highestValue
I
Init
InitAPI
IsOnline
isOnline
isOnline_async
isReadOnly
isSensorReady
L
load
load_async
loadAttribute
loadCalibrationPoints
loadMore
loadMore_async
log
logFrequency
LogFrequency
logicalName
LogicalName
lowestValue
luminosity
Luminosity
M
magneticHeading
Magnetometer
Module
more3DCalibration
mountPos
muteValueCallbacks
N
nextAccelerometer
nextCompass
nextDataLogger
nextGyro
nextMagnetometer
nextModule
nextRefFrame
nextTilt
P
persistentSettings
PreregisterHub
productId
ProductId
productName
ProductName
productRelease
ProductRelease
R
reboot
rebootCountdown
recording
Recording
RefFrame
registerAnglesCallback
registerBeaconCallback
registerConfigChangeCallback
RegisterDeviceArrivalCallback
RegisterDeviceRemovalCallback
RegisterHub
RegisterHubDiscoveryCallback
RegisterHubWebsocketCallback
registerLogCallback
RegisterLogFunction
registerQuaternionCallback
registerTimedReportCallback
registerValueCallback
reportFrequency
ReportFrequency
resolution
Resolution
restoreZeroCalibration
revertFromFlash
S
save3DCalibration
saveToFlash
SelectArchitecture
sensorState
serialNumber
SerialNumber
set_advMode
set_allSettings
set_allSettingsAndFiles
set_autoStart
set_bandwidth
set_beacon
set_beaconDriven
set_bearing
set_fusionMode
set_highestValue
set_logFrequency
set_logicalName
set_lowestValue
set_luminosity
set_mountPosition
set_recording
set_reportFrequency
set_resolution
set_timeUTC
set_userData
set_userVar
SetCacheValidity
SetDelegate
SetDeviceListValidity
SetHTTPCallbackCacheDir
SetNetworkTimeout
SetTimeout
SetUSBPacketAckMs
Sleep
start3DCalibration
startDataLogger
stopDataLogger
T
techspec
TestHub
Tilt
timeUTC
triggerConfigChangeCallback
triggerFirmwareUpdate
TriggerHubDiscovery
U
unit
unmuteValueCallbacks
UnregisterHub
UpdateDeviceList
UpdateDeviceList_async
updateFirmware
updateFirmwareEx
upTime
usage
usbcurrent
usbCurrent
userVar
W
wait_async
wiring
X
xValue
Y
YAccelerometer
YAPI
YCompass
YDataLogger
YDataSet
YGyro
YMagnetometer
YMeasure
YModule
YRefFrame
YTilt
yValue
Z
zValue


  1. short-short-short long-long-long short-short-short
  2. support@yoctopuce.com
  3. http://www.yoctopuce.com/EN/products/category/enclosures
  4. Header Molex ref 90325-3004 or 90325-0004, available from most electronic components suppliers (www.mouser.com, www.digikey.com, www.farnell.com, www.distrelec.ch...). To be used with connectors ref 90327-3304 or 90327-0304.
  5. The HID driver is the one that takes care of the mouse, the keyboard, etc.
  6. Although they existed for some time, Mini A connectors are not available anymore http://www.usb.org/developers/Deprecation_Announcement_052507.pdf
  7. www.yoctopuce.com/EN/virtualhub.php
  8. The interface is tested on Chrome, FireFox, Safari, Edge et IE 11.
  9. www.yoctopuce.com/EN/virtualhub.php
  10. More information available in the virtual hub documentation
  11. www.yoctopuce.com/EN/article/usb-cables-size-matters
  12. www.yoctopuce.com/EN/virtualhub.php
  13. http://www.yoctopuce.com/EN/libraries.php
  14. If you want to recompile the command line API, you also need the C++ API.
  15. http://www.yoctopuce.com/EN/libraries.php
  16. http://www.yoctopuce.com/EN/virtualhub.php
  17. http://www.python.org/download/
  18. www.yoctopuce.com/EN/libraries.php
  19. http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express
  20. www.yoctopuce.com/EN/libraries.php
  21. http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-csharp-express
  22. www.yoctopuce.com/EN/libraries.php
  23. The sources of this DLL are available in the C++ API
  24. Remember to change the filter of the selection window, otherwise the DLL will not show.
  25. http://www.yoctopuce.com/EN/libraries.php
  26. https://knowledge.ni.com/KnowledgeArticleDetails?id=kA00Z000000P8XnSAK
  27. https://forums.ni.com/t5/Developer-Center-Resources/Creating-a-LabVIEW-Palette/ta-p/3520557
  28. www.yoctopuce.com/EN/products/category/extensions-and-networking
  29. http://www.yoctopuce.com/EN/virtualhub.php
  30. see section Using Proxy objects
  31. https://www.yoctopuce.com/EN/products/category/extensions-and-networking
  32. www.yoctopuce.com/EN/virtualhub.php
  33. www.yoctopuce.com/EN/libraries.php
  34. www.yoctopuce.com/EN/virtualhub.php
  35. www.yoctopuce.com/EN/libraries.php
  36. Yoctohubs are a plug and play way to add network connectivity to your Yoctopuce devices. more info on http://www.yoctopuce.com/EN/products/category/extensions-and-networking
  37. www.yoctopuce.com/EN/libraries.php
  38. www.yoctopuce.com/EN/virtualhub.php
  39. www.yoctopuce.com/EN/libraries.php
  40. www.yoctopuce.com/EN/virtualhub.php
  41. http://babeljs.io
  42. A couple of free PHP servers: easyPHP for Windows, MAMP for Mac OS X.
  43. www.yoctopuce.com/EN/libraries.php
  44. www.yoctopuce.com/EN/virtualhub.php
  45. If you do not have a text editor, use Notepad rather than Microsoft Word.
  46. http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-basic-express
  47. www.yoctopuce.com/EN/libraries.php
  48. The sources of this DLL are available in the C++ API
  49. Remember to change the filter of the selection window, otherwise the DLL will not show.
  50. Actually, Borland provided free versions (for personal use) of Delphi 2006 and 2007. Look for them on the Internet, you may still be able to download them.
  51. Delphi libraries are regularly tested with Delphi 5 and Delphi XE2.
  52. www.yoctopuce.com/EN/libraries.php
  53. Use the Tools / Environment options menu.
  54. https://www.visualstudio.com/vs/cordova/vs/
  55. www.yoctopuce.com/EN/libraries.php
  56. https://www.visualstudio.com/downloads/
  57. www.yoctopuce.com/EN/libraries.php
  58. www.yoctopuce.com/EN/article/new-objective-c-library-for-mac-os-x
  59. The JavaScript, Node.js, and PHP libraries do not yet allow you to update the modules. These functions will be available in a next build.
  60. The value passed as parameter is the same as the value returned by the get_advertisedValue() method.
  61. The YMeasure objects used by the data logger are exactly the same kind as those passed as argument to the timed report callbacks.
  62. see: http://www.yoctopuce.com/EN/blog_by_categories/for-the-beginners
  63. see: http://www.yoctopuce.com/EN/article/about-programming-examples
  64. http://www.yoctopuce.com/FR/virtualhub.php
  65. see: http://www.yoctopuce.com/EN/article/error-message-another-process-is-already-using-yapi
  66. see: http://www.yoctopuce.com/EN/article/usb-cables-size-matters
  67. see: http://www.yoctopuce.com/EN/article/how-many-usb-devices-can-you-connect
Yoctopuce, get your stuff connected.