### Start User or Example Apps with Arduino App CLI Source: https://github.com/arduino/docs-content/blob/main/content/software/app-lab/7.cli/1.cli/apps-lab-cli.md Use shortcuts like `user:` and `examples:` with the `app start` command to quickly launch your own or built-in example applications. ```sh # run your own app arduino-app-cli app start user:my-app # run an example app (e.g. blink) arduino-app-cli app start examples:blink ``` -------------------------------- ### Full Example: Bar Animation Setup Source: https://github.com/arduino/docs-content/blob/main/content/hardware/10.mega/shields/giga-display-shield/tutorials/03.lvgl-guide/content.md Complete Arduino sketch demonstrating the setup of the GIGA Display Shield, LVGL, and a fully animated bar. ```arduino #include "Arduino_H7_Video.h" #include "Arduino_GigaDisplayTouch.h" #include "lvgl.h" Arduino_H7_Video Display(800, 480, GigaDisplayShield); /* Arduino_H7_Video Display(1024, 768, USBCVideo); */ Arduino_GigaDisplayTouch TouchDetector; static void set_slider_val(void * bar, int32_t val) { lv_bar_set_value((lv_obj_t *)bar, val, LV_ANIM_ON); } void setup() { delay(3000); Display.begin(); TouchDetector.begin(); lv_obj_t * screen = lv_obj_create(lv_scr_act()); lv_obj_set_size(screen, Display.width(), Display.height()); static lv_coord_t col_dsc[] = { 500, LV_GRID_TEMPLATE_LAST}; static lv_coord_t row_dsc[] = { 400, LV_GRID_TEMPLATE_LAST}; lv_obj_t * grid = lv_obj_create(lv_scr_act()); lv_obj_set_grid_dsc_array(grid, col_dsc, row_dsc); lv_obj_set_size(grid, Display.width(), Display.height()); lv_obj_center(grid); lv_obj_t * label; lv_obj_t * obj; obj = lv_obj_create(grid); lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, 0, 1, LV_GRID_ALIGN_STRETCH, 0, 1); lv_obj_set_flex_flow(obj, LV_FLEX_FLOW_COLUMN); lv_obj_t * bar = lv_bar_create(obj); lv_obj_set_size(bar, 200, 20); lv_obj_center(bar); lv_bar_set_value(bar, 70, LV_ANIM_OFF); lv_anim_t a; lv_anim_init(&a); lv_anim_set_exec_cb(&a, set_slider_val); lv_anim_set_time(&a, 3000); lv_anim_set_playback_time(&a, 3000); lv_anim_set_var(&a, bar); lv_anim_set_values(&a, 0, 100); lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE); lv_anim_start(&a); } void loop() { lv_timer_handler(); } ``` -------------------------------- ### Minimal LVGL Example with Grid Source: https://github.com/arduino/docs-content/blob/main/content/hardware/10.mega/shields/giga-display-shield/tutorials/03.lvgl-guide/content.md A complete example demonstrating the setup of a 2x2 grid and adding objects to each cell. Includes necessary includes and initialization. ```arduino #include "Arduino_H7_Video.h" #include "lvgl.h" #include "Arduino_GigaDisplayTouch.h" Arduino_H7_Video Display(800, 480, GigaDisplayShield); Arduino_GigaDisplayTouch TouchDetector; void setup() { delay(3000); Display.begin(); TouchDetector.begin(); //Display & Grid Setup lv_obj_t* screen = lv_obj_create(lv_scr_act()); lv_obj_set_size(screen, Display.width(), Display.height()); static lv_coord_t col_dsc[] = { 370, 370, LV_GRID_TEMPLATE_LAST }; static lv_coord_t row_dsc[] = { 215, 215, 215, 215, LV_GRID_TEMPLATE_LAST }; lv_obj_t* grid = lv_obj_create(lv_scr_act()); lv_obj_set_grid_dsc_array(grid, col_dsc, row_dsc); lv_obj_set_size(grid, Display.width(), Display.height()); //top left lv_obj_t* obj; obj = lv_obj_create(grid); lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, 0, 1, //column LV_GRID_ALIGN_STRETCH, 0, 1); //row //bottom left obj = lv_obj_create(grid); lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, 0, 1, //column LV_GRID_ALIGN_STRETCH, 1, 1); //row //top right obj = lv_obj_create(grid); lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, 1, 1, //column LV_GRID_ALIGN_STRETCH, 0, 1); //row //bottom right obj = lv_obj_create(grid); lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, 1, 1, //column LV_GRID_ALIGN_STRETCH, 1, 1); //row } void loop() { lv_timer_handler(); } ``` -------------------------------- ### Initialize Web Server and Get Start Time Source: https://github.com/arduino/docs-content/blob/main/content/hardware/12.hero/boards/yun-rev2/tutorials/temperature-web-panel/content.md This code initializes the web server to listen only on localhost and captures the sketch's start time by running the 'date' command. ```cpp // Listen for incoming connection only from localhost // (no one from the external network could connect) server.listenOnLocalhost(); server.begin(); // get the time that this sketch started: Process startTime; startTime.runShellCommand("date"); while (startTime.available()) { char c = startTime.read(); startString += c; } ``` -------------------------------- ### start Source: https://github.com/arduino/docs-content/blob/main/content/micropython/00.first-steps/03.runtime-package/runtime-package.md Begins the main loop of the program, allowing for setup, loop, cleanup, and preload hooks. ```APIDOC ## start ### Description Begins the main loop with hooks for setup, loop, cleanup, and preload. ### Parameters - `setup` (function) - Function to run once at the start. - `loop` (function) - Function to run repeatedly. - `cleanup` (function, optional) - Function to run once at the end. - `preload` (function, optional) - Function to run before setup. ### Returns None ``` -------------------------------- ### Set up BLE Services and Start Advertising Source: https://github.com/arduino/docs-content/blob/main/content/hardware/06.nicla/boards/nicla-sense-me/tutorials/web-ble-dashboard/content.md Configures BLE event handlers for various characteristics and starts advertising the BLE service. Ensure the service and characteristics are properly defined before this setup. ```cpp co2Characteristic.setEventHandler(BLERead, onCo2CharacteristicRead); gasCharacteristic.setEventHandler(BLERead, onGasCharacteristicRead); rgbLedCharacteristic.setEventHandler(BLEWritten, onRgbLedCharacteristicWrite); versionCharacteristic.setValue(VERSION); BLE.addService(service); BLE.advertise(); ``` -------------------------------- ### Full Example: Display Text with emWin Source: https://github.com/arduino/docs-content/blob/main/content/hardware/10.mega/shields/giga-display-shield/tutorials/12.emwin-guide/content.md This example initializes emWin, creates a window, and displays "Hello world" in red with a 16-point font on a green background. It includes the necessary setup and loop functions. ```arduino #include "DIALOG.h" static void _cbWin(WM_MESSAGE * pMsg) { switch (pMsg->MsgId) { case WM_PAINT: GUI_SetBkColor(GUI_GREEN); GUI_Clear(); GUI_SetColor(GUI_RED); GUI_SetFont(&GUI_Font16_1); GUI_DispString("Hello world"); break; default: WM_DefaultProc(pMsg); break; } } void setup() { delay(3000); GUI_Init(); WM_MULTIBUF_Enable(1); WM_CreateWindowAsChild(0, 0, LCD_GetXSize(), LCD_GetYSize(), WM_HBKWIN, WM_CF_SHOW, _cbWin, 0); } void loop() { GUI_Exec(); } ``` -------------------------------- ### GET Dashboards Source: https://github.com/arduino/docs-content/blob/main/content/arduino-cloud/07.api/02.arduino-iot-api/arduino-iot-api.md This example shows how to retrieve a list of dashboards using a GET request. ```APIDOC ## GET /dashboards ### Description Retrieves a list of dashboards associated with the authenticated user. ### Method GET ### Endpoint https://api2.arduino.cc/iot/v2/dashboards ### Request Example No request body is required for this GET request. ### Response #### Success Response (200) Returns a JSON array of dashboard objects. #### Response Example ```json [ { "id": "dashboard-id-1", "name": "My Dashboard", "layout": { ... }, "widgets": [ ... ] } ] ``` ``` -------------------------------- ### begin() Source: https://github.com/arduino/docs-content/blob/main/content/hardware/02.uno/boards/uno-r4-wifi/tutorials/led-matrix/led-matrix.md Initializes and starts the LED matrix. ```APIDOC ## begin() ### Description Starts the LED matrix, preparing it for operation. ### Usage ```cpp LEDMatrix.begin(); ``` ``` -------------------------------- ### Arduino Blink Example Source: https://github.com/arduino/docs-content/blob/main/content/software/ide-v1/tutorials/getting-started/cores/arduino-mbed_portenta/installing-mbed-os-portenta-boards.md The standard Blink example sketch provided by the Arduino IDE. Upload this to verify your board setup. ```cpp /* Blink Turns an LED on for one second, then off for one second, repeatedly. Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to LED13. Use "pinMode()" to set the LED to OUTPUT and "digitalWrite()" to turn it on or off. */ void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } ``` -------------------------------- ### Install LIS3DH Accelerometer Library Source: https://github.com/arduino/docs-content/blob/main/content/micropython/02.micropython-course/course/08.examples/examples.md Installs the LIS3DH driver library for the 3-axis digital accelerometer using the MicroPython Package Installer (mip). This is required before using the accelerometer example. ```python import mip mip.install("https://raw.githubusercontent.com/tinypico/tinypico-micropython/master/lis3dh%20library/lis3dh.py") ``` -------------------------------- ### RPC.begin() Source: https://github.com/arduino/docs-content/blob/main/content/hardware/10.mega/boards/giga-r1-wifi/tutorials/giga-dual-core/giga-dual-core.md Initializes the RPC library and boots the M4 core. Returns 1 on success and 0 on failure. ```APIDOC ## RPC.begin() ### Description Initializes the library. This function also boots the M4 core. ### Syntax ```arduino RPC.begin() ``` ### Returns - `1` on success. - `0` on failure. ``` -------------------------------- ### Install SSD1306 OLED Driver Source: https://github.com/arduino/docs-content/blob/main/content/micropython/02.micropython-course/course/08.examples/examples.md Installs the SSD1306 driver library for OLED displays using the MicroPython Package Installer (mip). This is required before using the OLED display example. ```python import mip mip.install("https://raw.githubusercontent.com/micropython/micropython-lib/master/micropython/drivers/display/ssd1306/ssd1306.py") ``` -------------------------------- ### Navigate to Example Directory Source: https://github.com/arduino/docs-content/blob/main/content/hardware/04.pro/carriers/portenta-mid-carrier/tutorials/user-manual/content.md Change the current directory to where the example scripts, such as 'gpios.py', are located. ```bash cd root/examples/ ``` -------------------------------- ### Start an Arduino App Source: https://github.com/arduino/docs-content/blob/main/content/hardware/02.uno/boards/uno-q/tutorials/07.debian-guide/content.md Start a specific Arduino App. Replace `user:my-app` or `examples:blink` with the actual app identifier. ```bash arduino-app-cli app start user:my-app ``` ```bash arduino-app-cli app start examples:blink ``` -------------------------------- ### Arduino Library begin() Method Source: https://github.com/arduino/docs-content/blob/main/content/learn/08.contributions/03.arduino-creating-library-guide/arduino-creating-library-guide.md Implement the begin() method to handle hardware configuration for your library. This is called from the sketch's setup() function. ```arduino void Morse::begin() { pinMode(_pin, OUTPUT); } ``` -------------------------------- ### Build CHIP Tool Example Source: https://github.com/arduino/docs-content/blob/main/content/hardware/03.nano/boards/nano-matter/tutorials/07.open-thread-border-router/content.md Build the CHIP Tool example within the connectedhomeip directory using the provided script. ```bash cd connectedhomeip scripts/examples/gn_build_example.sh examples/chip-tool out/debug ``` -------------------------------- ### Upload Blink Example Sketch Source: https://github.com/arduino/docs-content/blob/main/content/software/ide-v1/tutorials/getting-started/cores/arduino-samd/installing-samd21-core.md Verify the installation by uploading the standard Blink example sketch to your SAMD board. This is done by navigating to File > Examples > 01.Basics > Blink and clicking the upload button. ```arduino void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } ``` -------------------------------- ### Arduino Edge Control SD Card Datalogger Example Source: https://github.com/arduino/docs-content/blob/main/content/hardware/05.pro-solutions/solutions-and-kits/edge-control/tutorials/01.user-manual/content.md This code logs analog input values to a Micro SD card. Ensure the SD library is installed and the chip select pin is correctly configured. The code initializes the Edge Control, powers necessary rails, and sets up analog input before starting to log data. ```arduino #include #include #include constexpr unsigned int adcResolution{ 12 }; const int chipSelect = PIN_SD_CS; void setup() { // Open serial communications and wait for port to open: Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } EdgeControl.begin(); // Power on the 3V3 rail for SD Card Power.on(PWR_3V3); Power.on(PWR_VBAT); Wire.begin(); Expander.begin(); Serial.print("Waiting for IO Expander Initialization..."); while (!Expander) { Serial.print("."); delay(100); } Serial.println(" done."); Input.begin(); Input.enable(); analogReadResolution(adcResolution); Serial.print("Initializing SD card..."); // see if the card is present and can be initialized: if (!SD.begin(chipSelect)) { Serial.println("Card failed, or not present"); // don't do anything more: while (1) ; } Serial.println("card initialized."); } void loop() { // make a string for assembling the data to log: String dataString = ""; int sensor = Input.analogRead(INPUT_05V_CH01); // read the Edge Control 0-5v Channel 1 dataString += String(sensor); // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open("datalog.txt", FILE_WRITE); // if the file is available, write to it: if (dataFile) { dataFile.println(dataString); dataFile.close(); // print to the serial port too: Serial.println(dataString); } // if the file isn't open, pop up an error: else { Serial.println("error opening datalog.txt"); } } ``` -------------------------------- ### Get Current Time in Loop Source: https://github.com/arduino/docs-content/blob/main/content/hardware/03.nano/boards/nano-33-iot/tutorials/wifi-connection/content.md In the main loop, get the current time since the sketch started running. This is used for timing interval-based operations. ```arduino void loop() { unsigned long currentMillisInfo = millis(); ``` -------------------------------- ### Setup Function Source: https://github.com/arduino/docs-content/blob/main/content/tutorials/projects/localize-your-board-with-an-sms/localize-your-board-with-an-sms.md Initializes the necessary objects for the sketch, establishes the data connection using `connectNetwork()`, and begins the localization service. ```arduino //code section used to initialize data connection and localization object void setup() { connectNetwork(); location.begin(); } ``` -------------------------------- ### Initialize LED Matrix in Setup Source: https://github.com/arduino/docs-content/blob/main/content/hardware/02.uno/boards/uno-r4-wifi/tutorials/led-matrix/led-matrix.md Call the begin() method within the setup() function to initialize the LED Matrix. ```arduino matrix.begin(); ``` -------------------------------- ### Example 2.1: Hello World Shift In Source: https://github.com/arduino/docs-content/blob/main/content/tutorials/communication/guide-to-shift-in/guide-to-shift-in.md Basic example demonstrating how to read data from a single shift register. Ensure the CD4021 library is installed. ```arduino #include // Define the pins connected to the shift register const int LATCH_PIN = 8; // RCLK const int CLOCK_PIN = 12; // SHCP const int DATA_PIN = 11; // SER // Create a new CD4021 object CD4021 shiftRegister(LATCH_PIN, CLOCK_PIN, DATA_PIN); void setup() { // Initialize serial communication Serial.begin(9600); Serial.println("Shift In Example 2.1"); // Initialize the shift register shiftRegister.begin(); } void loop() { // Read the state of the shift register byte data = shiftRegister.read(); // Print the data to the serial monitor Serial.print("Data: "); for (int i = 7; i >= 0; i--) { Serial.print(bitRead(data, i)); } Serial.println(); // Wait for a short period before reading again delay(200); } ``` -------------------------------- ### Basic LED Matrix Sketch Setup Source: https://github.com/arduino/docs-content/blob/main/content/hardware/02.uno/boards/uno-r4-wifi/tutorials/led-matrix/led-matrix.md A complete basic sketch demonstrating the initialization of the LED Matrix library, object creation, and setup. ```arduino #include "Arduino_LED_Matrix.h" ArduinoLEDMatrix matrix; void setup() { Serial.begin(115200); matrix.begin(); } ``` -------------------------------- ### Full QSPI Flash Read/Write Example Source: https://github.com/arduino/docs-content/blob/main/content/hardware/04.pro/boards/portenta-h7/tutorials/reading-writing-flash-memory/content.md Demonstrates initializing the QSPI Flash, checking its properties, reading previous data, erasing, and writing a new message. This is a complete example for managing data on external flash. ```cpp #include "QSPIFBlockDevice.h" #include "MBRBlockDevice.h" using namespace mbed; #define BLOCK_DEVICE_SIZE 1024 * 8 // 8 KB #define PARTITION_TYPE 0x0B // FAT 32 void setup() { Serial.begin(115200); while (!Serial); Serial.println("QSPI Block Device Test"); Serial.println("------------------------"); // Feed the random number generator for later content generation randomSeed(analogRead(0)); // Create a block device on the available space of the flash QSPIFBlockDevice root(PD_11, PD_12, PF_7, PD_13, PF_10, PG_6, QSPIF_POLARITY_MODE_1, 40000000); MBRBlockDevice blockDevice(&root, 1); // Initialize the Flash IAP block device and print the memory layout if(blockDevice.init() != 0 || blockDevice.size() != BLOCK_DEVICE_SIZE) { Serial.println("Partitioning block device..."); blockDevice.deinit(); // Allocate a FAT 32 partition MBRBlockDevice::partition(&root, 1, PARTITION_TYPE, 0, BLOCK_DEVICE_SIZE); blockDevice.init(); } const auto eraseBlockSize = blockDevice.get_erase_size(); const auto programBlockSize = blockDevice.get_program_size(); Serial.println("Block device size: " + String((unsigned int) blockDevice.size() / 1024) + " KB"); Serial.println("Readable block size: " + String((unsigned int) blockDevice.get_read_size()) + " bytes"); Serial.println("Programmable block size: " + String((unsigned int) programBlockSize) + " bytes"); Serial.println("Erasable block size: " + String((unsigned int) eraseBlockSize / 1024) + " KB"); String newMessage = "Random number: " + String(random(1024)); // Calculate the amount of bytes needed to store the message // This has to be a multiple of the program block size const auto messageSize = newMessage.length() + 1; // C String takes 1 byte for NULL termination const unsigned int requiredEraseBlocks = ceil(messageSize / (float) eraseBlockSize); const unsigned int requiredBlocks = ceil(messageSize / (float) programBlockSize); const auto dataSize = requiredBlocks * programBlockSize; char buffer[dataSize] {}; // Read back what was stored at previous execution Serial.println("Reading previous message..."); blockDevice.read(buffer, 0, dataSize); Serial.println(buffer); // Erase a block starting at the offset 0 relative // to the block device start address blockDevice.erase(0, requiredEraseBlocks * eraseBlockSize); // Write an updated message to the first block Serial.println("Writing new message..."); Serial.println(newMessage); blockDevice.program(newMessage.c_str(), 0, dataSize); // Deinitialize the device blockDevice.deinit(); Serial.println("Done."); } void loop() {} ``` -------------------------------- ### Install Vim Text Editor Source: https://github.com/arduino/docs-content/blob/main/content/hardware/02.uno/boards/uno-q/tutorials/07.debian-guide/content.md An example of installing a specific package, Vim, which includes downloading necessary libraries and configuring the editor for immediate use. ```bash sudo apt install vim ``` -------------------------------- ### Full Example: Display Image with emWin Source: https://github.com/arduino/docs-content/blob/main/content/hardware/10.mega/shields/giga-display-shield/tutorials/12.emwin-guide/content.md This example initializes emWin, sets the display to landscape mode, enables multi-buffering, and displays a bitmap image within a window. Ensure the image file is in the sketch directory. ```arduino #include "DIALOG.h" extern GUI_CONST_STORAGE GUI_BITMAP bmarduinologo; /* Image bitmap structure (see img_arduinologo_emwin.c in attach) */ static void _cbWin(WM_MESSAGE * pMsg) { switch (pMsg->MsgId) { case WM_CREATE: break; case WM_PAINT: GUI_SetBkColor(GUI_WHITE); GUI_Clear(); /* Draw image */ GUI_DrawBitmap(&bmarduinologo, 85, 35); break; default: WM_DefaultProc(pMsg); break; } } void setup() { /* Init SEGGER emWin library. It also init display and touch controller */ GUI_Init(); LCD_ROTATE_SetSel(1); /* Set landscape mode */ WM_MULTIBUF_Enable(1); /* Enable multi buffering mode for Windows manager */ /* Create the main window.*/ WM_CreateWindowAsChild(0, 0, LCD_GetXSize(), LCD_GetYSize(), WM_HBKWIN, WM_CF_SHOW, _cbWin, 0); } void loop() { /* Keep emWin alive, handle touch and other stuff */ GUI_Exec(); } ``` -------------------------------- ### Initialize WiFi and Serial Communication Source: https://github.com/arduino/docs-content/blob/main/content/hardware/01.mkr/01.boards/mkr-1000-wifi/tutorials/mkr-1000-connect-to-wifi/mkr-1000-connect-to-wifi.md Include necessary libraries, define WiFi credentials, and initialize serial communication. The setup function attempts to connect to the specified WiFi network and prints connection status. ```cpp #include #include #include "arduino_secrets.h" char ssid[] = SECRET_SSID; // your network SSID (name) char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) int status = WL_IDLE_STATUS; // the Wifi radio's status ``` ```cpp void setup() { //Initialize serial and wait for port to open: Serial.begin(9600); while (!Serial); // attempt to connect to Wifi network: while (status != WL_CONNECTED) { Serial.print("Attempting to connect to network: "); Serial.println(ssid); // Connect to WPA/WPA2 network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } // you're connected now, so print out the data: Serial.println("You're connected to the network"); Serial.println("----------------------------------------"); printData(); Serial.println("----------------------------------------"); } ``` -------------------------------- ### Get Sketch Start Time Source: https://github.com/arduino/docs-content/blob/main/content/hardware/12.hero/boards/yun-rev2/tutorials/temperature-web-panel/content.md Use the Process class to run the 'date' shell command and capture the output to determine the sketch's start time. ```arduino Process startTime; startTime.runShellCommand("date"); while(startTime.available()) { char c = startTime.read(); startString += c; } } ``` -------------------------------- ### Opta Analog Expansion Digital Input Example Source: https://github.com/arduino/docs-content/blob/main/content/hardware/07.opta/opta-family/opta/tutorials/01.user-manual/content.md This example demonstrates how to initialize and read all digital inputs from connected Analog Expansion modules. It includes setup for multiple channels with specific digital input configurations. ```arduino #include "OptaBlue.h" #define PERIODIC_UPDATE_TIME 2000 #define DELAY_AFTER_SETUP 1000 /* -------------------------------------------------------------------------- */ void printExpansionType(ExpansionType_t t) { /* -------------------------------------------------------------------------- */ if (t == EXPANSION_NOT_VALID) { Serial.print("Unknown!"); } else if (t == EXPANSION_OPTA_DIGITAL_MEC) { Serial.print("Opta --- DIGITAL [Mechanical] ---"); } else if (t == EXPANSION_OPTA_DIGITAL_STS) { Serial.print("Opta --- DIGITAL [Solid State] ---"); } else if (t == EXPANSION_DIGITAL_INVALID) { Serial.print("Opta --- DIGITAL [!!Invalid!!] ---"); } else if (t == EXPANSION_OPTA_ANALOG) { Serial.print("~~~ Opta ANALOG ~~~"); } else { Serial.print("Unknown!"); } } /* -------------------------------------------------------------------------- */ void printExpansionInfo() { /* -------------------------------------------------------------------------- */ static long int start = millis(); if (millis() - start > 5000) { start = millis(); Serial.print("Number of expansions: "); Serial.println(OptaController.getExpansionNum()); for (int i = 0; i < OptaController.getExpansionNum(); i++) { Serial.print("Expansion n. "); Serial.print(i); Serial.print(" type "); printExpansionType(OptaController.getExpansionType(i)); Serial.print(" I2C address "); Serial.println(OptaController.getExpansionI2Caddress(i)); } } } /* -------------------------------------------------------------------------- */ /* SETUP */ /* -------------------------------------------------------------------------- */ void setup() { /* -------------------------------------------------------------------------- */ Serial.begin(115200); delay(2000); Serial.println("*** Opta Analog Digital Input example ***"); OptaController.begin(); for (int i = 0; i < OptaController.getExpansionNum(); i++) { for (int k = 0; k < OA_AN_CHANNELS_NUM; k++) { /* all channels are initialized in the same way as VOLTAGE ADC */ AnalogExpansion::beginChannelAsDigitalInput(OptaController, i, // the device k, // the output channel you are using true, // filter comparator false, // invert comparator true, // use simple debounce algorithm OA_DI_SINK_1, // sink 120 uA OA_DI_DEB_TIME_5, // ~ 42 ms false, // use fix threshold 8.0, // threshold at 8 V 24.0); // unused in this c } } } } /* the optaAnalogTask function runs every 2000 ms it set the pwm for all the * channels from with a period equal to 10 ms and a variable duty cycle from 10% * to 70% */ /* -------------------------------------------------------------------------- */ void optaAnalogTask() { /* -------------------------------------------------------------------------- */ static long int start = millis(); static bool stop_pwm = false; ``` -------------------------------- ### UART Communication Setup Source: https://github.com/arduino/docs-content/blob/main/content/hardware/05.pro-solutions/solutions-and-kits/edge-control/tutorials/01.user-manual/content.md Configure UART communication on the Edge Control by setting the baud rate in the setup() function. This example sets the baud rate to 115200. ```arduino // Start UART communication at 115200 baud Serial1.begin(115200); ``` -------------------------------- ### Arduino EdgeControl Latching Example Source: https://github.com/arduino/docs-content/blob/main/content/hardware/05.pro-solutions/solutions-and-kits/edge-control/tutorials/01.user-manual/content.md This example demonstrates activating both Latching Outputs and Latching Commands in a sequence. It includes setup for serial communication and initialization of the Latching library. ```arduino #include void setup() { Serial.begin(9600); auto startNow = millis() + 2500; while (!Serial && millis() < startNow) ; delay(1000); Serial.println("Hello, Challenge!"); Latching.begin(); } void loop() { Latching.channelDirection(LATCHING_CMD_1, POSITIVE); Latching.strobe(2000); // 2 seconds with a 12v output on latching cmd output P Latching.channelDirection(LATCHING_CMD_1, NEGATIVE); Latching.strobe(2000); // 2 seconds with a 12v output on latching cmd output N Latching.channelDirection(LATCHING_OUT_1, POSITIVE); Latching.strobe(4000); // 4 seconds with a 12v output on latching output P (opening the motorized valve) Latching.channelDirection(LATCHING_OUT_1, NEGATIVE); Latching.strobe(4000); // 4 seconds with a 12v output on latching output N (closing the motorized valve) delay(1000); } ``` -------------------------------- ### Setup Function for Callbacks and Advertising Source: https://github.com/arduino/docs-content/blob/main/content/hardware/05.pro-solutions/solutions-and-kits/stella/tutorials/01.user-manual/content.md Initializes the sketch by registering UWB and BLE callbacks and starting BLE advertising with a specified device name. ```arduino void setup() { // Register all callbacks UWB.registerRangingCallback(rangingHandler); UWBNearbySessionManager.onConnect(clientConnected); // ... other callbacks // Start advertising with device name UWBNearbySessionManager.begin("Arduino Stella"); } ``` -------------------------------- ### I2C Data Transmission Example Source: https://github.com/arduino/docs-content/blob/main/content/hardware/02.uno/boards/uno-q/tutorials/01.user-manual/content.md This example demonstrates transmitting data to an I2C-compatible device. It includes starting a transmission, writing instruction and data bytes, and ending the transmission. ```cpp #include void setup() { // Initialize the I2C communication Wire.begin(); } void loop() { // Replace with the target device’s I2C address byte deviceAddress = 0x35; // Replace with the appropriate instruction byte byte instruction = 0x00; // Replace with the value to send byte value = 0xFA; // Begin transmission to the target device Wire.beginTransmission(deviceAddress); // Send the instruction byte Wire.write(instruction); // Send the value Wire.write(value); // End transmission Wire.endTransmission(); delay(2000); } ``` -------------------------------- ### Matter On/Off Light Example for Nesso N1 Source: https://github.com/arduino/docs-content/blob/main/content/hardware/09.kits/maker/nesso-n1/tutorials/user-manual/content.md This Arduino sketch configures the Nesso N1 as a Matter On/Off light. It includes setup for both Matter over Wi-Fi and Matter over Thread, with transport layer configuration handled by defines. The code defines a callback function to handle state changes and controls the built-in LED. Ensure the Arduino_Nesso_N1 library is installed before uploading. ```arduino #include #include // Include WiFi.h only if you plan to use Matter over Wi-Fi #include // --- Transport Layer Configuration --- // To use Matter over Thread, include the three defines below. // To use Matter over Wi-Fi, comment out or remove these three defines. #define CONFIG_ENABLE_CHIPOBLE 1 // Enables BLE for commissioning #define CHIP_DEVICE_CONFIG_ENABLE_THREAD 1 // Enables the Thread stack #define CHIP_DEVICE_CONFIG_ENABLE_WIFI 0 // CRITICAL: Disables the Wi-Fi stack // ------------------------------------- // --- For Matter over Wi-Fi only --- const char* ssid = "YOUR_SSID"; const char* password = "YOUR_PASSWORD"; // ------------------------------------ // Create an On/Off Light Endpoint MatterOnOffLight OnOffLight; // This callback function is executed when a Matter controller sends a command bool setLightOnOff(bool state) { Serial.printf("Received Matter command: Light %s\r\n", state ? "ON" : "OFF"); // Control the built-in LED (inverted logic: LOW is ON) digitalWrite(LED_BUILTIN, state ? LOW : HIGH); return true; // Return true to confirm the command was successful } void setup() { pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, HIGH); // Start with the LED off Serial.begin(115200); delay(1000); // --- For Matter over Wi-Fi only --- if (!CHIP_DEVICE_CONFIG_ENABLE_THREAD) { Serial.printf("Connecting to %s ", ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(" Connected"); } // ------------------------------------ // Initialize the OnOffLight endpoint with an initial state of OFF OnOffLight.begin(false); // Attach the callback function to handle state changes OnOffLight.onChange(setLightOnOff); // Start the Matter service. Matter.begin(); // If the device was already commissioned, sync its LED state on boot if (Matter.isDeviceCommissioned()) { Serial.println("Matter Node is already commissioned. Ready for use."); setLightOnOff(OnOffLight.getOnOff()); } } void loop() { // This block periodically prints the pairing information until the device is commissioned if (!Matter.isDeviceCommissioned()) { static unsigned long lastPrintTime = 0; if (millis() - lastPrintTime > 5000) { Serial.println("\n----------------------------------------------------"); Serial.println("Matter Node not commissioned. Waiting for pairing..."); Serial.printf("Manual pairing code: %s\r\n", Matter.getManualPairingCode().c_str()); Serial.println("---------------------------------------------------- "); lastPrintTime = millis(); } } // A small delay is needed to allow background tasks to run delay(100); } ``` -------------------------------- ### Start an App with Arduino App CLI Source: https://github.com/arduino/docs-content/blob/main/content/software/app-lab/7.cli/1.cli/apps-lab-cli.md Launch an application on the UNO Q board by providing its path to the `app start` command. ```sh arduino-app-cli app start "/home/arduino/ArduinoApps/test" ``` -------------------------------- ### Setup PWM and Get Temperature (Python) Source: https://github.com/arduino/docs-content/blob/main/content/hardware/04.pro/carriers/portenta-hat-carrier/tutorials/user-manual/content.md Automates the PWM setup and thermal temperature reading using Python. It configures the PWM channel and retrieves the device's temperature. ```python def setup_pwm(pwm_chip, pwm_channel, period, duty_cycle): base_path = f"/sys/class/pwm/pwmchip{pwm_chip}" # Export the PWM channel with open(f"{base_path}/export", "w") as f: f.write(str(pwm_channel)) # Set period with open(f"{base_path}/pwm{pwm_channel}/period", "w") as f: f.write(str(period)) # Set duty cycle with open(f"{base_path}/pwm{pwm_channel}/duty_cycle", "w") as f: f.write(str(duty_cycle)) # Enable the PWM channel with open(f"{base_path}/pwm{pwm_channel}/enable", "w") as f: f.write("1") def get_thermal_temperature(zone=0): with open(f"/sys/devices/virtual/thermal/thermal_zone{zone}/temp", "r") as f: return int(f.read().strip()) if __name__ == "__main__": # Set up PWM setup_pwm(0, 9, 100000, 50000) # 50% duty # Read and print thermal temperature temperature = get_thermal_temperature() print(f"Thermal Temperature (thermal_zone0): {temperature}") ``` -------------------------------- ### Initialize LEDs in Setup Function Source: https://github.com/arduino/docs-content/blob/main/content/hardware/04.pro/boards/portenta-h7/tutorials/usb-host/content.md Initialize the Red, Green, and Blue LEDs as outputs and set their initial state to HIGH (off) within the `setup()` function. This ensures the LEDs are in a known state when the sketch begins. ```cpp pinMode(LEDR, OUTPUT); pinMode(LEDG, OUTPUT); pinMode(LEDB, OUTPUT); //Turn off the LEDs digitalWrite(LEDR, HIGH); digitalWrite(LEDG, HIGH); digitalWrite(LEDB, HIGH); ``` -------------------------------- ### Basic LED Blink Example with Arduino Runtime Source: https://github.com/arduino/docs-content/blob/main/content/micropython/00.first-steps/03.runtime-package/runtime-package.md This example demonstrates the fundamental structure of an Arduino Runtime MicroPython program, including setup and loop functions for controlling an LED. ```python from arduino import * led = 'LED_BUILTIN' def setup(): print('starting my program') def loop(): print('loopy loop') digital_write(led, HIGH) delay(500) digital_write(led, LOW) delay(500) start(setup, loop) ``` -------------------------------- ### Initialize and Read All Analog Inputs on Opta Expansions Source: https://github.com/arduino/docs-content/blob/main/content/hardware/07.opta/opta-family/opta/tutorials/01.user-manual/content.md This example initializes all analog input channels on connected Opta expansions for voltage ADC readings and periodically reads their values. It includes helper functions to print expansion types and information. ```arduino #include "OptaBlue.h" #define PERIODIC_UPDATE_TIME 500 #define DELAY_AFTER_SETUP 5000 using namespace Opta; /* -------------------------------------------------------------------------- */ void printExpansionType(ExpansionType_t t) { /* -------------------------------------------------------------------------- */ if(t == EXPANSION_NOT_VALID) { Serial.print("Unknown!"); } else if(t == EXPANSION_OPTA_DIGITAL_MEC) { Serial.print("Opta --- DIGITAL [Mechanical] ---"); } else if(t == EXPANSION_OPTA_DIGITAL_STS) { Serial.print("Opta --- DIGITAL [Solid State] ---"); } else if(t == EXPANSION_DIGITAL_INVALID) { Serial.print("Opta --- DIGITAL [!!Invalid!!] ---"); } else if(t == EXPANSION_OPTA_ANALOG) { Serial.print("~~~ Opta ANALOG ~~~"); } else { Serial.print("Unknown!"); } } /* -------------------------------------------------------------------------- */ void printExpansionInfo() { /* -------------------------------------------------------------------------- */ static long int start = millis(); if(millis() - start > 5000) { start = millis(); Serial.print("Number of expansions: "); Serial.println(OptaController.getExpansionNum()); for(int i = 0; i < OptaController.getExpansionNum(); i++) { Serial.print("Expansion n. "); Serial.print(i); Serial.print(" type "); printExpansionType(OptaController.getExpansionType(i)); Serial.print(" I2C address "); Serial.println(OptaController.getExpansionI2Caddress(i)); } } } /* -------------------------------------------------------------------------- */ /* SETUP */ /* -------------------------------------------------------------------------- */ void setup() { /* -------------------------------------------------------------------------- */ Serial.begin(115200); delay(2000); OptaController.begin(); for(int i = 0; i < OptaController.getExpansionNum(); i++) { for(int k = 0; k < OA_AN_CHANNELS_NUM;k++){ /* all channels are initialized in the same way as VOLTAGE ADC */ AnalogExpansion::beginChannelAsAdc(OptaController, i, // the device k, // the output channel you are using OA_VOLTAGE_ADC, // adc type true, // enable pull down false, // disable rejection false, // disable diagnostic 0); // disable averaging } } } /* -------------------------------------------------------------------------- */ void optaAnalogTask() { /* -------------------------------------------------------------------------- */ static long int start = millis(); if(millis() - start > PERIODIC_UPDATE_TIME) { start = millis(); for(int i = 0; i < OptaController.getExpansionNum(); i++) { AnalogExpansion exp = OptaController.getExpansion(i); if(exp) { Serial.println("\nAnalog Expansion n. " + String(exp.getIndex())); ```