### Standard FileSystemStore Usage Example Source: https://github.com/armmbed/mbed-os/blob/master/storage/docs/FileSystemStore/FileSystemStore_design.md Demonstrates standard operations including initialization, setting, getting, updating, and removing key-value pairs. Also shows incremental writing and iterating over keys. ```C++ // External file system of LittleFS type. Should be initialized. extern LittleFileSystem fs; // Instantiate fsstore with our file system FileSystemStore fsstore(&fs); int res; // Initialize fsstore res = fsstore.init(); // Add "Key1" const char *val1 = "Value of key 1"; const char *val2 = "Updated value of key 1"; res = fsstore.set("Key1", val1, sizeof(val1), 0); // Update value of "Key1" res = fsstore.set("Key1", val2, sizeof(val2), 0); uint_8 value[32]; size_t actual_size; // Get value of "Key1". Value should return the updated value. res = fsstore.get("Key1", value, sizeof(value), &actual_size); // Remove "Key1" res = fsstore.remove("Key1"); // Incremental write, if need to generate large data with a small buffer const int data_size = 1024; char buf[8]; KVSTore::set_handle_t handle; res = fsstore.set_start(&handle, "Key2", data_size, 0); for (int i = 0; i < data_size / sizeof(buf); i++) { memset(buf, i, sizeof(buf)); res = fsstore.set_add_data(handle, buf, sizeof(buf)); } res = fsstore.set_finalize(handle); // Iterate over all keys starting with "Key" res = 0; KVSTore::iterator_t it; fsstore.iterator_open(&it, "Key*"); char key[KVSTore::KV_MAX_KEY_LENGTH]; while (!res) { res = fsstore.iterator_next(&it, key, sizeof(key)); } res = fsstore.iterator_close(&it); // Deinitialize FileSystemStore res = fsstore.deinit(); ``` -------------------------------- ### Serial Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt A basic example demonstrating the 'Hello World!' functionality using the Serial class in mbed-os. This is a common starting point for serial communication. ```c++ #include "mbed.h" int main() { Serial pc(USBTX, USBRX); pc.printf("Hello World!\r\n"); } ``` -------------------------------- ### Install and Configure inetd for Network Services Source: https://github.com/armmbed/mbed-os/blob/master/connectivity/netsocket/tests/TESTS/netsocket/README.md Example commands to install inetd and configure it to enable internal network services like discard, echo, chargen, daytime, and time over TCP6 and UDP6. ```bash $ sudo apt install inetutils-inetd $ nano /etc/inetd.conf ``` ```bash #:INTERNAL: Internal services discard stream tcp6 nowait root internal discard dgram udp6 wait root internal echo stream tcp6 nowait root internal echo dgram udp6 wait root internal chargen stream tcp6 nowait root internal chargen dgram udp6 wait root internal daytime stream tcp6 nowait root internal time stream tcp6 nowait root internal ``` -------------------------------- ### AnalogIn Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt A basic example demonstrating how to read an analog input pin. Ensure the pin is compatible with AnalogIn. ```cpp #include "mbed.h" // Entry point of the program int main() { // Create an AnalogIn object on pin A0 AnalogIn adc(A0); // Loop indefinitely while (true) { // Read the analog value (0.0 to 1.0) float value = adc.read(); // Print the value to the console printf("AnalogIn value: %.2f\n", value); // Wait for 1 second before the next reading Thread::wait(1000); } } ``` -------------------------------- ### Compile Mbed OS Example Source: https://github.com/armmbed/mbed-os/blob/master/docker_images/mbed-os-env/README.md Example commands to import, navigate to, and compile an Mbed OS example within the Docker container. Ensure you replace `` with your specific hardware target. ```bash mbed-tools import mbed-os-example-blinky cd mbed-os-example-blinky mbed-tools compile -m -t GCC_ARM ``` -------------------------------- ### Install and Configure Stunnel4 for TLS Network Services Source: https://github.com/armmbed/mbed-os/blob/master/connectivity/netsocket/tests/TESTS/netsocket/README.md Example commands to install stunnel4 and configure it for TLS-enabled network services. This is a prerequisite for using TLS versions of protocols like echo, discard, etc. ```bash $ sudo apt install stunnel4 $ nano /etc/stunnel/stunnel.conf ``` -------------------------------- ### Standard TDBStore Usage Example Source: https://github.com/armmbed/mbed-os/blob/master/storage/docs/TDBStore/TDBStore_design.md Demonstrates the typical workflow for using the TDBStore class, including initialization, setting, updating, getting, removing key-value pairs, performing incremental writes, iterating over keys, and deinitialization. Requires an underlying block device like SPIFBlockDevice. ```C++ // Underlying block device. Here, SPI Flash is fully used. // One can use SlicingBlockDevice if we want a partition. SPIFBlockDevice bd(PTE2, PTE4, PTE1, PTE5); // Instantiate tdbstore with our block device TDBStore tdbstore(&bd); int res; // Initialize tdbstore res = tdbstore.init(); // Add "Key1" const char *val1 = "Value of key 1"; const char *val2 = "Updated value of key 1"; res = tdbstore.set("Key1", val1, sizeof(val1), 0); // Update value of "Key1" res = tdbstore.set("Key1", val2, sizeof(val2), 0); uint_8 value[32]; size_t actual_size; // Get value of "Key1". Value should return the updated value. res = tdbstore.get("Key1", value, sizeof(value), &actual_size); // Remove "Key1" res = tdbstore.remove("Key1"); // Incremental write, if need to generate large data with a small buffer const int data_size = 1024; char buf[8]; KVSTore::set_handle_t handle; res = tdbstore.set_start(&handle, "Key2", data_size, 0); for (int i = 0; i < data_size / sizeof(buf); i++) { memset(buf, i, sizeof(buf)); res = tdbstore.set_add_data(handle, buf, sizeof(buf)); } res = tdbstore.set_finalize(handle); // Iterate over all keys starting with "Key" res = 0; KVSTore::iterator_t it; tdbstore.iterator_open(&it, "Key*"); char key[KVSTore::KV_MAX_KEY_LENGTH]; while (!res) { res = tdbstore.iterator_next(&it, key, sizeof(key)); } res = tdbstore.iterator_close(&it); // Deinitialize TDBStore res = tdbstore.deinit(); ``` -------------------------------- ### PortOut HelloWorld Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt Demonstrates the basic usage of the PortOut interface to control hardware GPIO ports. This example requires a device-specific PortNames.h file. ```C++ #include "mbed.h" int main() { PortOut port(PortName::Port0, 0xFF); // Set pins 0, 1, and 2 as output port = 0x07; // Turn on pins 0 and 1 port.write(0x03); // Turn off pin 0 port.clear(0x01); // Toggle pin 1 port.toggle(0x02); while (1) { // Loop indefinitely } } ``` -------------------------------- ### Ticker Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt This example demonstrates how to set up a Ticker to repeatedly invert an LED. It serves as a basic introduction to using the Ticker functionality. ```cpp #include "mbed.h" // Ticker object to generate periodic interrupts Ticker ticker; // LED object to blink DigitalOut led(LED1); // Function to be called by the ticker void tick() { led = !led; } int main() { // Set up the ticker to call the tick function every 0.2 seconds ticker.attach(&tick, 0.2); // The main thread can do other work or sleep while (1) { // You can add other tasks here Thread::wait(1000); } } ``` -------------------------------- ### Asynchronous Socket Handler Setup Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt This example demonstrates setting up an asynchronous handler for a TCP socket. It configures the socket for nonblocking operations and uses an event queue to manage the state machine for connecting, sending, and receiving data. ```C++ nsapi_size_or_error_t send_query(TCPSocket *socket) { return socket->send(QUERY, QUERY_LEN); } nsapi_size_or_error_t receive_data(TCPSocket *socket) { // Simplified example, does not properly handle streaming and appending to buffer return socket->recv(my_buffer, remaining_len); } void handle_socket_sigio(EventFlags *evt, TCPSocket *socket) { static enum { CONNECTING, SEND, RECEIVE, CLOSE, } next_state = CONNECTING; switch (next_state) { case CONNECTING: switch(socket->connect("api.ipify.org", 80)) { case NSAPI_ERROR_IN_PROGRESS: // Connecting to server break; case NSAPI_ERROR_ALREADY: // Now connected to server next_state = SEND; break; default: // Error in connection phase next_state = CLOSE; } case SEND: if (send_query(socket) > 0) next_state = RECEIVE; else next_state = CLOSE; // Error break; case RECEIVE: if (receive_data(socket) == NSAPI_ERROR_WOULD_BLOCK) break; next_state = CLOSE; break; case CLOSE: socket->close(); evt->set(1); // Signal the main thread break; } } int main() { EthernetInterface net; net.connect(); TCPSocket socket; socket.open(&net); EventFlags completed; EventQueue *queue = mbed_event_queue(); Event handler = queue->event(handle_socket_sigio, &completed, &socket); socket.set_blocking(false); socket.sigio(handler); handler(); // Kick the state machine to start connecting completed.wait_any(1); } ``` -------------------------------- ### AnalogOut Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt A basic example demonstrating the usage of the AnalogOut interface. Ensure the target board supports AnalogOut on the selected pins. ```cpp #include "mbed.h" AnalogOut aout(A0); int main() { aout.write(0.5f); // Set output to 50% of maximum voltage while(1) { wait(1.0); } } ``` -------------------------------- ### RawSerial Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt A basic "Hello, World!" example demonstrating the usage of the RawSerial class for serial communication. ```C++ #include "mbed.h" RawSerial pc(USBTX, USBRX); int main() { pc.printf("Hello World!\n\r"); } ``` -------------------------------- ### Install and Configure Lighttpd Server Source: https://github.com/armmbed/mbed-os/blob/master/connectivity/netsocket/tests/TESTS/netsocket/README.md Steps to install the lighttpd web server and prepare its document root for use with certbot. ```sh sudo apt-get install lighttpd sudo rm -rf /var/www/html/* sudo echo "

Empty

" > /var/www/html/index.html sudo echo "" >> /var/www/html/index.html sudo chown www-data:www-data /var/www/html/index.html sudo systemctl restart lighttpd.service ``` -------------------------------- ### Run Mbed OS Test Example Source: https://github.com/armmbed/mbed-os/blob/master/docker_images/mbed-os-env/README.md Example commands to import Mbed OS, navigate to the source directory, and run tests on a connected target. Replace `` with your specific hardware target. ```bash mbed import mbed-os cd mbed-os mbed test -t GCC_ARM -m ``` -------------------------------- ### Install and Set Up Certbot for Certificate Management Source: https://github.com/armmbed/mbed-os/blob/master/connectivity/netsocket/tests/TESTS/netsocket/README.md Instructions for installing certbot and obtaining an SSL certificate for a specified domain. ```sh sudo apt-get update sudo apt-get install software-properties-common sudo add-apt-repository ppa:certbot/certbot sudo apt-get update sudo apt-get install certbot sudo certbot certonly sudo certbot certonly --webroot -w /var/www/html -d ``` -------------------------------- ### BusIn Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt A simple example showcasing the BusIn interface for reading multiple digital input pins at once. The order of pins in the constructor is reversed for bit ordering. ```cpp #include "mbed.h" BusIn bus(D0, D1, D2, D3, D4, D5, D6, D7); int main() { while(1) { if (bus.read() == 0xFF) { // All pins are high } else { // Some pins are low } wait(0.1f); } } ``` -------------------------------- ### Clone Mbed OS Examples Source: https://github.com/armmbed/mbed-os/blob/master/tools/test/examples/README.md Clone the examples repository. The -e option can filter for a specific example. ```python python mbed-os/tools/test/examples/examples.py clone ``` -------------------------------- ### PwmOut HelloWorld Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt This example demonstrates controlling a PWM signal using the PwmOut interface with default period settings. It ramps the duty cycle from 0% to 100%. ```C++ #include "mbed.h" PwmOut pwm(LED1); int main() { // Default period is 0.020s while (1) { for (float duty = 0.0f; duty <= 1.0f; duty += 0.1f) { pwm.write(duty); wait(0.2f); } } } ``` -------------------------------- ### GattServer Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt This example demonstrates how to set up and use the GattServer for Bluetooth Low Energy communication. It shows how to add services and characteristics, and handle client interactions. ```C++ #include "mbed.h" #include "ble/BLE.h" #include "GattServer.h" // Example service and characteristic UUIDs const UUID SERVICE_UUID = UUID("180D"); // Heart Rate Service const UUID CHARACTERISTIC_UUID = UUID("2A37"); // Heart Rate Measurement GattServer *server; void onDataSent(void) { // Callback for when data is sent to a client printf("Data sent to client.\n"); } void onDataWriten(const GattWriteOperation &writeOperation) { // Callback for when a client writes data printf("Client wrote data to handle %d.\n", writeOperation.handle); // You can access the written data via writeOperation.data } void onDataRead(const GattReadOperation &readOperation) { // Callback for when a client reads data printf("Client read data from handle %d.\n", readOperation.handle); // You can set the data to be read via readOperation.data } void onUpdatesEnabled(const GattAttribute &attribute) { // Callback for when a client subscribes to updates printf("Client subscribed to updates for characteristic with handle %d.\n", attribute.getHandle()); } void onUpdatesDisabled(const GattAttribute &attribute) { // Callback for when a client unsubscribes from updates printf("Client unsubscribed from updates for characteristic with handle %d.\n", attribute.getHandle()); } void onConfirmationReceived(const GattAttribute &attribute) { // Callback for when a client acknowledges a notification printf("Confirmation received for characteristic with handle %d.\n", attribute.getHandle()); } int main() { server = new GattServer(); // Register event handlers server->onDataSent(onDataSent); server->onDataWriten(onDataWriten); server->onDataRead(onDataRead); server->onUpdatesEnabled(onUpdatesEnabled); server->onUpdatesDisabled(onUpdatesDisabled); server->onConfirmationReceived(onConfirmationReceived); // Create a GattService GattService service(SERVICE_UUID); // Create a GattCharacteristic // Properties: READ | WRITE | NOTIFY GattCharacteristic characteristic(CHARACTERISTIC_UUID, NULL, 1, 10, GattCharacteristic::Properties_t( GattCharacteristic::READ | GattCharacteristic::WRITE | GattCharacteristic::NOTIFY )); // Add the characteristic to the service service.addCharacteristic(characteristic); // Add the service to the GattServer server->addService(service); // Initialize BLE and start the server BLE &ble = BLE::Instance(); ble.init(); ble.gap().setDeviceName("mbed-gatt-server"); ble.startAdvertising(); printf("GattServer started. Waiting for connections...\n"); while (true) { // Main loop, can be used for other tasks Thread::yield(); } return 0; } ``` -------------------------------- ### LittleFS Example: Boot Count Update Source: https://github.com/armmbed/mbed-os/blob/master/storage/filesystem/littlefs/littlefs/README.md This example demonstrates how to mount, format (if necessary), read, write, and close a file in LittleFS. It updates a boot count, ensuring data persistence across power cycles. The filesystem remains in a valid state even if interrupted. ```c #include "lfs.h" // variables used by the filesystem lfs_t lfs; lfs_file_t file; // configuration of the filesystem is provided by this struct const struct lfs_config cfg = { // block device operations .read = user_provided_block_device_read, .prog = user_provided_block_device_prog, .erase = user_provided_block_device_erase, .sync = user_provided_block_device_sync, // block device configuration .read_size = 16, .prog_size = 16, .block_size = 4096, .block_count = 128, .lookahead = 128, }; // entry point int main(void) { // mount the filesystem int err = lfs_mount(&lfs, &cfg); // reformat if we can't mount the filesystem // this should only happen on the first boot if (err) { lfs_format(&lfs, &cfg); lfs_mount(&lfs, &cfg); } // read current count uint32_t boot_count = 0; lfs_file_open(&lfs, &file, "boot_count", LFS_O_RDWR | LFS_O_CREAT); lfs_file_read(&lfs, &file, &boot_count, sizeof(boot_count)); // update boot count boot_count += 1; lfs_file_rewind(&lfs, &file); lfs_file_write(&lfs, &file, &boot_count, sizeof(boot_count)); // remember the storage is not updated until the file is closed successfully lfs_file_close(&lfs, &file); // release any resources we were using lfs_unmount(&lfs); // print the boot count printf("boot_count: %d\n", boot_count); } ``` -------------------------------- ### GCC Compiler Linker Script Example Source: https://github.com/armmbed/mbed-os/blob/master/targets/TARGET_Cypress/TARGET_PSOC6/psoc6cm0p/COMPONENT_CM0P_CRYPTO/README.md Example of setting FLASH_CM0P_SIZE for the GCC compiler in the linker script. ```c Example for the GCC compiler: ... /* The size and start addresses of the Cortex-M0+ application image */ FLASH_CM0P_SIZE = 0xA000; ... ``` -------------------------------- ### SPI Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt This example demonstrates a basic SPI communication. It uses the WHOAMI register to interact with a slave device, with Mbed OS acting as the SPI master and DigitalOut managing the slave chip select. ```cpp #include "mbed.h" // Pin definitions for SPI #define SPI_MOSI MBED_CONF_SPI_MOSI #define SPI_MISO MBED_CONF_SPI_MISO #define SPI_SCLK MBED_CONF_SPI_SCLK #define SPI_CS MBED_CONF_SPI_CS // Create an SPI object SPI spi(SPI_MOSI, SPI_MISO, SPI_SCLK); // Create a DigitalOut object for Slave Select (CS) DigitalOut cs(SPI_CS); int main() { // Initialize the SPI interface with default settings (1MHz, 8-bit, Mode 0) // You can also configure frequency and format: // spi.frequency(1000000); // spi.format(8, 0); // Set the slave select pin high (inactive) cs = 1; // Write and read data from the SPI slave // In this example, we write 0x9F to the slave and read the response. // The WHOAMI register is often read to identify the slave device. cs = 0; // Activate the slave select pin spi.write(0x9F); // Send a command/address to the slave char response = spi.write(0x00); // Send dummy data to clock out the response cs = 1; // Deactivate the slave select pin // Print the received response printf("WHOAMI response: 0x%02X\n", response); return 0; } ``` -------------------------------- ### ARM Compiler 6 Linker Script Example Source: https://github.com/armmbed/mbed-os/blob/master/targets/TARGET_Cypress/TARGET_PSOC6/psoc6cm0p/COMPONENT_CM0P_CRYPTO/README.md Example of setting FLASH_CM0P_SIZE for the ARM Compiler 6 in the linker script. ```c Example for ARMC6 compiler: ... /* The size and start addresses of the Cortex-M0+ application image */ #define FLASH_CM0P_SIZE 0xA000 ... ``` -------------------------------- ### GattClient Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt Example demonstrating the usage of the GattClient for BLE interactions. This snippet requires the mbed-os-example-ble-GattClient library. ```cpp #include "mbed.h" #include "ble/BLE.h" #include "gatt_client.h" // Example usage of GattClient (specific code not provided in source) // This is a placeholder for the actual example code found at the provided URL. // The actual code would demonstrate discovery, read/write operations, and event handling. int main() { // Initialization and GattClient usage would go here return 0; } ``` -------------------------------- ### Install Python Requirements Source: https://github.com/armmbed/mbed-os/blob/master/drivers/usb/tests/TESTS/usb_device/README.md Installs all required Python modules for testing using a top-level requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### LittleFS Superblock Example Source: https://github.com/armmbed/mbed-os/blob/master/storage/filesystem/littlefs/littlefs/SPEC.md Provides a concrete example of a complete LittleFS superblock, showing the values for each field and its byte-level representation. ```text (32 bits) revision count = 3 (0x00000003) (32 bits) dir size = 52 bytes, end of dir (0x00000034) (64 bits) tail pointer = 3, 2 (0x00000003, 0x00000002) (8 bits) entry type = superblock (0x2e) (8 bits) entry length = 20 bytes (0x14) (8 bits) attribute length = 0 bytes (0x00) (8 bits) name length = 8 bytes (0x08) (64 bits) root directory = 3, 2 (0x00000003, 0x00000002) (32 bits) block size = 512 bytes (0x00000200) (32 bits) block count = 1024 blocks (0x00000400) (32 bits) version = 1.1 (0x00010001) (8 bytes) magic string = littlefs (32 bits) CRC = 0xc50b74fa 00000000: 03 00 00 00 34 00 00 00 03 00 00 00 02 00 00 00 ....4........... 00000010: 2e 14 00 08 03 00 00 00 02 00 00 00 00 02 00 00 ................ 00000020: 00 04 00 00 01 00 01 00 6c 69 74 74 6c 65 66 73 ........littlefs 00000030: fa 74 0b c5 .t.. ``` -------------------------------- ### LittleFS Example File Entry on Disk Source: https://github.com/armmbed/mbed-os/blob/master/storage/filesystem/littlefs/littlefs/SPEC.md Illustrates a concrete example of a file entry as it appears on disk, showing the byte values for type, length, attributes, name length, entry data, and the entry name. ```text (8 bits) entry type = file (0x11) (8 bits) entry length = 8 bytes (0x08) (8 bits) attribute length = 0 bytes (0x00) (8 bits) name length = 12 bytes (0x0c) (8 bytes) entry data = 05 00 00 00 20 00 00 00 (12 bytes) entry name = smallavacado 00000000: 11 08 00 0c 05 00 00 00 20 00 00 00 73 6d 61 6c ........ ...smal 00000010: 6c 61 76 61 63 61 64 6f lavacado ``` -------------------------------- ### Mbed OS Wi-Fi Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt This example demonstrates scanning for Wi-Fi access points using Mbed OS. It highlights the use of specific Wi-Fi interface drivers like ESP8266Interface and OdinWiFiInterface. ```cpp #include "mbed.h" #include "netsocket/NetworkInterface.h" #include "ESP8266Interface.h" // Example driver // Define the network interface to use. This might be ESP8266Interface, OdinWiFiInterface, etc. // For this example, we'll assume ESP8266Interface is available and configured. // extern WiFiInterface *wifi_ptr; int main() { // Obtain a default network interface instance. This might be configured via mbed_lib.json NetworkInterface *net = NetworkInterface::get_default_instance(); if (!net) { printf("Network interface not found.\n"); return -1; } // Connect to the Wi-Fi network // Replace with your SSID and password, and appropriate security mode const char* ssid = "YOUR_SSID"; const char* password = "YOUR_PASSWORD"; nsapi_error_t connect_result = net->connect(ssid, password, NSAPI_SECURITY_WPA_WPA2); if (connect_result == NSAPI_ERROR_OK) { printf("Successfully connected to Wi-Fi network '%s'.\n", ssid); // Get network information SocketAddress ip_addr; net->get_ip_address(&ip_addr); printf("IP Address: %s\n", ip_addr.get_ip_address()); // You can now use the network interface for socket operations // For example, opening a TCP or UDP socket. // Disconnect from the network when done net->disconnect(); printf("Disconnected from Wi-Fi network.\n"); } else { printf("Failed to connect to Wi-Fi network '%s'. Error code: %d\n", ssid, connect_result); // Handle specific errors based on NSAPI_ERROR codes if needed // For example: // if (connect_result == NSAPI_ERROR_AUTH_FAILURE) { // printf("Authentication failure. Check your password.\n"); // } } return 0; } ``` -------------------------------- ### Wi-Fi Interface Example Source: https://github.com/armmbed/mbed-os/blob/master/connectivity/drivers/emac/README.md Demonstrates how a Wi-Fi driver can expose its EMAC for testing purposes. The constructor must accept an OnboardNetworkStack. ```c++ MyWiFiInterface net; net.set_credentials(); EMAC &emac = net.get_emac(); do_emac_test(emac); ``` ```c++ MyWiFiInterface(OnboardNetworkStack &stack = OnboardNetworkStack::get_default_instance()); ``` -------------------------------- ### General Socket Usage Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt This example demonstrates the typical application flow for using sockets, including initializing a network interface, creating a socket, connecting, sending data, receiving data, and closing the socket. ```APIDOC ## General use The following steps describe the typical application flow: 1. Initialize a network interface. 2. Create a socket. 3. Connect (optional step for datagram protocols). 4. Send data. 5. Receive data. 6. Close the socket. The following code demonstrates those steps by sending an HTTP query to a server: ```cpp // Initialize network interface EthernetInterface eth; eth.connect(); // Create a socket TCPSocket sock; sock.open(ð); // Connect sock.connect("arm.com", 80); // Send data char buf[100]; sock.send("GET / HTTP/1.0\r\n\r\n", 18); // Receive data sock.recv(buf, 100); // Close the socket sock.close(); ``` ``` -------------------------------- ### Deploy Dependency Libraries Source: https://github.com/armmbed/mbed-os/blob/master/tools/test/examples/README.md Deploy necessary dependency libraries for the examples. ```python python mbed-os/tools/test/examples/examples.py deploy ``` -------------------------------- ### CAN Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt Sends a counter on one CAN bus and listens on another. Requires CAN bus transceivers connected together. ```cpp #include "mbed.h" CAN can1(PA_12, PA_11); // CAN TX, CAN RX CAN can2(PB_13, PB_12); // CAN TX, CAN RX int main() { char counter = 0; while (1) { // Send a message on can1 CANMessage tx_msg(0x123, &counter, 1); if (can1.write(tx_msg) != 0) { printf("Message sent on can1: %d\n\r", counter); } // Check for messages on can2 CANMessage rx_msg; if (can2.read(rx_msg)) { printf("Message received on can2: %d\n\r", rx_msg.data[0]); } counter++; wait(1.0); } } ``` -------------------------------- ### Cordio BLE HCI Driver Implementation Example Source: https://github.com/armmbed/mbed-os/blob/master/connectivity/FEATURE_BLE/include/ble/driver/doc/PortingGuide.md An example implementation of the function that returns a reference to the HCI driver. It shows how to initialize the transport and HCI drivers. ```c++ ble::CordioHCIDriver& ble_cordio_get_hci_driver() { static ble::vendor::target_name::TransportDriver transport_driver( /* transport parameters */ ); static ble::vendor::target_name::HCIDriver hci_driver( transport_driver, /* other hci driver parameters */ ); return hci_driver; } ``` -------------------------------- ### InterruptIn Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt A basic example demonstrating the usage of the InterruptIn class to handle interrupts. This snippet serves as a starting point for interrupt-driven applications. ```C++ #include "mbed.h" InterruptIn button(USER_BUTTON); DigitalOut led(LED1); void toggle_led() { led = !led; } int main() { button.rise(&toggle_led); button.fall(&toggle_led); while (1) { // Main loop can do other tasks Thread::wait(1000); } } ``` -------------------------------- ### PortInOut Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt Illustrates how to use the PortInOut interface for reading and writing to a GPIO port. This is faster than BusInOut but less flexible. ```cpp #include "mbed.h" int main() { PortInOut port(PortName::Port0); // Set a mask to use specific pins (e.g., pins 0-3) port.input(0x0F); // Sets pins 0, 1, 2, 3 as input port.output(0xF0); // Sets pins 4, 5, 6, 7 as output // Write a value to the output pins port.write(0xA0); // Writes 1010 to pins 4-7 // Read the value from the input pins int input_value = port.read() & 0x0F; // Reads pins 0-3 // Example: Toggle output pins based on input // while(1) { // if (port.read() & 0x0F) { // port.write(0x50); // } else { // port.write(0xA0); // } // } } ``` -------------------------------- ### PPP Notify Phase Callback Example Source: https://github.com/armmbed/mbed-os/blob/master/connectivity/lwipstack/lwip/doc/ppp.txt An example callback function that reacts to different PPP session phases by controlling an LED. This allows for visual feedback on the PPP connection's status. ```c static void ppp_notify_phase_cb(ppp_pcb *pcb, u8_t phase, void *ctx) { switch (phase) { /* Session is down (either permanently or briefly) */ case PPP_PHASE_DEAD: led_set(PPP_LED, LED_OFF); break; /* We are between two sessions */ case PPP_PHASE_HOLDOFF: led_set(PPP_LED, LED_SLOW_BLINK); break; /* Session just started */ case PPP_PHASE_INITIALIZE: led_set(PPP_LED, LED_FAST_BLINK); break; /* Session is running */ case PPP_PHASE_RUNNING: led_set(PPP_LED, LED_ON); break; default: break; } } ``` -------------------------------- ### MQTT Client Initialization and Connection Source: https://github.com/armmbed/mbed-os/blob/master/connectivity/lwipstack/lwip/doc/mqtt_client.txt Demonstrates static and dynamic memory allocation for the MQTT client and initiating a connection to the MQTT server. Ensure the `example_do_connect` function is implemented to handle the connection logic. ```c mqtt_client_t static_client; example_do_connect(&static_client); ``` ```c mqtt_client_t *client = mqtt_client_new(); if(client != NULL) { example_do_connect(&client); } ``` -------------------------------- ### DigitalIn Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt Reads the state of a digital input pin. Any numbered Arm Mbed pin can be used. ```cpp #include "mbed.h" DigitalIn button(USER_BUTTON); int main() { while (1) { if (button.read() == 0) { printf("Button pressed!\n\r"); } else { printf("Button not pressed\n\r"); } wait(0.2); } } ``` -------------------------------- ### Build and Install TF-M Source: https://github.com/armmbed/mbed-os/blob/master/targets/TARGET_NUVOTON/TARGET_M2354/TARGET_TFM/TARGET_NU_M2354/COMPONENT_TFM_S_FW/README.md After configuring with CMake, use this command to build the TF-M project and install the necessary output files. This command assumes a Unix-like environment with Make. ```bash cmake --build cmake_build --install ``` -------------------------------- ### PwmOut Example: Set Period and Duty Cycle Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt This example sets the PWM period in seconds and the duty cycle as a relative percentage of the period. It blinks an LED over a four-second cycle. ```C++ #include "mbed.h" PwmOut pwm(LED2); int main() { // Set period to 4 seconds pwm.period(4.0); // Set duty cycle to 50% of the period pwm.write(0.5); while (1) { // LED will be on for 2 seconds and off for 2 seconds } } ``` -------------------------------- ### Asynchronous DNS Host Name Resolution Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt This example demonstrates how to perform an asynchronous DNS host name resolution using the mbed OS DNS API. It shows the setup for the network interface and the call to resolve a host name asynchronously. ```C++ #include "mbed.h" #include "netsocket/nsapi_dns.h" // Network interface static EthernetInterface eth; // Callback for asynchronous DNS resolution void dns_callback(nsapi_dns_error_t err, const SocketAddress &address) { if (err == NSAPI_ERROR_OK) { printf("DNS resolved to: %s\n", address.get_ip_address() ? address.get_ip_address() : ""); } else { printf("DNS resolution failed: %d\n", err); } } int main() { // Connect to the network eth.connect(); // Resolve a host name asynchronously nsapi_dns_error_t err = nsapi_dns_gethostbyname("example.com", dns_callback, NSAPI_HOST_PROBE_ALL); if (err != NSAPI_ERROR_IN_PROGRESS) { printf("Failed to start asynchronous DNS resolution: %d\n", err); } // Keep the program running to allow the callback to be invoked while (true) { Thread::wait(1000); } } ``` -------------------------------- ### Get Cellular Interface Instance Source: https://github.com/armmbed/mbed-os/blob/master/connectivity/docs/Multihoming - Design document.md Manually constructs and connects a cellular interface instance using EasyCellularConnection. This allows for explicit cellular network setup. ```cpp NetworkInterface *cellular_net; cellular_net = EasyCellularConnection::get_target_default_instance(); cellular_net->connect(); ``` -------------------------------- ### PortIn Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt Demonstrates the basic usage of the PortIn interface. Ensure the port name is defined in your device's PortNames.h. ```cpp #include "mbed.h" int main() { PortIn port(PortName::Port0); // Read the value of the port int value = port.read(); // You can also read individual pins // int pin_value = port.read() & (1 << pin_number); // Example: Toggle an LED based on port value (assuming LED1 is connected) // while(1) { // if (port.read()) { // led1 = 1; // } else { // led1 = 0; // } // } } ``` -------------------------------- ### Get Default Network Interface and Connect Source: https://github.com/armmbed/mbed-os/blob/master/connectivity/docs/Multihoming - Design document.md This snippet shows how to obtain the default network interface instance and initiate a connection. It's a common starting point for network operations. ```C++ NetworkInterface *net; net = NetworkInterface::get_default_instance(); net->connect(); ``` -------------------------------- ### Using Default Handlers in Specification Source: https://github.com/armmbed/mbed-os/blob/master/features/frameworks/utest/README.md Demonstrates how to specify default handlers for a test specification. This example sets up a custom test setup handler and configures the specification to use the 'greentea continue' behavior for handling test failures. ```cpp Specification specification(greentea_setup, cases, greentea_continue_handlers); ``` -------------------------------- ### BusInOut Hello World Example Source: https://github.com/armmbed/mbed-os/blob/master/TESTS/integration/COMMON/sample.txt Demonstrates the basic usage of the BusInOut interface for bidirectional communication with multiple pins. Ensure pins are capable of digital input and output. ```cpp #include "mbed.h" // Example: Use pins A0-A7 as a BusInOut BusInOut my_bus_io(A0, A1, A2, A3, A4, A5, A6, A7); int main() { // Set the bus as output and write a value my_bus_io.output(); my_bus_io.write(0x55); // Write binary 01010101 // Read the value from the bus int read_value = my_bus_io.read(); printf("Read value: 0x%X\n", read_value); // Set the bus as input my_bus_io.input(); // Example of reading individual bits (assuming A0 is bit 0, A1 is bit 1, etc.) // Note: The order in constructor is reversed for bit order in byte. // If BusInOut(a,b,c,d,e,f,g,h), then bits are hgfedcba. // So, A0 is bit 0, A1 is bit 1, ..., A7 is bit 7. if (my_bus_io[0].read() == 1) { printf("Pin A0 is HIGH\n"); } // Example of writing individual bits my_bus_io[1] = 1; // Set A1 to HIGH my_bus_io[2] = 0; // Set A2 to LOW return 0; } ``` -------------------------------- ### Basic File System Usage Example Source: https://github.com/armmbed/mbed-os/blob/master/storage/filesystem/littlefsv2/README.md Demonstrates mounting, reading, writing, and unmounting a file in the littlefs. It includes error handling for mounting and file creation, and ensures data is flushed by closing the file. ```c++ #include "LittleFileSystem2.h" #include "SPIFBlockDevice.h" // Physical block device, can be any device that supports the BlockDevice API SPIFBlockDevice bd(PTE2, PTE4, PTE1, PTE5); // Storage for the littlefs LittleFileSystem2 fs("fs"); // Entry point int main() { // Mount the filesystem int err = fs.mount(&bd); if (err) { // Reformat if we can't mount the filesystem, // this should only happen on the first boot LittleFileSystem2::format(&bd); fs.mount(&bd); } // Read the boot count uint32_t boot_count = 0; FILE *f = fopen("/fs/boot_count", "r+"); if (!f) { // Create the file if it doesn't exist f = fopen("/fs/boot_count", "w+"); } fread(&boot_count, sizeof(boot_count), 1, f); // Update the boot count boot_count += 1; rewind(f); fwrite(&boot_count, sizeof(boot_count), 1, f); // Remember that storage may not be updated until the file // is closed successfully fclose(f); // Release any resources we were using fs.unmount(); // Print the boot count printf("boot_count: %ld\n", boot_count); } ``` -------------------------------- ### Example Compilation Result Table Source: https://github.com/armmbed/mbed-os/blob/master/tools/test/examples/README.md This table displays the results of the example compilation tests, indicating success or failure for each example and target. ```text Passed example compilation: +---------------------------------+"--------"+"----------"+"----------"+"--------------"+ | EXAMPLE NAME |" TARGET "|" TOOLCHAIN "|" TEST GEN "|" BUILD RESULT "| +---------------------------------+"--------"+"----------"+"----------"+"--------------"+ | mbed-os-example-kvstore |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| | mbed-os-example-tls-socket |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| | mbed-os-example-blockdevice |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| | mbed-os-example-wifi |" K64F "|" GCC_ARM "|" TEST_OFF "|" PASSED "| | mbed-os-example-error-handling |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| | mbed-os-example-sd-driver |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| | mbed-os-example-crash-reporting |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| | mbed-os-example-filesystem |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| | mbed-os-example-blinky |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| | mbed-os-example-cpu-stats |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| | mbed-os-example-sys-info |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| | mbed-os-example-attestation |" K64F "|" GCC_ARM "|" TEST_ON "|" PASSED "| +---------------------------------+"--------"+"----------"+"----------"+"--------------"+ Number of failures = 0 ``` -------------------------------- ### Standard SecureStore Class Usage Source: https://github.com/armmbed/mbed-os/blob/master/storage/docs/SecureStore/SecureStore_design.md Demonstrates the typical workflow for using the SecureStore class, including initialization, setting, updating, retrieving, and removing key-value pairs. It also shows how to perform incremental writes for large data and iterate over keys. ```C++ // Underlying key value store - here TDBStore (should be instantiated and initialized) extern TDBStore tdbstore; // Rollback protect store - also of TDBStore type (should be instantiated and initialized) extern TDBStore rbp_tdbstore; // Instantiate SecureStore with tdbstore as underlying key value store and rbp_tdbstore as RBP storage SecureStore secure_store(&tdbstore, &rbp_tdbstore); int res; // Initialize secure_store res = secure_store.init(); const char *val1 = "Value of key 1"; const char *val2 = "Updated value of key 1"; // Add "Key1" with encryption flag res = secure_store.set("Key1", val1, sizeof(val1), KVSTore::REQUIRE_CONFIDENTIALITY_FLAG); // Update value of "Key1" (flags must be the same per key) res = secure_store.set("Key1", val2, sizeof(val2), KVSTore::REQUIRE_CONFIDENTIALITY_FLAG); uint_8 value[32]; size_t actual_size; // Get value of "Key1". Value should return the updated value. res = secure_store.get("Key1", value, sizeof(value), &actual_size); // Remove "Key1" res = secure_store.remove("Key1"); // Incremental write, if need to generate large data with a small buffer const int data_size = 1024; char buf[8]; KVSTore::set_handle_t handle; res = secure_store.set_start(&handle, "Key2", data_size, 0); for (int i = 0; i < data_size / sizeof(buf); i++) { memset(buf, i, sizeof(buf)); res = secure_store.set_add_data(handle, buf, sizeof(buf)); } res = secure_store.set_finalize(handle); // Iterate over all keys starting with "Key" res = 0; KVSTore::iterator_t it; secure_store.iterator_open(&it, "Key*"); char key[KVSTore::KV_MAX_KEY_LENGTH]; while (!res) { res = secure_store.iterator_next(&it, key, sizeof(key)e); } res = secure_store.iterator_close(&it); // Deinitialize SecureStore res = secure_store.deinit(); ``` -------------------------------- ### IAR Compiler Linker Script Example Source: https://github.com/armmbed/mbed-os/blob/master/targets/TARGET_Cypress/TARGET_PSOC6/psoc6cm0p/COMPONENT_CM0P_CRYPTO/README.md Example of setting FLASH_CM0P_SIZE for the IAR compiler in the linker script. ```c Example for the IAR compiler: ... /* The size and start addresses of the Cortex-M0+ application image */ define symbol FLASH_CM0P_SIZE = 0xA000; ... ```