Opta™ User Manual
Learn about the hardware and software features of Opta™ devices.
This user manual will provide a comprehensive overview of Opta™, covering its major hardware and software elements. With this user manual, you will learn how to set up, configure, and use all the main features of an Opta™ device.
Hardware and Software Requirements
Hardware Requirements
- Opta™ Lite, Opta™ RS485, or Opta™ WiFi (x1)
- USB-C® cable (x1)
- +12-24 VDC/0.5 A power supply (x1)
Software Requirements
- Arduino IDE 2.0+ or Arduino Web Editor
- Arduino PLC IDE 1.0.3+ (for IEC 61131-3 PLC programming languages)
- Arduino PLC IDE 1.0.3+ Tools
To learn more about the PLC IDE, check out our tutorials here.
Opta™ Overview
Opta™ is a secure micro Programmable Logic Controller (PLC) with Industrial Internet of Things (IoT) capabilities. Developed in partnership with Finder®, this device supports both the Arduino programming language and standard IEC-61131-3 PLC programming languages, such as Ladder Diagram (LD), Sequential Function Chart (SFC), Function Block Diagram (FBD), Structured Text (ST), and Instruction List (IL), making it an ideal device for automation engineers.
Based on the STM32H747XI from STMicroelectronics®, a high-performance Arm® Cortex®-M7 + Cortex®-M4 microcontroller, Opta™ is a perfect option for a wide range of applications, from real-time control to predictive maintenance applications.
Opta™ Variants
There are three variants of Opta™ created to fit the different needs of each industry and application.
The difference between each of the variants can be found in the following table:
Feature | Opta™ Lite | Opta™ RS485 | Opta™ WiFi |
---|---|---|---|
SKU | AFX00003 | AFX00001 | AFX00002 |
USB | USB-C® | USB-C® | USB-C® |
Ethernet Support | 10/100BASE-T Port | 10/100BASE-T Port | 10/100BASE-T Port |
RS-485 | N/A | Half-duplex | Half-duplex |
Wi-Fi® | N/A | N/A | 802.11 b/g/n |
Bluetooth® | N/A | N/A | Bluetooth® Low Energy |
The main differences between each one of the variants are related to their connectivity possibilities. All the variants can be connected to the Cloud using the onboard Ethernet. If your solution does not need an RS-485 interface or wireless connectivity, Opta™ Lite can fit your needs. If you need to connect your device to a Modbus RTU bus using an RS-485 connection but do not need wireless communication, Opta™ RS485 is the chosen variant. To have all Opta™ features and flexibility, with full wireless Wi-Fi® and Bluetooth® Low Energy connectivity, the Opta™ WiFi variant is the perfect choice for your professional projects.
Opta™ Main Components
Opta™ features a secure, certified, and durable design that enables it for automation and industrial applications.
Here's an overview of the device's main components shown in the image above:
- Microcontroller: At the heart of Opta™ is the STM32H747XI, a powerful and high-performance microcontroller from STMicroelectronics®. The STM32H747XI is built around an Arm® Cortex®-M7 and Arm® Cortex®-M4 32-bit RISC cores. The Arm® Cortex®-M7 core operates at up to 480 MHz, and the Arm® Cortex®-M4 core at up to 240 MHz.
- Wireless connectivity: Opta™ (WiFi variant only) supports 2.4 GHz Wi-Fi® (802.11 b/g/n) and Bluetooth® Low Energy (4.2 supported by firmware and 5.1 supported by hardware), allowing the device to communicate wirelessly with other devices and systems.
- Ethernet connectivity: Opta™ (all variants) features an onboard, high-performance 10/100 Mbps Ethernet transceiver accessible through its onboard RJ45 connector.
- Security: Opta™ features an onboard ready-to-use secure element, the ATECC608B from Microchip®, specifically designed for IoT devices that provides advanced security features, being perfect for Industrial IoT (IIoT) environments where security is critical.
- USB connectivity: Opta™ features an onboard USB-C® port that can be used for programming and data logging but not to command the relay outputs. To do so, power Opta™ using an external power supply.
- Analog and digital peripherals: Opta™ features analog and digital peripherals such as eight analog/digital input ports and four digital outputs ports (relay outputs).
- RS-485 connectivity: Opta™ (RS485 and WiFi variants) features a physical RS-485 communication interface available through an onboard terminal connector that can be used for standard communication interfaces like Modbus RTU or custom communication protocols.
- Form factor: Opta™ devices can be mounted standalone on a DIN rail, a grid, or a panel, providing quick and easy access to all input/output ports and peripherals.
Opta™ Core and Libraries
The
Arduino Mbed OS Opta Boards
core contains the libraries and examples to work with Opta™'s peripherals and onboard components, such as its input ports, output ports, Wi-Fi® and Bluetooth® module (WiFi variant only). To install the core for Opta™, navigate to Tools > Board > Boards Manager or click the Boards Manager icon in the left tab of the IDE. In the Boards Manager tab, search for opta
and install the latest Arduino Mbed OS Opta Boards
core version.Arduino PLC IDE
PLC IDE is the Arduino solution to program Opta™ devices using the five programming languages recognized by the IEC 61131-3 standard.
The IEC 61131-3 programming languages include:
- Ladder Diagram (LD)
- Functional Block Diagram (FBD)
- Structured Text (ST)
- Sequential Function Chart (SFC)
- Instruction List (IL)
In the PLC IDE, you can mix PLC programming with standard Arduino sketches within the integrated sketch editor and share variables between the two environments. You can also automate tasks in your software applications; this gives you control over scheduling and repetition, enhancing the reliability and efficiency of your project. Moreover, communication protocols such as Modbus RTU and Modbus TCP can be managed effortlessly using integrated no-code fieldbus configurators.
Check out the following resources that will show you how to start with the Arduino PLC IDE and use use IEC 61131-3 programming languages with Opta™:
The Arduino IDE and the Arduino PLC IDE programming environments have important differences in control and real-time performance, which means that the device is configured differently the first time you use one or the other. In case you have been using Opta with the PLC IDE, and you want to come back to use it inside the Arduino environment, we recommend performing the memory partitioning process that is explained in the Opta™ Memory Partitioning for Use with the Arduino IDE tutorial.
Pinout
The complete pinout (for all Opta™ variants) is available and downloadable as PDF from the link below:
Datasheet
The complete datasheet (for all Opta™ variants) is available and downloadable as PDF from the link below:
STEP Files
The complete STEP files (for all Opta™ variants) are available and downloadable from the link below:
First Use
Powering the Opta™
Opta™ can be powered in different ways:
- Using a USB-C® cable (not included) for programming purposes only. Opta's output ports (relay outputs) are not powered via its USB-C® port.
- Using an external +12 VDC to +24 VDC power supply connected to Opta's power supply terminals. Please, refer to the pinout section of the user manual.
Hello World Example
Let's program Opta™ with the classic
hello world
example used in the Arduino ecosystem: the Blink
sketch. We will use this example to verify the board's connection to the Arduino IDE and that the Opta™ core and device are working as expected.There are two ways to program this example in the device:
- Navigate to File > Examples > 01.Basics > Blink.
- Copy and paste the code below into a new sketch in the Arduino IDE.
1void setup() {2 // Initialize LED_BUILTIN as an output3 pinMode(LED_BUILTIN, OUTPUT);4}5
6void loop() {7 // Turn the LED_BUILTIN ON8 digitalWrite(LED_BUILTIN, HIGH);9 delay(1000);10 // Turn the user LED_BUILTIN OFF11 digitalWrite(LED_BUILTIN, LOW);12 delay(1000);13}
For all Opta™ variants, the
macro represents the green LED on top of the device's RESET button.LED_BUILTIN
To upload the code to your Opta™ device, click the Verify button to compile the sketch and check for errors; then click the Upload button to program the device with the sketch.
You should see the green LED on top of your device's
RESET
button turn on for one second, then off for one second, repeatedly. USB®-C Port
Opta™ has an onboard USB®-C port that can be used for programming the device's microcontroller and for data logging with mass storage devices such as USB memory sticks.
Opta's USB®-C port shall be used only for programming or data logging. This port does not power Opta's output relays.
Electrical Terminals
This user manual section covers Opta's electrical terminals, showing their main hardware and software characteristics. Opta™ has 12 electrical terminals, four of which can be used for the power supply of the device, and eight of them can be used as digital/analog inputs.
Power Supply
As shown in the image below, the first four terminals, from left to right, are Opta's power supply terminals; two are marked with
+
signs and two with -
signs. An external +12 VDC to +24 VDC power supply can be connected to these terminals. Opta's maximum power consumption at +12 VDC is 2 W, and at +24 VDC is 2.2 W.
For use with Opta™ devices, we recommend the official Finder 78.12.1.230.2400 power supply. This power supply was designed to provide stable +24 VDC despite consistently fluctuating current draw.
Programmable Inputs
The image below shows Opta™ devices have eight analog/digital programmable inputs accessible through terminals
I1
, I2
, I3
, I4
, I5
, I6
, I7
, and I8
. Analog/digital input terminals are mapped as described in the following table:
Opta™ Terminal | Arduino Pin Mapping |
---|---|
| /
|
| /
|
| /
|
| /
|
| /
|
| /
|
| /
|
| /
|
Analog Inputs
The input voltage range for each analog input terminal is the following:
- Input voltage range: 0 to +10 VDC
The analog input terminals can be used through the built-in functions of the Arduino programming language. To use the input terminals as analog inputs:
- Add the
instruction in your sketch'sanalogReadResolution()
function.setup()
The sketch below shows how to monitor analog voltages on Opta's input terminals
I1
, I2
, and I3
. It initializes a serial connection, takes readings from each defined terminal, converts those readings into voltage based on a 12-bit resolution, and outputs these voltage values through the Arduino IDE's Serial Monitor. The readings are looped every second, allowing you to monitor changes real-time changes.1/**2 Opta's Analog Input Terminals3 Name: opta_analog_inputs_example.ino4 Purpose: This sketch demonstrates the use of I1, I2, and I3 input 5 terminals as analog inputs on Opta.6
7 @author Arduino PRO Content Team8 @version 2.0 22/07/239*/10
11// Define constants for voltage, resolution, and divider.12const float VOLTAGE_MAX = 3.0; // Maximum voltage that can be read13const float RESOLUTION = 4095.0; // 12-bit resolution14const float DIVIDER = 0.3; // Voltage divider15
16// Array of terminals.17const int TERMINALS[] = {A0, A1, A2};18
19// Number of terminals.20const int NUM_PINS = 3;21
22void setup() {23 // Initialize serial communication at 9600 bits per second.24 Serial.begin(9600);25
26 // Enable analog inputs on Opta27 // Set the resolution of the ADC to 12 bits.28 analogReadResolution(12);29}30
31void loop() {32 // Loop through each of the terminal, read the terminal analog value, convert it to voltage, and print the result.33 for (int i = 0; i < NUM_PINS; i++) {34 readAndPrint(TERMINALS[i], i + 1);35 }36
37 // Delay for a second before reading the terminals again.38 delay(1000);39}40
41// This function reads the value from the specified pin, converts it to voltage, and prints the result.42void readAndPrint(int terminal, int terminalNumber) {43 // Read the input value from the analog pin.44 int terminalValue = analogRead(terminal);45
46 // Convert the terminal value to its corresponding voltage. 47 float voltage = terminalValue * (VOLTAGE_MAX / RESOLUTION) / DIVIDER;48
49 // Print the terminal value and its corresponding voltage.50 Serial.print("I");51 Serial.print(terminalNumber);52 Serial.print(" value: ");53 Serial.print(terminalValue);54 Serial.print(" corresponding to ");55 Serial.print(voltage, 5);56 Serial.println(" VDC");57}
Digital Inputs
The input voltage range for each digital input terminal is the following:
- Input voltage range: 0 to +24 VDC
The input terminals can be used through the built-in functions of the Arduino programming language. To use the input terminals as digital inputs:
- Add the
instruction in your sketch'spinMode(pinName, INPUT)
function.setup()
The sketch below shows how to monitor digital states on Opta's input terminals
I1
, I2
, and I3
. It initializes a serial connection, takes readings from each defined terminal, and interprets them as either HIGH
or LOW
digital states. These states are then output through the Arduino IDE's Serial Monitor. The state readings are looped every second, allowing you to monitor real-time changes.1/**2 Opta's Digital Input Terminals3 Name: opta_digital_inputs_example.ino4 Purpose: This sketch demonstrates the use of I1, I2, and I3 input5 terminals as digital inputs on Opta.6
7 @author Arduino PRO Content Team8 @version 2.0 23/07/239*/10
11// Array of terminals.12const int TERMINALS[] = {A0, A1, A2};13
14// Number of terminals.15const int NUM_PINS = 3;16
17void setup() {18 // Initialize serial communication at 9600 bits per second.19 Serial.begin(9600);20
21 // Set the mode of the pins as digital inputs.22 for (int i = 0; i < NUM_PINS; i++) {23 pinMode(TERMINALS[i], INPUT);24 }25}26
27void loop() {28 // Loop through each of the terminal, read the terminal digital value, and print the result.29 for (int i = 0; i < NUM_PINS; i++) {30 readAndPrint(TERMINALS[i], i + 1);31 }32
33 // Delay for a second before reading the terminals again.34 delay(1000);35}36
37// This function reads the digital value from the specified pin and prints the result.38void readAndPrint(int terminal, int terminalNumber) {39 // Read the input value from the digital pin.40 int terminalValue = digitalRead(terminal);41 42 // Print the terminal value.43 Serial.print("I");44 Serial.print(terminalNumber);45 Serial.print(" value: ");46 Serial.println(terminalValue);47}
LEDs
Opta™ Lite and Opta™ RS485 devices have four user-programmable LEDs, and Opta™ WiFi devices have an extra one.
User-programmable LEDs are mapped as described in the following table:
Opta™ User LED | Arduino Pin Mapping |
---|---|
| /
|
| /
|
| /
|
| /
|
(WiFi variant only) | /
|
(Green color) | /
|
(Red color) |
|
The sketch below shows how to create a Knight Rider-style "scanning" effect using Opta™s user LEDs. It works by sequentially lighting up each user's LED, creating a visual effect of scanning back and forth. This effect is achieved by defining an array of the user LED identifiers and using loops to cycle through these identifiers, turning each user LED on and off in sequence.
1/**2 Opta's Knight Rider Scanning Effect3 Name: opta_knight_rider_example.ino4 Purpose: This sketch demonstrates a Knight Rider scanning effect using 5 the user LEDs of Opta devices.6
7
8 @author Arduino PRO Content Team9 @version 2.0 22/07/2310*/11
12// Define an array to hold the pin numbers for Opta's user LEDs.13const int USER_LEDS[] = {LED_D0, LED_D1, LED_D2, LED_D3};14
15// Number of Opta's user LEDs16const int NUM_LEDS = 4;17
18void setup() {19 // Set the mode for each user LED to OUTPUT.20 for (int i = 0; i < NUM_LEDS; i++) {21 pinMode(USER_LEDS[i], OUTPUT);22 }23}24
25void loop() {26 // Scan from the first LED to the last.27 for (int i = 0; i < NUM_LEDS; i++) {28 // Turn on the LED.29 // Wait for 50 milliseconds.30 digitalWrite(USER_LEDS[i], HIGH); 31 delay(50); 32 // Turn off the LED.33 // Wait for 50 milliseconds.34 digitalWrite(USER_LEDS[i], LOW); 35 delay(50); 36 }37 38 // Scan back from the last LED to the first.39 for (int i = NUM_LEDS - 1; i >= 0; i--) {40 // Turn on the LED.41 // Wait for 50 milliseconds.42 digitalWrite(USER_LEDS[i], HIGH); 43 delay(50); 44 // Turn off the LED.45 // Wait for 50 milliseconds.46 digitalWrite(USER_LEDS[i], LOW); 47 delay(50); 48 }49}
You should see a Knight Rider-style "scanning" effect with Opta's user LEDs.
You also have another user-programmable LED located on top of the RESET button of the device; this green user LED is represented with the
LED_BUILTIN
macro and it is available in all Opta™ variants. The USER LED located above the USER BUTTON is only available on Opta™ WiFi (AFX00002).
The blink code that uses the green
LED_BUILTIN
LED is shown below:1void setup() {2 // Initialize LED_BUILTIN as an output3 pinMode(LED_BUILTIN, OUTPUT);4}5
6void loop() {7 // Turn the LED_BUILTIN ON8 digitalWrite(LED_BUILTIN, HIGH);9 delay(1000);10 // Turn the user LED_BUILTIN OFF11 digitalWrite(LED_BUILTIN, LOW);12 delay(1000);13}
You should see the green LED on top of your device's RESET button turn on for one second, then off for one second, repeatedly.
User Button
All Opta™ variants devices have an onboard user-programmable button; this user button is mapped as
BTN_USER
in the Opta™ core. The user button has an internal pull-up resistor, meaning its default value (while not being pressed) is HIGH
. The user-programmable button can be used through the built-in functions of the Arduino programming language.
To use the user button, first define it as a digital input:
- Add the
instruction in your sketch'spinMode(BTN_USER, INPUT)
function.setup()
To read the status of the user button:
- Add the
instruction in your sketch.digitalRead(BTN_USER)
The sketch below shows how to use Opta's programmable user button to control the sequence of status LEDs,
D0
to D3
. 1/**2 Opta's User Button Example3 Name: opta_user_button_example.ino4 Purpose: Configures Opta's user-programmable button to control the user LEDs.5 This example includes debouncing for the user button.6
7 @author Arduino PRO Content Team8 @version 2.0 23/07/239*/10
11// Current and previous state of the button.12int buttonState = 0;13int lastButtonState = 0;14
15// Counter to keep track of the LED sequence.16int counter = 0;17
18// Variables to implement button debouncing.19unsigned long lastDebounceTime = 0;20unsigned long debounceDelay = 50; // In ms21
22// Array to store LED pins.23int LEDS[] = {LED_D0, LED_D1, LED_D2, LED_D3};24int NUM_LEDS = 4;25
26void setup() {27 // Initialize Opta user LEDs.28 for(int i = 0; i < NUM_LEDS; i++) {29 pinMode(LEDS[i], OUTPUT);30 }31 pinMode(BTN_USER, INPUT);32}33
34void loop() {35 int reading = digitalRead(BTN_USER);36 37 // Check if button state has changed.38 if (reading != lastButtonState) {39 lastDebounceTime = millis();40 }41
42 // Debouncing routine.43 if ((millis() - lastDebounceTime) > debounceDelay) {44 if (reading != buttonState) {45 buttonState = reading;46
47 // Only increment the counter if the new button state is HIGH.48 if (buttonState == HIGH) {49 if(counter < NUM_LEDS){50 counter++;51 }52 else{53 counter = 0;54 }55 }56 }57 }58
59 // Save the current state as the last state, for next time through the loop.60 lastButtonState = reading;61 62 // Control LED states.63 changeLights();64}65
66/**67 Control the status LEDs based on a counter value.68 Turns off all LEDs first, then turns on the LED 69 corresponding to the current counter value.70
71 @param None.72*/73void changeLights() {74 // Turn off all user LEDs.75 for(int i = 0; i < NUM_LEDS; i++) {76 digitalWrite(LEDS[i], LOW);77 }78
79 // Turn on the selected user LED.80 if(counter > 0) {81 digitalWrite(LEDS[counter - 1], HIGH);82 }83}
The sketch initializes the state of the user's LEDs and button, along with variables for button debouncing. This sketch continuously reads the state of the user button, debounces the button input to avoid false triggering due to electrical noise, and increments a counter each time the button is pressed. It then passes the control to the
changeLights()
function. This function first turns off all LEDs and then, depending on the value of the counter, turns on the corresponding LED. With each button press, the counter increments, and a different LED lights up, cycling back to the beginning after the final LED.You should now be able to control the status LED sequence by pressing Opta's programmable user button.
Relays
Opta™ devices (all variants) have four Normally Open (NO) 10 A relays capable of actuating on loads at a rated voltage of 250 VAC and up to a maximum switching voltage of 400 VAC.
User-programmable relay outputs are mapped as described in the following table:
Opta™ Relay Output | Arduino Pin Mapping |
---|---|
| /
|
| /
|
| /
|
| /
|
The output relays can be used through the built-in functions of the Arduino programming language. To use an output relay as a digital output:
- Add the
instruction in your sketch'spinMode(relayOutput, OUTPUT)
function.setup()
To change the status of the output relay (
LOW
or HIGH
):- Add your sketch's
ordigitalWrite(relayOutput, LOW)
instruction.digitalWrite(relayOutput, HIGH)
The sketch below tests the output relays and status LEDs of an Opta™ device. The sketch initializes the relay outputs and user LEDs as outputs; then, the sketch turns each output relay and its corresponding status LED on and off in sequence, with a one-second delay between each state change. This allows us to visually verify the correct functioning of the output relays and user LEDs.
1/*2 Opta's Output Relays 3 Name: opta_outputs_relays_example.ino4 Purpose: This sketch tests the output relays of Opta devices.5
6
7 @author Arduino PRO Content Team8 @version 2.0 22/07/239*/10
11// Arrays of relays and user LEDs12int relayOutputs[] = {D0, D1, D2, D3};13int userLeds[] = {LED_D0, LED_D1, LED_D2, LED_D3};14
15// Compute the number of relays/LEDs based on the size of the relayPins array16int numRelays = 4;17
18void setup() {19 for(int i = 0; i < numRelays; i++) {20 // Sets the mode of the relays and user LEDs as outputs21 pinMode(relayOutputs[i], OUTPUT); 22 pinMode(userLeds[i], OUTPUT); 23 }24}25
26void loop() {27 // For each relay/user LED: turn it on, wait for a second, turn it off, wait for another second28 for(int i = 0; i < numRelays; i++) {29 digitalWrite(relayOutputs[i], HIGH); 30 digitalWrite(userLeds[i], HIGH);31 delay(1000);32 digitalWrite(relayOutputs[i], LOW);33 digitalWrite(userLeds[i], LOW);34 delay(1000);35 }36}
Communication
This user manual section covers the different communication interfaces and protocols supported by Opta™ devices, including the Ethernet, RS-485, Modbus, Wi-Fi®, and Bluetooth®.
Ethernet
Opta™ devices (all variants) feature an onboard low-power 10BASE-T/100BASE-TX Ethernet physical layer (PHY) transceiver. The transceiver complies with the IEEE 802.3 and 802.3u standards and supports communication with an Ethernet MAC through a standard RMII interface. The Ethernet transceiver is accessible through the onboard RJ45 connector.
The
Arduino Mbed OS Opta Boards
core has a built-in library that lets you use the onboard Ethernet PHY transceiver right out of the box: the Ethernet
library. Let's use an example code demonstrating some of the transceiver's capabilities. The sketch below enables an Opta™ device to connect to the Internet via an Ethernet connection. Once connected, it performs a
GET
request to the ip-api.com
service to fetch details about the device's IP address. It then parses the received JSON object using the Arduino_JSON
library to extract key IP details: IP address, city, region, and country. This data is then printed to the Arduino IDE's Serial Monitor.1/**2 Web Client (Ethernet version)3 Name: opta_ethernet_web_client.ino4 Purpose: This sketch connects an Opta device to ip-api.com via Ethernet5 and fetches IP details for the device.6
7 @author Arduino PRO Content Team8 @version 2.0 15/08/239*/10
11// Include the necessary libraries.12#include <Ethernet.h>13#include <Arduino_JSON.h>14
15// Server address for ip-api.com.16const char* server = "ip-api.com";17
18// API endpoint path to get IP details in JSON format.19String path = "/json/";20
21// Static IP configuration for the Opta device.22IPAddress ip(10, 130, 22, 84);23
24// Ethernet client instance for the communication.25EthernetClient client;26
27// JSON variable to store and process the fetched data.28JSONVar doc;29
30// Variable to ensure we fetch data only once.31bool dataFetched = false;32
33void setup() {34 // Begin serial communication at a baud rate of 115200.35 Serial.begin(115200);36
37 // Wait for the serial port to connect,38 // This is necessary for boards that have native USB.39 while (!Serial);40
41 // Attempt to start Ethernet connection via DHCP,42 // If DHCP failed, print a diagnostic message.43 if (Ethernet.begin() == 0) {44 Serial.println("- Failed to configure Ethernet using DHCP!");45
46 // Try to configure Ethernet with the predefined static IP address.47 Ethernet.begin(ip);48 }49 delay(2000);50}51
52void loop() {53 // Ensure we haven't fetched data already,54 // ensure the Ethernet link is active,55 // establish a connection to the server,56 // compose and send the HTTP GET request.57 if (!dataFetched) {58 if (Ethernet.linkStatus() == LinkON) {59 if (client.connect(server, 80)) {60 client.print("GET ");61 client.print(path);62 client.println(" HTTP/1.1");63 client.print("Host: ");64 client.println(server);65 client.println("Connection: close");66 client.println();67
68 // Wait and skip the HTTP headers to get to the JSON data.69 char endOfHeaders[] = "\r\n\r\n";70 client.find(endOfHeaders);71
72 // Read and parse the JSON response.73 String payload = client.readString();74 doc = JSON.parse(payload);75
76 // Check if the parsing was successful.77 if (JSON.typeof(doc) == "undefined") {78 Serial.println("- Parsing failed!");79 return;80 }81
82 // Extract and print the IP details.83 Serial.println("*** IP Details:");84 Serial.print("- IP Address: ");85 Serial.println((const char*)doc["query"]);86 Serial.print("- City: ");87 Serial.println((const char*)doc["city"]);88 Serial.print("- Region: ");89 Serial.println((const char*)doc["regionName"]);90 Serial.print("- Country: ");91 Serial.println((const char*)doc["country"]);92 Serial.println("");93
94 // Mark data as fetched.95 dataFetched = true;96 }97 // Close the client connection once done.98 client.stop();99 } else {100 Serial.println("- Ethernet link disconnected!");101 }102 }103}
The sketch includes the
Ethernet
and Arduino_JSON
libraries, essential for Ethernet and JSON handling functionality. In the setup()
function, serial communication is initiated for debugging and output. Instead of DHCP, the Ethernet connection uses a predefined static IP address.Once the Ethernet connection runs, the sketch connects to the
ip-api.com
service, utilizing the HTTP protocol. Specifically, an HTTP GET
request is crafted to retrieve details about the device's IP address, including its city, region, and country. If the connection to the server fails, the sketch will output an error message to the Arduino IDE's Serial Monitor for troubleshooting.Within the
loop()
function, an HTTP GET
request is sent to the ip-api.com
service once. The sketch then waits for and skips the response's HTTP headers, parsing the following JSON payload.Key IP details such as IP address, city, region, and country are extracted and then displayed in the IDE's Serial Monitor using the parsed data. If the Ethernet link happens to be disconnected, a corresponding message is printed to the Serial Monitor. Should the JSON parsing fail, an error message is showcased on the IDE's Serial Monitor, prompting the sketch to exit the current iteration of the
loop()
function immediately.You should see the following output in the Arduino IDE's Serial Monitor:
You can download the example code here.
The Media Access Control (MAC) address is essential for computer networking and devices with Internet of Things (IoT) capabilities, such as the Opta™. To learn more into-depth about how to retrieve the MAC address of an Opta™ device using the Arduino ecosystem tools, check out the following tutorial:
RS-485
Opta™ RS485 and WiFi variants have a built-in RS-485 interface, enabling the construction of robust and reliable data transmission systems. RS-485 interface is still the most widely used protocol for Point Of Sale (POS), industrial, and telecommunications applications. The wide common-mode range enables data transmission over longer cable lengths and in noisy environments such as the floor of a factory. Also, the high input impedance of the receivers allows more devices to be attached to the lines.
The Opta™ RS485 and WiFi variants' RS-485 interface operates in a half-duplex mode. This means it can send or receive data at any given time, but not simultaneously.
RS-485 data lines in Opta™ RS485 and Opta™ WiFi variants are labeled as described in the following table:
EIA-485 Specification Labels | Opta™ Labels |
---|---|
|
|
|
|
RS-485 data lines labels differ between manufacturers. Most manufacturers will use
and +
to label the data lines or variations such as –
and D+
. Some manufacturers will label inputs as A and B but get the polarity backward, so A is positive and B negative. Although predicting how other manufacturers will mark these lines is impossible, practical experience suggests that the D-
line should be connected to the A terminal, and the -
line should be connected to the B terminal. Reversing the polarity will not damage an RS-485 device but will not communicate.+
To enable communication on Opta™ devices via its RS-485 interface, you can use the
library. Let's use an example code demonstrating some of its RS-485 capabilities. Here is an example of using the ArduinoRS485
ArduinoRS485
library to transmit messages via the RS-485 interface on an Opta™ device.1/*2 Opta's Basic RS-485 Communication3
4 Name: opta_basic_rs485_example.ino5 Purpose: This sketch tests the RS-485 interface of 6 Opta RS485 and Opta WiFi devices.7
8 @author Arduino PRO Content Team9 @version 2.0 22/07/2310*/11#include <ArduinoRS485.h>12
13// Set the baudrate to be used by the RS-485 interface.14constexpr auto baudrate { 115200 };15
16/**17 Configure the RS-485 interface. It initializes the18 interface with the specified baud rate and explicitly 19 disables data reception to avoid potential data 20 collision in this half-duplex communication standard.21
22 @param baudrate (int)23*/24void configureRS485(const int baudrate) {25 const auto bitduration { 1.f / baudrate };26 const auto wordlen { 9.6f }; // Or 10.0f depending on the channel configuration27 const auto preDelayBR { bitduration * wordlen * 3.5f * 1e6 };28 const auto postDelayBR { bitduration * wordlen * 3.5f * 1e6 }29
30 RS485.begin(baudrate);31 RS485.setDelays(preDelayBR, postDelayBR);32 RS485.noReceive();33}34
35/**36 Send a text message through the RS485 interface. Writes 37 the intended message to the transmission buffer, appends38 carriage return and newline characters for message 39 termination, and finally ends the transmission. 40
41 @param message (char)42*/43size_t printlnRS485(char* message) {44 RS485.beginTransmission();45 auto len = strlen(message);46 RS485.write(message, len);47 RS485.write('\r');48 RS485.write('\n');49 RS485.endTransmission();50}51
52void setup() {53 configureRS485(baudrate);54 printlnRS485("- RS-485 interface configured!");55}56
57void loop() {58 delay(2000);59 // Wait for two seconds and then sends a test message via the RS485 interface.60 printlnRS485("- This is a message transmitted via RS-485!");61}
The sketch starts with the
configureRS485()
function, which initializes the RS-485 interface with the defined baud rate and turns off data receiving. The printlnRS485()
function handles the transmission of text messages. It starts the transmission, sends the message followed by a carriage return and newline character, and ends the transmission. The setup()
function calls the configureRS485()
function to configure the RS-485 interface and then sends a confirmation message. The loop()
function repeatedly sends a message every two seconds using the printlnRS485()
function.To learn more into-depth about the RS-485 interface in Opta™ devices, check out the following tutorial:
Modbus (RTU/TCP)
Opta™ RS485 and WiFi variants incorporate a built-in Modbus interface, enabling the implementation of robust and reliable data transmission systems. Modbus, in its RTU version that utilizes RS-485 serial transmission or in its TCP version that operates over Ethernet, remains one of the most widely used protocols for industrial automation applications, building management systems, and process control, among others.
Modbus RTU, generally operating in half-duplex mode, with its capability to handle noisy and long-distance transmission lines, makes it an excellent choice for industrial environments. Modbus RTU communication is supported using the Arduino Opta's RS-485 physical interface.
Opta™ does not have internal terminator resistors, so they must be added following the Modbus protocol specification if necessary.
Modbus TCP, taking advantage of Ethernet connectivity, allows easy integration with existing computer networks and facilitates data communication over long distances using the existing network infrastructure. It operates in full-duplex mode, allowing simultaneous sending and receiving of data.
The many nodes connected in a Modbus network, whether RTU or TCP, allow high flexibility and scalability in constructing automation and control systems.
To learn more about the Modbus interface in Opta™ devices, check out the following tutorials and application notes:
- Getting Started with Modbus RTU on Opta™
- Modbus TCP On Opta™ Using PLC IDE
- Tank Level Monitoring with the Opta™
- Tank Thermoregulation with Portenta Machine Control & Opta™
- Energy Management with Opta™
Wi-Fi®
Opta™ WiFi variant devices feature an onboard Wi-Fi® module that provides seamless wireless connectivity, allowing Opta™ to connect to Wi-Fi® networks and interact with other devices over-the-air (OTA).
Some of the key capabilities of Opta™'s onboard Wi-Fi® module are the following:
- Wireless connectivity: The onboard Wi-Fi® module supports IEEE 802.11b/g/n Wi-Fi® standards, enabling devices to establish reliable and high-speed wireless connections to access the Internet and communicate with other devices.
- Secure communication: The onboard module incorporates various security protocols such as WEP, WPA, WPA2, and WPA3, ensuring robust data encryption and protection against unauthorized access during wireless communication.
- Onboard antenna: Opta™ WiFi devices feature an onboard Wi-Fi® antenna specifically designed, matched, and certified for the onboard Wi-Fi® module requirements.
The
Arduino Mbed OS Opta Boards
core has a built-in library that lets you use the onboard Wi-Fi® module right out of the box: the WiFi
library. Let's walk through an example code demonstrating some of the module's capabilities.The sketch below enables an Opta™ device to connect to the Internet via Wi-Fi® (like the Ethernet example). Once connected, it performs a
GET
request to the ip-api.com
server to fetch details related to its IP address. It then parses the received JSON object using the Arduino_JSON
library to extract key IP details: IP address, city, region, and country. This data is then printed to the Arduino IDE's Serial Monitor.You need to create first a header file named
arduino_secrets.h
to store your Wi-Fi® network credentials. To do this, add a new tab by clicking the ellipsis (the three horizontal dots) button on the top right of the Arduino IDE 2.Put
arduino_secrets.h
as the "Name for new file" and enter the following code on the header file:1char ssid[] = "SECRET_SSID"; // Your network SSID (name)2char password[] = "SECRET_PASS"; // Your network password (use for WPA, or use as key for WEP)
Replace
SECRET_SSID
with the name of your Wi-Fi® network and SECRET_PASS
with the password of it and save the project. The example code is as follows: 1/**2 WiFi Web Client3 Name: opta_wifi_web_client.ino4 Purpose: This sketch connects an Opta device to ip-api.com via WiFi5 and fetches IP details.6
7 @author Arduino PRO Content Team8 @version 2.2 16/08/239*/10
11#include <WiFi.h>12#include <Arduino_JSON.h>13
14// Wi-Fi network details.15const char* ssid = "YOUR_SSID";16const char* password = "YOUR_PASSWORD";17
18// Server address for ip-api.com.19const char* server = "ip-api.com";20
21// API endpoint path to get IP details in JSON format.22String path = "/json";23
24// Wi-Fi client instance for the communication.25WiFiClient client;26
27// JSON variable to store and process the fetched data.28JSONVar doc;29
30// Variable to ensure we fetch data only once.31bool dataFetched = false;32
33void setup() {34 // Begin serial communication at a baud rate of 115200.35 Serial.begin(115200);36
37 // Wait for the serial port to connect,38 // This is necessary for boards that have native USB.39 while (!Serial);40
41 // Start the Wi-Fi connection using the provided SSID and password.42 Serial.print("- Connecting to ");43 Serial.println(ssid);44 WiFi.begin(ssid, password);45
46 while (WiFi.status() != WL_CONNECTED) {47 delay(1000);48 Serial.print(".");49 }50
51 Serial.println();52 Serial.println("- Wi-Fi connected!");53 Serial.print("- IP address: ");54 Serial.println(WiFi.localIP());55}56
57void loop() {58 // Check if the IP details have been fetched.59 // If not, call the function to fetch IP details,60 // Set the flag to true after fetching.61 if (!dataFetched) {62 fetchIPDetails();63 dataFetched = true;64 }65}66
67/**68 Fetch IP details from defined server69
70 @param none71 @return IP details72*/73void fetchIPDetails() {74 if (client.connect(server, 80)) {75 // Compose and send the HTTP GET request.76 client.print("GET ");77 client.print(path);78 client.println(" HTTP/1.1");79 client.print("Host: ");80 client.println(server);81 client.println("Connection: close");82 client.println();83
84 // Wait and skip the HTTP headers to get to the JSON data.85 char endOfHeaders[] = "\r\n\r\n";86 client.find(endOfHeaders);87
88 // Read and parse the JSON response.89 String payload = client.readStringUntil('\n');90 doc = JSON.parse(payload);91
92 // Check if the parsing was successful. 93 if (JSON.typeof(doc) == "undefined") {94 Serial.println("- Parsing failed!");95 return;96 }97
98 // Extract and print the IP details.99 Serial.println("*** IP Details:");100 String query = doc["query"];101 Serial.print("- IP Address: ");102 Serial.println(query);103 String city = doc["city"];104 Serial.print("- City: ");105 Serial.println(city);106 String region = doc["regionName"];107 Serial.print("- Region: ");108 Serial.println(region);109 String country = doc["country"];110 Serial.print("- Country: ");111 Serial.println(country);112 Serial.println("");113 } else {114 Serial.println("- Failed to connect to server!");115 }116
117 // Close the client connection once done. 118 client.stop();119}
The sketch includes the
WiFi
and Arduino_JSON
, which provide the necessary Wi-Fi® and JSON handling functionality. The setup()
function initiates serial communication for debugging purposes and attempts to connect to a specified Wi-Fi® network. If the connection is not established, the sketch will keep trying until a successful connection is made.Once the Wi-Fi® connection is established, the sketch is ready to connect to the
ip-api.com
server using the HTTP protocol. Specifically, an HTTP GET
request is constructed to query details related to its IP address. The GET
request is sent only once after the Wi-Fi® connection is active.The
loop()
function is the heart of the sketch. It checks whether the data has been fetched or not. If the data still needs to be fetched, it tries to establish a connection to the server. If the connection is successful, the sketch sends an HTTP GET
request, skips the HTTP headers of the response, and uses the JSON.parse()
function from the Arduino_JSON
library to parse the JSON object from the response. The parsed data extracts key IP details like IP address, city, region, and country, which are then printed to the Arduino IDE's Serial Monitor. Once the data is published, the client is disconnected to free up resources. Suppose the JSON parsing fails for any reason. In that case, an error message is outputted to the Arduino IDE's Serial Monitor, and the sketch immediately exits the current iteration of the loop()
function.Since the data is fetched only once, there's no need for repeatedly sending
HTTP GET
requests. After the initial fetch, you should see the details related to the IP address displayed in the Arduino IDE's Serial Monitor:You can download the example code here.
The MAC address is essential for computer networking and devices with Internet of Things (IoT) capabilities, such as the Opta™. To learn more into-depth about how to retrieve the MAC address of an Opta™ device using the Arduino ecosystem tools, check out the following tutorial:
Bluetooth Low Energy®
Opta™ WiFi variant devices feature an onboard Bluetooth Low Energy® module, which supports Bluetooth 5.1 BR/EDR/LE up to 3 Mbps PHY data rate. Bluetooth 4.2 is supported by Arduino firmware.
To enable Bluetooth® communication on Opta™ devices, you can use the
library. Let's use an example code demonstrating some of its Bluetooth® module's capabilities. Here is an example of using the ArduinoBLE library to create a voltage level monitor application, such as a 0 to 10 VDC sensor. The provided example code demonstrates the creation of a Bluetooth® Low Energy service and the characteristic of voltage values read from one of the analog input terminals of an Opta™ device to a central device, for example, a smartphone.ArduinoBLE
You can use the nRF Connect for Mobile app from Nordic Semiconductor® to test the functionality of the example code shown below. nRF Connect is a powerful tool that allows you to scan and explore Bluetooth Low Energy® devices and communicate with them.
1/**2 Opta's Bluetooth Example3 Name: opta_bluetooth_example.ino4 Purpose: Read voltage level from an analog input terminal of an Opta device,5 then maps the voltage reading to a percentage value ranging from 0 to 100.6
7 @author Arduino PRO Content Team8 @version 1.1 23/07/239*/10
11#include <ArduinoBLE.h>12
13// Define the voltage service and its characteristic.14BLEService voltageService("1101");15BLEUnsignedCharCharacteristic voltageLevelChar("2101", BLERead | BLENotify);16
17const int TERMINAL = A0;18const long interval = 200; // Delay interval in ms for voltage reading and LED blinking19
20BLEDevice central;21
22/**23 Read voltage level from an analog input terminal of an Opta device,24 then maps the voltage reading to a voltage value ranging from 0 to 10 VDC.25
26 @param none27 @return the voltage value (int).28*/29int readVoltageLevel() {30 int voltage = analogRead(TERMINAL);31 int voltageLevel = map(voltage, 0, 4095, 0, 10);32 return voltageLevel;33}34
35void setup() {36 // Initialize LED_USER as an output.37 pinMode(LED_USER, OUTPUT);38 digitalWrite(LED_USER, HIGH);39
40 // Initialize serial communication at 9600 bits per second.41 Serial.begin(9600);42
43 // Enable analog inputs on Opta.44 // Set the resolution of the ADC to 12 bits.45 analogReadResolution(12); 46
47 // Initialize the BLE module.48 if (!BLE.begin()) {49 Serial.println("- Starting BLE failed!");50 while (1); // In case of failure, loop indefinitely.51 }52
53 // Set the local name and advertised service for the BLE module.54 BLE.setLocalName("VoltageMonitor");55 BLE.setAdvertisedService(voltageService);56 voltageService.addCharacteristic(voltageLevelChar);57 BLE.addService(voltageService);58
59 // Start advertising the BLE service.60 BLE.advertise();61 Serial.println("- Bluetooth device active, waiting for connections...");62}63
64void loop() {65 // Get the current time since the Arduino started.66 unsigned long currentMillis = millis();67 68 // Static variables to hold the last time the tasks were performed.69 static unsigned long previousVoltageMillis = 0; // Last time the voltage was read70 static unsigned long previousLEDMillis = 0; // Last time the LED state changed71
72 // If the interval has passed, update the LED.73 if (currentMillis - previousLEDMillis >= interval) {74 // Save the current time to check against in the next loop iteration.75 previousLEDMillis = currentMillis;76
77 // Toggle the state of the LED.78 digitalWrite(LED_USER, !digitalRead(LED_USER));79 }80
81 // If a central device is connected.82 if (central) {83 if (central.connected()) {84 // Set the LED color to solid blue when connected.85 digitalWrite(LED_USER, HIGH);86
87 // If the interval has passed, update the voltage level.88 if (currentMillis - previousVoltageMillis >= interval) {89 // Save the current time to check against in the next loop iteration.90 previousVoltageMillis = currentMillis;91
92 // Read the voltage level and update the BLE characteristic with the voltage level value.93 int voltageLevel = readVoltageLevel();94
95 Serial.print("- Voltage level is: ");96 Serial.println(voltageLevel);97 voltageLevelChar.writeValue(voltageLevel);98 }99 }100 else {101 central = BLE.central();102 if (central) {103 Serial.print("- Connected to device: ");104 Serial.println(central.address());105 }106 else {107 Serial.print("- BLE not connected: ");108 Serial.println(central.address());109 }110 }111 }112 else {113 central = BLE.central();114 if (central) {115 Serial.print("- Connected to device: ");116 Serial.println(central.address());117 }118 }119}
After importing the necessary libraries and defining the Bluetooth® Low Energy service and characteristic, the
setup()
function initializes the Opta™ device and sets up the Bluetooth® Low Energy service and characteristic. The sketch then starts advertising the defined service to allow connections.In the
loop()
function, the sketch constantly checks for a Bluetooth® Low Energy connection. When a central device connects to the device, the Opta's built-in USER LED stays solidly on, and the sketch begins continuously reading the voltage level from an analog input terminal, mapping it to a voltage value between 0 and 10 VDC, and transmitting it to the central device via the defined Bluetooth® Low Energy characteristic. If no central device is connected, the USER LED blinks regularly. The non-blocking approach of the sketch allows simultaneous tasks on it, such as sensor data reading and LED control.You should be able now to connect to your Opta™ using a central device. The Bluetooth ® Low Energy service and characteristic information are shown in the image below using the nRF Connect for Mobile app.
Interrupts
Opta's analog/digital programmable inputs and user-programmable button are interrupt capable. An interrupt is a signal that prompts Opta's microcontroller to stop its current execution and start executing a special routine known as the Interrupt Service Routine (ISR). Once the ISR finishes, the microcontroller resumes executing its previous routine.
Interrupts are particularly useful when reacting instantly to an external event, such as a button press or a sensor signal. Without interrupts, you would have to constantly poll the status of a button or a sensor in the main loop of your running sketch. With interrupts, you can let your Opta's microcontroller do other tasks and only react when a desired event occurs.
Due to Opta's microcontroller interrupt structure, interrupts in terminals
(I1
) and A0
(I4
) cannot be used simultaneously to avoid operational issues. It is important to note that, despite this limitation, any other combination of inputs can be used for interrupt detection. However, this means that, at most, seven of the eight available inputs can be used simultaneously for interrupts, as combinations containing both A4
and I1
are excluded from viable configurations.I4
Interrupts can be used through the built-in functions of the Arduino programming language. To enable interrupts in your Opta's analog/digital programmable inputs and user-programmable button:
- Add the
instruction in your sketch'sattachInterrupt(digitalPinToInterrupt(pin), ISR, mode)
function. Notice that thesetup()
parameter can bepin
,A0
,A1
,A2
,A3
,A4
,A5
,A6
, orA7
; theBTN_USER
parameter is the ISR function to call when the interrupt occurs, and theISR
parameter defines when the interrupt should be triggered (mode
,LOW
,CHANGE
, orRISING
).FALLING
The sketch below shows how to use Opta's programmable user button to control the sequence of status LEDs,
D0
to D3
. In the original code shown in the User Button section, the user button's state was continuously checked inside the main loop of the sketch, and when a change was detected, the LEDs were updated accordingly. While this approach works for simple tasks, it becomes inefficient when your Opta™ has to perform more complex tasks or react to multiple inputs. In the modified code, we've set up an interrupt that triggers on a falling edge (FALLING
) of the signal from the user button, which means it triggers when the button is pressed. 1/**2 Opta's User Button Example (Interrupt)3 Name: opta_user_button_interrupt_example.ino4 Purpose: Configures Opta's user-programmable button to control the user LEDs5 using interrupts rather than polling the button's state. This example includes6 debouncing for the user button.7 8 @author Arduino PRO Content Team9 @version 2.0 23/07/2310*/11
12// Current and previous state of the button.13volatile bool buttonPressed = false;14
15// Counter to keep track of the LED sequence.16int counter = 0;17
18// Variables to implement button debouncing.19unsigned long lastDebounceTime = 0;20unsigned long debounceDelay = 150;21
22// Array to store LED pins.23int LEDS[] = {LED_D0, LED_D1, LED_D2, LED_D3};24int NUM_LEDS = 4;25
26void setup() {27 // Initialize Opta user LEDs.28 for(int i = 0; i < NUM_LEDS; i++) {29 pinMode(LEDS[i], OUTPUT);30 }31 32 // Set up the interrupt on USER_BTN to trigger on a rising edge (when the button is pressed)33 attachInterrupt(digitalPinToInterrupt(BTN_USER), buttonISR, FALLING);34}35
36/**37 Interrupt service routine (ISR)38 Set the variable buttonPressed to true39
40 @param None.41*/42void buttonISR() {43 buttonPressed = true;44}45
46void loop() {47 // If the button was pressed48 if (buttonPressed) {49 // Debouncing routine.50 if ((millis() - lastDebounceTime) > debounceDelay) {51 lastDebounceTime = millis();52
53 // Only increment the counter if the new button state is HIGH.54 if(counter < NUM_LEDS){55 counter++;56 }57 else{58 counter = 0;59 }60 61 // Reset the button pressed flag62 buttonPressed = false;63 }64 }65
66 // Control LED states.67 changeLights();68}69
70/**71 Control the status LEDs based on a counter value.72 Turns off all LEDs first, then turns on the LED 73 corresponding to the current counter value.74
75 @param None.76*/77void changeLights() {78 // Turn off all user LEDs.79 for(int i = 0; i < NUM_LEDS; i++) {80 digitalWrite(LEDS[i], LOW);81 }82
83 // Turn on the selected user LED.84 if(counter > 0) {85 digitalWrite(LEDS[counter - 1], HIGH);86 }87}
Note: The example code above employs a "debouncing" technique to ensure that the user button press is recognized as a singular event despite any rapid electrical fluctuations that can occur when physically pressing the button. Upon detecting a press through an interrupt, the sketch waits for a brief interval (150 milliseconds, set by the
debounceDelay
variable) before processing the press. This delay ensures that any additional "noise" or fluctuations don't trigger multiple registrations of the same press, ensuring precise LED sequencing operation.To learn more into-depth about interrupts in Opta™ devices, check out the following tutorial:
Real-Time Clock (RTC)
Opta™ device's (all variants) microcontroller (the STM32H747XI) features a low-power Real-Time Clock (RTC) with sub-second accuracy and hardware calendar accessible through specific RTC management methods from Mbed™️.
Some of the key capabilities of Opta's onboard RTC are the following:
- Calendar with subsecond, seconds, minutes, hours (12 or 24 formats), week day, date, month, and years in BCD (binary-coded decimal) format.
- Automatic correction for 28, 29 (leap year), 30, and 31 days of the month.
- Two programmable alarms.
- Timestamp feature, which can be used to save the calendar content.
The
Arduino Mbed OS Opta Boards
core has built-in libraries that let you use the device's onboard RTC, the WiFi
, and mbed_mktime
libraries; let's walk through an example code demonstrating some of the module's capabilities. The sketch below connects an Opta™ device to a Wi-Fi® network, synchronizes its onboard RTC with a Network Time Protocol (NTP) server using the NTPClient
library, and prints the current RTC time to the Arduino IDE's Serial Monitor every 5 seconds. Install the NTPClient
library using the Arduino IDE's Library Manager. You need to create first a header file named
arduino_secrets.h
to store your Wi-Fi® network credentials. To do this, add a new tab by clicking the ellipsis (the three horizontal dots) button on the top right of the Arduino IDE 2.Put
arduino_secrets.h
as the "Name for new file" and enter the following code on the header file:1char ssid[] = "SECRET_SSID"; // Your network SSID (name)2char password[] = "SECRET_PASS"; // Your network password (use for WPA, or use as key for WEP)
Replace
SECRET_SSID
with the name of your Wi-Fi® network and SECRET_PASS
with the password of it and save the project. The example code is as follows: 1/**2 Opta's RTC Example3 Name: opta_rtc_example.ino4 Purpose: Connects an Opta device to a Wi-Fi network, synchronizes its onboard RTC5 with a NTP server and prints the current RTC time to the Serial Monitor every 5 seconds.6
7 @author Arduino PRO Content Team8 @version 1.0 23/07/239*/10
11// Libraries used in the sketch.12#include <WiFi.h>13#include "arduino_secrets.h"14#include <NTPClient.h>15#include <mbed_mktime.h>16
17// Wi-Fi network credentials.18int status = WL_IDLE_STATUS;19
20// NTP client configuration and RTC update interval.21WiFiUDP ntpUDP;22NTPClient timeClient(ntpUDP, "pool.ntp.org", -6*3600, 0);23// Display time every 5 seconds.24unsigned long interval = 5000UL;25unsigned long lastTime = 0;26
27void setup() {28 Serial.begin(9600);29 while (!Serial) {30 ;31 }32 delay(5000);33
34 // Attempt Wi-Fi connection.35 while (status != WL_CONNECTED) {36 Serial.print("- Attempting to connect to WPA SSID: ");37 Serial.println(ssid);38 status = WiFi.begin(ssid, password);39 delay(500);40 }41
42 // NTP client object initialization and time update, display updated time on the Serial Monitor.43 timeClient.begin();44 timeClient.update();45 const unsigned long epoch = timeClient.getEpochTime();46 set_time(epoch);47
48 // Show the synchronized time.49 Serial.println();50 Serial.println("- TIME INFORMATION:");51 Serial.print("- RTC time: ");52 Serial.println(getLocalTime());53}54
55void loop() {56 // Display RTC time periodically.57 unsigned long currentTime = millis();58 if (currentTime - lastTime >= interval) {59 displayRTC();60 lastTime = currentTime;61 }62}63
64/**65 Display Opta's internal RTC time 66
67 @param none68 @return none69*/70void displayRTC() {71 Serial.println();72 Serial.println("- TIME INFORMATION:");73 Serial.print("- RTC time: ");74 Serial.println(getLocalTime());75}76
77/**78 Retrieves Opta's RTC time79
80 @param none81 @return Opta's RTC time in hh:mm:ss format82*/83String getLocalTime() {84 char buffer[32];85 tm t;86 _rtc_localtime(time(NULL), &t, RTC_FULL_LEAP_YEAR_SUPPORT);87 strftime(buffer, 32, "%k:%M:%S", &t);88 return String(buffer);89}
This sketch uses
WiFi.h
, NTPClient.h
, and mbed_mktime.h
libraries and methods to connect to a specific Wi-Fi® network using the provided credentials (network name and password). Once the internet connection has been established, the code synchronizes with a Network Time Protocol (NTP) server, using the NTPClient.h
library, to obtain the current Coordinated Universal Time (UTC). This time is then converted to local time and used to set the device's internal RTC, thanks to the functionalities provided by mbed_mktime.h
methods. Once the RTC has been synchronized in the setup, the sketch enters an infinite loop. In this loop, every 5 seconds, it retrieves the current time from the RTC and prints it to the serial monitor in a more readable format, using the tm structure provided by
mbed_mktime.h
. This ensures that even if the internet connection is interrupted or the system restarts, accurate time tracking is maintained as long as the RTC's power supply is not interrupted. You should see the following output in the Arduino IDE's Serial Monitor:You can download the example code here. To learn more about date and time manipulation operations, check out the
function documentation from Mbed™️. Also, check out this real-world case described in the following application note where Opta's RTC:time
Arduino Cloud
All Opta™ variants are fully compatible with the Arduino Cloud, simplifying how professional applications are developed and tracked. By using the IoT Cloud, you can, for example, monitor your Opta's input terminals, control your device's user LEDs and output relays remotely, and update your device's firmware OTA. To learn more about the Arduino Cloud visit our Getting Started with Arduino Cloud
In case it is the first time you are using the IoT Cloud:
- To use the IoT Cloud, you need an account. If you do not have an account, create one for free here.
- To use the Arduino Web Editor or IoT Cloud, the Arduino Create Agent must be running on your computer. You can install the Arduino Create Agent here.
Let's walk through a step-by-step demonstration of how to use an Opta™ device with the IoT Cloud.
Log in to your IoT Cloud account; you should see the following:
First, provision your Opta™ device on your IoT Cloud space. To do this, navigate to Devices and then click on the ADD DEVICE button:
The Setup Device pop-up window will appear. Navigate into AUTOMATIC and select the Arduino board option:
After a while, your Opta™ device should be discovered by the IoT Cloud, as shown below:
To set up your device, click the CONFIGURE button, assign a name to your device, and choose the preferred network connection method. The device supports both Wi-Fi® and Ethernet as connectivity options; thus, it can be configured for either connection type.
Based on the chosen connection type, the device will be configured accordingly. The user manual will show the configuration process for both Wi-Fi® and Ethernet connections.
Via Ethernet Connection
To configure Opta™ with an Ethernet connection, after clicking CONFIGURE, please choose the Ethernet option.
This will configure your Opta™ for secure Ethernet communication with the IoT Cloud, which may require some time to complete.
Via Wi-Fi® Connection
To configure using the Wi-Fi® connection for the device, please choose the WiFi option after clicking the CONFIGURE button.
To learn how to configure Opta™ in the Arduino Cloud using the two connectivity setup options, check out our tutorials for Ethernet and Wi-Fi
Your Opta™ will be configured to communicate securely with the IoT Cloud via a Wi-Fi® connection; this process can take a while.
After configuring Opta™ with your choice of connection, the next step is creating a "Thing" to test the connection between your device and the IoT Cloud. Go to Things and click on CREATE THING, then name your thing.
Navigate into Associate Device and click the Select Device button. Select your Opta™ device and associate it with your "Thing".
If Opta™ has been configured to use the Ethernet connection, no additional steps are required as DHCP is used to configure the Ethernet interface automatically.
If you need to use specific Ethernet interface settings, turn off the default settings in Network by clicking on Change to input custom parameters.
The required network credentials are:
- IP address
- Netmask
- Gateway
- DNS
To make the changes take effect with custom network credentials, please navigate to the Sketch tab and upload the sketch to load the credentials on the device. The sketch upload will be shown later in the process.
If Opta™ has been configured to use the Wi-Fi® connection, navigate to Network, click the Configure button, and enter your network credentials.
The project is ready to add variables to your "Thing"; navigate into Cloud Variables and click the ADD button.
Add one variable with the following characteristics:
- Name:
led
- Variable type:
boolean
- Variable permission:
Read & Write
- Variable update policy:
On change
You should see the
led
variable in the Cloud Variables section. Navigate into Dashboards and select the CREATE DASHBOARD button; this will create a new dashboard and give your dashboard a name.Add the following widgets to your dashboard:
- Switch: Name the widget Switch and link it to the
variable you created before.led
- LED: Name the widget LED and link it to the
variable you created before.led
Your dashboard should look like the following:
Go back to your Things and open the "Thing" you created. In the "Thing" setup page, navigate into Sketch, where you should see the online editor.
In the generated sketch, define
LED_D0
pin as an output in the setup()
function:1void setup() {2 // Initialize serial and wait for port to open:3 Serial.begin(9600);4 // This delay gives the chance to wait for a Serial Monitor without blocking if none is found5 delay(1500);6
7 // LED_D0 macro access the onboard green LED8 pinMode(LED_D0, OUTPUT);9
10 // Defined in thingProperties.h11 initProperties();12
13 // Connect to Arduino Cloud14 ArduinoCloud.begin(ArduinoIoTPreferredConnection);15
16 /*17 The following function allows you to obtain more information18 related to the state of network and IoT Cloud connection and errors19 the higher number the more granular information you’ll get.20 The default is 0 (only errors).21 Maximum is 422 */23 setDebugMessageLevel(2);24 ArduinoCloud.printDebugInfo();25}
In the
onLedChange()
function, which was generated automatically by the Arduino Cloud when the variable led
was created, you must associate the onboard green LED state with the led
variable:1/*2 Since Led is READ_WRITE variable, onLedChange() is3 executed every time a new value is received from IoT Cloud.4*/5void onLedChange() {6 digitalWrite(LED_D0, !led);7}
The complete example code can be found below:
1/*2 Sketch generated by the Arduino Cloud3
4 Arduino Cloud Variables description5
6 The following variables are automatically generated and updated when changes are made to the Thing7
8 bool led;9
10 Variables which are marked as READ/WRITE in the Cloud Thing will also have functions11 which are called when their values are changed from the Dashboard.12 These functions are generated with the Thing and added at the end of this sketch.13*/14
15#include "thingProperties.h"16
17void setup() {18 // Initialize serial and wait for port to open:19 Serial.begin(9600);20 // This delay gives the chance to wait for a Serial Monitor without blocking if none is found21 delay(1500);22
23 // LED_D0 macro access the onboard green LED24 pinMode(LED_D0, OUTPUT);25
26 // Defined in thingProperties.h27 initProperties();28
29 // Connect to Arduino Cloud30 ArduinoCloud.begin(ArduinoIoTPreferredConnection);31
32 /*33 The following function allows you to obtain more information34 related to the state of network and IoT Cloud connection and errors35 the higher number the more granular information you’ll get.36 The default is 0 (only errors).37 Maximum is 438 */39 setDebugMessageLevel(2);40 ArduinoCloud.printDebugInfo();41}42
43void loop() {44 ArduinoCloud.update();45 // Your code here46}47
48/*49 Since Led is READ_WRITE variable, onLedChange() is50 executed every time a new value is received from IoT Cloud.51*/52void onLedChange() {53 digitalWrite(LED_D0, !led);54}
To upload the code to the Opta™ from the online editor, click the green Verify button to compile the sketch and check for errors, then click the green Upload button to program the board with the sketch.
The code uses the
thingProperties.h
header, which contains essential network interface settings and definitions required for the above example code.The Arduino Cloud creates This header file automatically, customized to the specific network interface settings and variables defined. It is advisable not to modify this file manually. Instead, any changes to variables should be made within the Arduino Cloud environment.
If Opta™ is set up with Wi-Fi® as the network interface, the
thingProperties.h
file will include settings such as the network SSID and password. The example code for this configuration is shown below:1//code generated by Arduino IoT Cloud, DO NOT EDIT.2
3#include <ArduinoIoTCloud.h>4#include <Arduino_ConnectionHandler.h>5
6const char SSID[] = SECRET_SSID; // Network SSID (name)7const char PASS[] = SECRET_OPTIONAL_PASS; // Network password (use for WPA, or use as key for WEP)8
9void onLedChange();10
11bool led;12
13void initProperties(){14
15 ArduinoCloud.addProperty(led, READWRITE, ON_CHANGE, onLedChange);16
17}18
19WiFiConnectionHandler ArduinoIoTPreferredConnection(SSID, PASS);
Alternatively, if Opta™ is configured to use an Ethernet connection, the
thingProperties.h
file will include different settings such as IP, DNS, Gateway, and Netmask. The corresponding code for this configuration would be as follows:1#include <ArduinoIoTCloud.h>2#include <Arduino_ConnectionHandler.h>3
4const char IP[] = SECRET_OPTIONAL_IP;5const char DNS[] = SECRET_OPTIONAL_DNS;6const char GATEWAY[] = SECRET_OPTIONAL_GATEWAY;7const char NETMASK[] = SECRET_OPTIONAL_NETMASK;8
9void onLedChange();10
11bool led;12
13void initProperties(){14
15 ArduinoCloud.addProperty(led, READWRITE, ON_CHANGE, onLedChange);16
17}18
19EthernetConnectionHandler ArduinoIoTPreferredConnection(IP, DNS, GATEWAY, NETMASK);
Navigate into Dashboards again, your board should connect to the Wi-Fi® network or via Ethernet interface you configured before (you can follow the connection process with the online editor integrated Serial Monitor). Your board's STATUS LED 1 (
LED_D0
) should light on or off when the position of the switch changes.To learn more about Opta™ and the Arduino IoT Cloud, check out the following resources that can help you learning about the Arduino IoT Cloud and Opta™:
Support
If you encounter any issues or have questions while working with Opta™ devices, we provide various support resources to help you find answers and solutions.
Help Center
Explore our Help Center, which offers a comprehensive collection of articles and guides for Opta™ devices. The Help Center is designed to provide in-depth technical assistance and help you make the most of your device.
Forum
Join our community forum to connect with other Opta™ devices users, share your experiences, and ask questions. The Forum is an excellent place to learn from others, discuss issues, and discover new ideas and projects related to Opta™.
Contact Us
Please get in touch with our support team if you need personalized assistance or have questions not covered by the help and support resources described before. We're happy to help you with any issues or inquiries about Opta™ devices.
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.