diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-buttons/tutorials/how-buttons-ardu/how-to-buttons-ardu.md b/content/hardware/11.accessories/modulino-nodes/modulino-buttons/tutorials/how-buttons-ardu/how-to-buttons-ardu.md index 1ff1957351..052df4e5c8 100644 --- a/content/hardware/11.accessories/modulino-nodes/modulino-buttons/tutorials/how-buttons-ardu/how-to-buttons-ardu.md +++ b/content/hardware/11.accessories/modulino-nodes/modulino-buttons/tutorials/how-buttons-ardu/how-to-buttons-ardu.md @@ -1,8 +1,11 @@ --- -title: "How To Use The Modulino Buttons" -description: "Learn how to get the most out of your Modulino Buttons." +title: "Modulino Buttons" +description: "Complete guide for the Modulino Buttons tactile input and LED feedback module." tags: - Modulino + - Buttons + - Input + - LED - QWIIC - I2C author: 'Pedro Sousa Lima' @@ -11,20 +14,18 @@ hardware: software: - ide-v2 - web-editor + - micropython --- -The Modulino Buttons is a modular sensor that provides tactile input and visual feedback, making it perfect to add interactive controls to your projects! -The Modulino form factor is shaped with two QWIIC connectors and the I²C protocol integration, allowing the connection and programming of multiple Modulino nodes in a very simple way. In addition to the QWIIC's connectors, the Modulino nodes also expose solderable pins that can be used in multiple ways and make them compatible with boards that are not QWIIC compatible. +![Buttons Overview](assets/connection-guide-buttons.gif) +The Modulino Buttons is a modular sensor that provides tactile input and visual feedback, making it perfect to add interactive controls to your projects! Pressing a button pulls the signal LOW, and each button has an onboard pull-up resistor. The LEDs can be controlled independently through the onboard microcontroller. -![Module demonstration](assets/connection-guide-buttons.gif) +## Hardware Overview -Pressing a button pulls the signal LOW, and each button has an onboard pull-up resistor. The LEDs can be controlled independently through the onboard microcontroller. +### General Characteristics - -## General Characteristics - -The **Modulino Buttons** module uses three tactile buttons and LEDs, which do not have native I²C capabilities. Instead, the buttons and LEDs are controlled by the Modulino's onboard microcontroller (STM32C011F4U6TR). This microcontroller provides I²C communication, allowing for flexible reading of button states and control of the LEDs. One unique feature of this setup is the ability to change the I²C address via software. This means the address can be modified based on your application needs, making it adaptable to different system configurations. +The **Modulino Buttons** module uses three tactile buttons and LEDs, controlled by the Modulino's onboard microcontroller (STM32C011F4U6TR). This microcontroller provides I²C communication, allowing for flexible reading of button states and control of the LEDs. | Specification | Details | |-------------------|-----------------------------| @@ -34,6 +35,7 @@ The **Modulino Buttons** module uses three tactile buttons and LEDs, which do no | Interface | UART, SWD, I2C | | Pull-up Resistors | Integrated on button inputs | +One unique feature of this setup is the ability to change the I²C address via software, making it adaptable to different system configurations. The default I²C address for the **Modulino Buttons** module is: @@ -41,17 +43,11 @@ The default I²C address for the **Modulino Buttons** module is: |----------------------|----------------------|-------------------------------------------------| | 0x7C | 0x3E | Any custom address (via software configuration) | -When scanning for I²C address on the bus, you might find the modulino using the **Hardware I²C Address**. However, you should always use the **Modulino I²C Address** when using the official Modulino library. - -Later in this article we teach how to [change the address](#how-to-change-i2c-address). - -## Pinout - -The tactile buttons and LEDs are the core components of this module. These input and output devices are controlled by an onboard STM32 microcontroller, which supports digital communication (I²C), meaning it connects directly to the I²C bus on the module without requiring additional conversion circuitry. +### Pinout ![Arduino Buttons Pinout](assets/ButtonsPinouts.png) -### 1x10 Header +#### 1x10 Header | Pin | Function | |-------|----------------| @@ -66,20 +62,7 @@ The tactile buttons and LEDs are the core components of this module. These input | B | Button B | | C | Button C | -- **A: Button A** – This pin connects directly to button A. -- **GND: Ground** – Ground connection for power and signal reference. -- **3V3: Power** – 3.3 V power supply input. -- **PF2: RESET** – The reset pin for the microcontroller, which can be used to reset the system. -- **SWCLK: SWD Clock** – Used for providing the clock signal in the SWD interface. -- **SWDIO: SWD Data** – Used for debugging, as part of the Serial Wire Debug (SWD) interface. -- **TX1: USART Transmit** – Used for transmitting data over UART communication. -- **RX1: USART Receive** – Used for receiving data over UART communication. -- **B: Button B** – This pin connects directly to button B. -- **C: Button C** – This pin connects directly to button C. - -### 1x4 Header (I2C) - -The pinout for the Modulino Buttons is shown below. While the recommended connection method is via the QWIIC connectors, this solderable header provides a connection option when using the modulino with a non-QWIIC compatible board. +#### 1x4 Header (I2C) | Pin | Function | |-------|--------------| @@ -88,22 +71,18 @@ The pinout for the Modulino Buttons is shown below. While the recommended connec | SDA | I²C Data | | SCL | I²C Clock | -## Power Specifications +### Power Specifications -The board is typically powered by +3.3 VDC when using the QWIIC interface as per the I²C standard. - -| Parameter | Condition | Minimum | Typical | Maximum | Unit | -|------------------|-------------------|---------|-------------|---------|------| -| Supply Voltage | - | - | 3.3 (QWIIC) | - | V | +| Parameter | Condition | Minimum | Typical | Maximum | Unit | +|------------------|------------------------------|---------|-------------|---------|------| +| Supply Voltage | - | - | 3.3 (QWIIC) | - | V | | LED Current Draw | Single LED Active (A,B or C) | - | 2.5 | - | mA | -The module additionally includes a power LED that draws 1 mA and turns on as soon as it is powered. J1 (Qwiic connector), J2 (Qwiic connector), and the headers all share the same power branch. The power distribution of the module is therefore as follows: - -![Power Tree Modulino Buttons](assets/Modulino_Buttons_Power_Tree.png) +The module includes a power LED that draws 1 mA and turns on as soon as it is powered. -## Schematic +### Schematic -The Modulino Buttons uses a simple circuit, as shown in the schematic below: +The Modulino Buttons uses a straightforward circuit design featuring three tactile buttons, three user-programmable LEDs, and the STM32C011F4U6TR microcontroller. ![Full Schematic Modulino Buttons](assets/schematic.png) @@ -111,81 +90,20 @@ The main components are the **three tactile buttons**, **three user-programmable You can connect to the I²C pins (SDA and SCL) using either the **QWIIC connectors** (J1 and J2, this is the recommended method) or the **solderable pins** (J4). The board runs on **3.3V**, which comes from the QWIIC cable or the **3V3 pin** on J4. -There's also a small power LED indicator that lights up when the board is on. -You can grab the full schematic and PCB files from the [Modulino Buttons](https://docs.arduino.cc/hardware/modulinos/modulino-buttons) product page. - -## How To Connect Your Modulino - -The easiest and most reliable way to connect your Modulino is through the QWIIC Connect System. It’s plug-and-play, uses standard I²C, and makes it easy to join multiple modules. If your board supports QWIIC, this is the recommended way to go. - -Note that the dedicated I²C pins will differ from board to board meaning it is always a good idea to check your specific model. - -![Modulino Wiring Options QWIIC(A - recommended) and Header(B)](assets/connection-guide-buttons.png) - -### QWIIC Connector - -Whenever available, the **QWIIC Connect System** is the preferred method. Connecting to the Modulino is extremely simple, just use a standard QWIIC cable to connect your board to either of the QWIIC connectors on the Modulino. Because the cable and connectors are polarized, there is no need to worry about accidentally swapping connections. - -QWIIC is a plug-and-play I²C Connect System that uses standardized 4-pin connectors: - -- GND -- 3.3V -- SDA (Data) -- SCL (Clock) - -![Connection Guide QWIIC](assets/connection-guide-buttons-qwiik.png) - -The Modulino features two QWIIC connectors, which are internally connected in parallel. This means you can daisy-chain multiple modules easily by connecting additional QWIIC cables between them. - -### Solderable Header - -When QWIIC is not available, you can use the exposed solderable pins on the module. You can solder pins to the unpopulated pads; just remember the pinout provided in this guide to connect to the right pins of your board. - -![Connection Guide Solder Pads](assets/connection-guide-buttons-jumper.png) - -## Daisy-Chaining Multiple Modulino Nodes - - -Regardless of whether you connect the first Modulino via QWIIC or through the solderable pins, you can still take advantage of the extra QWIIC connector to daisy-chain additional modules. -Each Modulino includes two QWIIC connectors wired in parallel, allowing you to connect one module to the next in a chain. As long as each module is configured with a unique I²C address, they can all communicate on the same bus. - -This approach keeps your setup clean, modular, and expandable without adding extra wiring complexity. +You can grab the full schematic and PCB files from the [Modulino Buttons product page](https://docs.arduino.cc/hardware/modulinos/modulino-buttons). -![Modulino Wiring Options](assets/connection-guide-buttons-qwiic-chain.png) +## Programming with Arduino -***The number of modules you can connect will depend on what modules you are chaining together, as this system allows for multiple sensors from different manufacturers to be added. Also, the cables you use for these connections will play a significant role in the setup’s performance. Ensure your cables are properly connected and capable of handling the required data transfer. -Each module should have a unique address on a chain if you plan to address them individually. Later in this article we teach how to [change the address](#how-to-change-i2c-address). Multiple modules with the same address will cause conflicts on the I²C bus and will not allow you to address them individually.*** +The Modulino Buttons is fully compatible with the Arduino IDE and the official Modulino library. The following examples showcase basic button reading and LED control functionality that can be easily integrated into your interactive projects. -## How To Use Your Modulino +### Prerequisites -### Installing The Modulino Library +- Install the Modulino library via the Arduino IDE Library Manager +- Connect your Modulino Buttons via QWIIC or solderable headers -You need the official Modulino library available [here](https://docs.arduino.cc/libraries/modulino/) to use the Modulino Buttons. +For detailed instructions on setting up your Arduino environment and installing libraries, please refer to the [Getting Started with Modulinos guide](link-to-generic-guide). -With the Arduino IDE you get some tools that make adding a library easier. To learn how to install the IDE please visit our [page](https://docs.arduino.cc/software/ide-v2/tutorials/getting-started/ide-v2-downloading-and-installing/). - -After opening the IDE, a tab should be visible on the left. Press the book icon for "library" as highlighted in the image. - -![IDE Library Tab](assets/IDE-Left-Tab.png) - -The process should look like this: - -![Library Install](assets/library-install.gif) - -A message will appear after the installation is successful. - -### Getting Button Press Data - -Interacting with the Modulino Buttons module is simple using the `Modulino` library. - -For the **Buttons** module, there are two key functions: - -- `update()`**:** Requests new data from the button module. -- `isPressed(index)`**:** Checks if a specific button (`A`, `B`, or `C`) is pressed. -- `setLeds(A, B, C)`**:** Sets the state of the LED (`A`, `B`, or `C`). -- ```Modulino.begin();```: By default the Modulino library uses ```Wire1``` if your connection is in a different Wire you will have to edit it, check [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/) (by default the Modulino library uses ```Wire1``` if your board model has a different pinout for the dedicated I²C pins you might have to edit it. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/)) for the library's hardware compatibility. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/). - -Here is an example sketch demonstrating how to use these functions to detect button presses: +### Basic Example ```arduino #include @@ -216,22 +134,16 @@ void loop() { } } ``` -The code example provided shows how to initialize the button module, read button states, and control the LEDs. The program begins by turning on all three LEDs, then continuously checks for button presses and reports them through the serial monitor. Each button is identified by its index (0 for A, 1 for B, 2 for C), making it easy to expand the functionality for more complex interactions. This simple interface can be adapted to trigger various actions in your projects, from controlling other components to navigating menus or implementing game controls. -### Detecting Button Events +### Key Functions -The Modulino Buttons module can be enhanced with the [Button2 library](https://docs.arduino.cc/libraries/button2/) to detect various button events beyond simple presses. This approach allows you to respond to single clicks, double clicks, triple clicks, and long presses. +- `update()`: Requests new data from the button module +- `isPressed(index)`: Checks if a specific button (0=A, 1=B, 2=C) is pressed +- `setLeds(A, B, C)`: Sets the state of the LEDs (true=on, false=off) -For the **Button Events** functionality, there are several key functions: +### Advanced Example - Button Events with Button2 Library -- `setButtonStateFunction(function)`**:** Sets a custom function that provides the button state. -- `setClickHandler(function)`**:** Sets a handler for single-click events. -- `setDoubleClickHandler(function)`**:** Sets a handler for double-click events. -- `setTripleClickHandler(function)`**:** Sets a handler for triple-click events. -- `setLongClickHandler(function)`**:** Sets a handler for long-press events. -- `loop()`**:** Must be called repeatedly to check for button state changes. - -Here is an example sketch demonstrating how to implement button event detection: +The Modulino Buttons can be enhanced with the Button2 library to detect various button events beyond simple presses. ```arduino #include "Modulino.h" @@ -266,9 +178,7 @@ void handler(Button2& btn) { } void setup() { - Serial.begin(115200); - Modulino.begin(); modulino_buttons.begin(); @@ -286,64 +196,155 @@ void loop() { } ``` -The code example provided shows how to integrate the Button2 library with the Modulino Buttons module to detect advanced button interactions. It creates a virtual button connected to Button A (index 0) and sets up handlers for different types of clicks. The `button0StateHandler()` function serves as a bridge between the Modulino hardware and the Button2 library by converting the button state to the expected format. When running, the program will detect and report single clicks, double clicks, triple clicks, and long presses through the serial monitor. This approach enables more sophisticated user interfaces in your projects, from navigating multi-level menus to implementing different functions based on how a user interacts with a single button. +## Programming with MicroPython -### How To Change I2C Address +The Modulino Buttons is fully compatible with MicroPython through the official Modulino MicroPython library. The following examples demonstrate how to detect button presses, handle various button events, and control the integrated LEDs in your MicroPython projects. -An example sketch, AddressChanger, is also included with the library inside the `Utilities` folder and available [here](https://github.com/arduino-libraries/Modulino/blob/main/examples/Utilities/AddressChanger/AddressChanger.ino). This sketch changes the I²C address at a software level on the Module's microcontroller. +### Prerequisites -![Example location on the IDE](assets/AdressChangeIDE.png) +- Install the Modulino MicroPython library +- Ensure Arduino Lab for MicroPython is installed -- Connect the module to your board, remove any other modules that might be in the chain. Connection must be via I²C. -- Upload the sketch. -- Open the Serial Monitor. -- Text should now appear. Make sure the correct bauld-rate is selected if the displayed characters seem corrupted. +For detailed instructions on setting up your MicroPython environment and installing packages, please refer to the [Getting Started with Modulinos guide](link-to-generic-guide). - ![Expected console output](assets/adressChanger.png) +### Basic Example -- Select the address and confirm. Valid I²C addresses range from 0x08 to 0x77 (7-bit values in hexadecimal format, e.g., 0x42). -- Your address should now have changed. Make sure to take note of the selected address. +```python +from modulino import ModulinoButtons +from time import sleep -To keep track of the address in use the module has a white rectangle on the back. Feel free to use this to write the address that was chosen. +buttons = ModulinoButtons() -When using a custom address in your sketch, you'll need to specify this address when creating the module object. For example: -```arduino -ModulinoButtons buttons(0x3E); // Replace 0x3E with your specific address -``` +# Define button press actions +buttons.on_button_a_press = lambda : print("Button A pressed") +buttons.on_button_a_long_press = lambda : print("Button A long press") +buttons.on_button_a_release = lambda : print("Button A released") +buttons.on_button_b_press = lambda : print("Button B pressed") +buttons.on_button_b_long_press = lambda : print("Button B long press") +buttons.on_button_b_release = lambda : print("Button B released") -## Troubleshooting +buttons.on_button_c_press = lambda : print("Button C pressed") +buttons.on_button_c_long_press = lambda : print("Button C long press") +buttons.on_button_c_release = lambda : print("Button C released") -### Buttons Not Responding +# LED Sequence: Turn each LED on with a delay, then turn them off +buttons.led_a.on() +sleep(0.5) +buttons.led_b.on() +sleep(0.5) +buttons.led_c.on() +sleep(0.5) +buttons.set_led_status(False, False, False) # Turn off all LEDs -If your Modulino's power LED isn't on or the buttons aren't responsive, first check that the board is properly connected: +while True: + buttons_state_changed = buttons.update() + + if buttons_state_changed: + led_a_status = buttons.is_pressed(0) # Turn LED A on if button A is pressed + led_b_status = buttons.is_pressed(1) # Turn LED B on if button B is pressed + led_c_status = buttons.is_pressed(2) # Turn LED C on if button C is pressed + buttons.set_led_status(led_a_status, led_b_status, led_c_status) +``` -- Ensure both the board and the Modulino are connected to your computer, and that the power LEDs on both are lit. -- If the issue persists, make sure the Qwiic cable is properly clicked into place. +### Key Functions and Properties + +- `.on_button_x_press`: Callback for button press events +- `.on_button_x_long_press`: Callback for long press events +- `.on_button_x_release`: Callback for button release events +- `.led_x.on()/.off()`: Control individual LEDs +- `.set_led_status(a, b, c)`: Set all LED states at once +- `.is_pressed(index)`: Check if a button is currently pressed +- `.update()`: Check for button state changes + +### Advanced Example - Menu System + +```python +from modulino import ModulinoButtons +from time import sleep + +buttons = ModulinoButtons() + +# Menu system variables +menu_items = ["Option 1", "Option 2", "Option 3", "Settings", "Exit"] +current_index = 0 +in_submenu = False + +def show_menu(): + """Display current menu state via LEDs and serial""" + print("\n--- MENU ---") + for i, item in enumerate(menu_items): + prefix = ">" if i == current_index else " " + print(f"{prefix} {item}") + + # Show position with LEDs + buttons.set_led_status( + current_index == 0, + current_index == 2, + current_index == 4 + ) + +def next_item(): + """Move to next menu item""" + global current_index + current_index = (current_index + 1) % len(menu_items) + show_menu() + +def previous_item(): + """Move to previous menu item""" + global current_index + current_index = (current_index - 1) % len(menu_items) + show_menu() + +def select_item(): + """Select current menu item""" + print(f"\n✓ Selected: {menu_items[current_index]}") + + # Flash all LEDs to confirm selection + for _ in range(3): + buttons.set_led_status(True, True, True) + sleep(0.1) + buttons.set_led_status(False, False, False) + sleep(0.1) + +# Configure button actions +buttons.on_button_a_press = previous_item # Navigate up +buttons.on_button_b_press = select_item # Select +buttons.on_button_c_press = next_item # Navigate down + +# Initialize +print("Menu Navigation System") +print("A: Previous | B: Select | C: Next") +show_menu() + +# Main loop +while True: + buttons.update() + sleep(0.01) +``` -### Library Not Installed Properly +## Troubleshooting -If you encounter an issue with the `#include "modulino.h"` command, verify that the Modulino library is correctly installed: +### Buttons Not Responding -- Check your IDE to ensure the library is installed and up-to-date. -- Re-install the library through the Library Manager. +If your Modulino's power LED isn't on or the buttons aren't responsive: +- Ensure both the board and the Modulino are connected properly +- Verify that the power LEDs on both are lit +- Check that the QWIIC cable is properly clicked into place ### LEDs Not Working -If the LEDs aren't lighting up as expected, make sure: - -- The correct LED states are being set in your code (true for on, false for off). -- All exposed electronics are not touching any conductive surfaces, as this could interfere with the operation. - -## Conclusion - -The **Modulino Buttons** is a digital input and output device that communicates over I²C and follows the Modulino form factor. It includes standard Qwiic connectors for quick, solderless connections and easy daisy-chaining with other modules. Paired with the Modulino library, it makes detecting button presses and controlling LEDs straightforward, allowing you to focus on experimenting or building your system logic. It's a small, reliable module suited for both user interfaces and interactive control systems. - -## What Is Next? +If the LEDs aren't lighting up as expected: +- Verify correct LED states are being set in your code +- Check that exposed electronics are not touching conductive surfaces +- Ensure adequate power supply for LED operation -Now that you've learned how to use your Modulino Buttons, you're all set to integrate it into your projects! +## Project Ideas -- Create a simple menu system where each button performs a different function. -- Build a game controller for a simple arcade-style game. -- Use the buttons to control other Modulino devices in your project. -- Design an interactive installation where button presses trigger different visual and audio effects. \ No newline at end of file +- **Simple Menu System**: Each button performs a different function or navigates menus +- **Game Controller**: Build controls for arcade-style games +- **Interactive Control Panel**: Control other Modulino devices in your project +- **Pattern Memory Game**: Create a Simon-style memory game with LED feedback +- **Morse Code Trainer**: Practice Morse code with button input and LED feedback +- **Smart Home Controller**: Three-button interface for home automation +- **Music Box Controller**: Each button plays different notes or controls playback \ No newline at end of file diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-buzzer/tutorials/how-buzzer-ardu/assets/BuzzerOverview.png b/content/hardware/11.accessories/modulino-nodes/modulino-buzzer/tutorials/how-buzzer-ardu/assets/BuzzerOverview.png new file mode 100644 index 0000000000..aa71e573da Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-buzzer/tutorials/how-buzzer-ardu/assets/BuzzerOverview.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-buzzer/tutorials/how-buzzer-ardu/content.md b/content/hardware/11.accessories/modulino-nodes/modulino-buzzer/tutorials/how-buzzer-ardu/content.md index 0c74563365..4f56f4579f 100644 --- a/content/hardware/11.accessories/modulino-nodes/modulino-buzzer/tutorials/how-buzzer-ardu/content.md +++ b/content/hardware/11.accessories/modulino-nodes/modulino-buzzer/tutorials/how-buzzer-ardu/content.md @@ -1,8 +1,11 @@ --- -title: "How To Use The Modulino Buzzer" -description: "Learn how to get the most out of your Modulino Buzzer." +title: "Modulino Buzzer" +description: "Complete guide for the Modulino Buzzer audio output module." tags: - Modulino + - Buzzer + - Audio + - Sound - QWIIC - I2C author: 'Pedro Sousa Lima' @@ -11,15 +14,18 @@ hardware: software: - ide-v2 - web-editor + - micropython --- -The Modulino Buzzer is a modular sensor that generates audio output, making it perfect to add sound feedback to your projects! -The Modulino form factor is shaped with two QWIIC connectors and the I²C protocol integration, allowing the connection and programming of multiple Modulino nodes in a very simple way. In addition to the QWIIC's connectors, the Modulino nodes also expose solderable pins that can be used in multiple ways and make them compatible with boards that are not QWIIC compatible. +![Buzzer Overview](assets/BuzzerOverview.png) +The Modulino Buzzer is a modular sensor that generates audio output, making it perfect to add sound feedback to your projects! It uses the standardised Modulino form factor with QWIIC connectors for easy integration. -## Hardware Specifications +## Hardware Overview -The Modulino Buzzer based on the buzzer (PKLCS1212E4001-R1) is capable of generating different tones and sound patterns. Take a look at the following table to know more about its characteristics: +### General Characteristics + +The Modulino Buzzer is based on the PKLCS1212E4001-R1 buzzer, capable of generating different tones and sound patterns. | Parameter | Condition | Minimum | Typical | Maximum | Unit | |----------------------|-----------|---------|---------|---------|------| @@ -30,27 +36,19 @@ The Modulino Buzzer based on the buzzer (PKLCS1212E4001-R1) is capable of genera The **Modulino Buzzer** module uses the **PKLCS1212E4001-R1** buzzer, which does not have native I²C capabilities. Instead, the buzzer is controlled by the Modulino's onboard microcontroller (STM32C011F4U6T). This microcontroller provides I²C communication, allowing for flexible control of the buzzer. -One unique feature of this setup is the ability to change the I²C address via software. This means the address can be modified based on your application needs, making it adaptable to different system configurations. +One unique feature of this setup is the ability to change the I²C address via software, making it adaptable to different system configurations. The default I²C address for the **Modulino Buzzer** module is: -| Modulino I²C Address | Hardware I²C Address |Editable Addresses (HEX)| -|----------------------|----------------------|----------------------| -| 0x3C | 0x1E |Any custom address (via software configuration) - - -When scanning for I²C address on the bus, you might find the modulino using the **Hardware I²C Address**. However, you should always use the **Modulino I²C Address** when using the official Modulino library. - -Later in this article we teach how to [change the address](#how-to-change-i2c-address). +| Modulino I²C Address | Hardware I²C Address | Editable Addresses (HEX) | +|----------------------|----------------------|--------------------------------------------------| +| 0x3C | 0x1E | Any custom address (via software configuration) | - -## Pinout - -The PKLCS1212E4001-R1 buzzer is the core component of this module. This audio output device is controlled by an onboard STM32 microcontroller, which supports digital communication (I²C), meaning it connects directly to the I²C bus on the module without requiring additional conversion circuitry. +### Pinout ![Arduino Buzzer Pinout](assets/BuzzerPinouts.png) -### 1x8 Header +#### 1x8 Header | Pin | Function | |--------|-----------------| @@ -63,20 +61,10 @@ The PKLCS1212E4001-R1 buzzer is the core component of this module. This audio ou | RX1 | USART Receive | | PA0 | Buzzer | -- **GND:** Provides ground reference for the circuit. -- **3V3:** Supplies 3.3 V power to connected components and modules. -- **Reset:** The reset pin for the microcontroller, which can be used to reset the system. -- **SWCLK:** Used for providing the clock signal in the SWD interface. -- **SWDIO:** Used for debugging, as part of the Serial Wire Debug (SWD) interface. -- **TX1:** Used for transmitting data over UART communication. -- **RX1:** Used for receiving data over UART communication. -- **PA0:** This pin is used to control the buzzer's output signal. In fact, this pin can be used to bypass the I²C interface and control the buzzer directly using a square wave. -![Direct control via signal](assets/buzzerPA0.gif) - - -### 1x4 Header (I2C) +**PA0**: This pin can be used to bypass the I²C interface and control the buzzer directly using a square wave. +![Control through PA0 Pin](assets/buzzerPA0.gif) -The pinout for the Modulino Buzzer is shown below. While the recommended connection method is via the QWIIC connectors, this solderable header provides a connection option when using the modulino with a non-QWIIC compatible board. +#### 1x4 Header (I2C) | Pin | Function | |-------|--------------| @@ -85,23 +73,18 @@ The pinout for the Modulino Buzzer is shown below. While the recommended connect | SDA | I²C Data | | SCL | I²C Clock | - -## Power Specifications - -The board is typically powered by +3.3 VDC when using the QWIIC interface as per the I²C standard. +### Power Specifications | Parameter | Condition | Typical | Unit | |---------------------|-----------|---------|------| | Operating Voltage | - | 3.3 | V | | Current Consumption | - | ~6.4 | mA | -The module additionally includes a power LED that draws 1 mA and turns on as soon as it is powered. -J1 (Qwiic connector), J2 (Qwiic connector), and the headers all share the same power branch. The power distribution of the module is therefore as follows: -![Power Tree Modulino Buzzer](assets/Modulino_Buzzer_Power_Tree.png) +The module includes a power LED that draws 1 mA and turns on as soon as it is powered. -## Schematic +### Schematic -The Modulino Buzzer uses a simple circuit, as shown in the schematic below: +The Modulino Buzzer features a simple yet effective circuit design for audio generation. ![Full Schematic Modulino Buzzer](assets/schematic.png) @@ -111,75 +94,20 @@ You can connect to the I²C pins (SDA and SCL) using either the **QWIIC connecto There's also a small power LED indicator that lights up when the board is on. -You can grab the full schematic and PCB files from the [Modulino Buzzer](https://docs.arduino.cc/hardware/modulinos/modulino-buzzer) product page. - -## How To Connect Your Modulino - -The easiest and most reliable way to connect your Modulino is through the QWIIC Connect System. It’s plug-and-play, uses standard I²C, and makes it easy to join multiple modules. If your board supports QWIIC, this is the recommended way to go. Note that the dedicated I²C pins will differ from board to board meaning it is always a good idea to check your specific model. - -If your board doesn’t have a QWIIC connector, you can still access the same I²C bus and power the module using the solderable header pads just make sure you wire it to 3.3V and match the I²C pinout. - -![Modulino Wiring Options QWIIC(A - recommended) and Header(B)](assets/connection-guide-buzzer.png) - -### QWIIC Connector - -Whenever available, the **QWIIC Connect System** is the preferred method. Connecting to the Modulino is extremely simple, just use a standard QWIIC cable to connect your board to either of the QWIIC connectors on the Modulino. Because the cable and connectors are polarized, there is no need to worry about accidentally swapping connections. - -QWIIC is a plug-and-play I²C Connect System that uses standardized 4-pin connectors: -- GND -- 3.3V -- SDA (Data) -- SCL (Clock) - -![Connection Guide QWIIC](assets/connection-guide-buzzer-qwiik.png) - -The Modulino features two QWIIC connectors, which are internally connected in parallel. This means you can daisy-chain multiple modules easily by connecting additional QWIIC cables between them. - -### Solderable Header - -When QWIIC is not available, you can use the exposed solderable pins on the module. You can solder pins to the unpopulated pads; just remember the pinout provided in this guide to connect to the right pins of your board. - -![Connection Guide Solder Pads](assets/connection-guide-buzzer-jumper.png) - -## Daisy-Chaining Multiple Modulino Nodes - -Regardless of whether you connect the first Modulino via QWIIC or through the solderable pins, you can still take advantage of the extra QWIIC connector to daisy-chain additional modules. - -Each Modulino includes two QWIIC connectors wired in parallel, allowing you to connect one module to the next in a chain. As long as each module is configured with a unique I²C address, they can all communicate on the same bus as long as you select the correct I²C pins depending on your board. - -This approach keeps your setup clean, modular, and expandable without adding extra wiring complexity. - -![Modulino Wiring Options](assets/connection-guide-buzzer-qwiic-chain.png) - -***The number of modules you can connect will depend on what modules you are chaining together, as this system allows for multiple sensors from different manufacturers to be added. Also, the cables you use for these connections will play a significant role in the setup’s performance. Ensure your cables are properly connected and capable of handling the required data transfer. -Each module should have a unique address on a chain if you plan to address them individually. Later in this article we teach how to [change the address](#how-to-change-i2c-address). Multiple modules with the same address will cause conflicts on the I²C bus and will not allow you to address them individually.*** - -## How To Use Your Modulino +You can grab the full schematic and PCB files from the [Modulino Buzzer product page](https://docs.arduino.cc/hardware/modulinos/modulino-buzzer). -### Installing The Modulino Library +## Programming with Arduino -You need the official Modulino library available [here](https://docs.arduino.cc/libraries/modulino/) to use the Modulino Buzzer. +The Modulino Buzzer is fully compatible with the Arduino IDE and the official Modulino library. The following examples showcase how to generate tones, create melodies, and add audio feedback to your Arduino projects. -With the Arduino IDE you get some tools that make adding a library easier. To learn how to install the IDE please visit our [page](https://docs.arduino.cc/software/ide-v2/tutorials/getting-started/ide-v2-downloading-and-installing/). +### Prerequisites -After opening the IDE, a tab should be visible on the left. Press the book icon for "library" as highlighted in the image. +- Install the Modulino library via the Arduino IDE Library Manager +- Connect your Modulino Buzzer via QWIIC or solderable headers -![IDE Library Tab](assets/IDE-Left-Tab.png) +For detailed instructions on setting up your Arduino environment and installing libraries, please refer to the [Getting Started with Modulinos guide](link-to-generic-guide). -The process should look like this: - -![Library Install](assets/library-install.gif) - -A message will appear after the installation is successful. - -### Play A Simple Tune - -Getting sound feedback from the buzzer is fairly simple using the ```Modulino``` library. For the **Modulino Buzzer** there is one important function: - -- ```tone(frequency, duration)```: Generates a tone with the specified frequency (in Hz) and duration (in milliseconds). -- ```Modulino.begin();```: By default the Modulino library uses ```Wire1``` if your connection is in a different Wire you will have to edit it, check [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/) (by default the Modulino library uses ```Wire1``` if your board model has a different pinout for the dedicated I²C pins you might have to edit it. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/)) for the library's hardware compatibility. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/). - -Here is an example sketch of how to implement this function to control the buzzer: +### Basic Example ```arduino #include @@ -200,69 +128,210 @@ void loop(){ buzzer.tone(0, duration); // Stop the tone delay(1000); // Wait for 1 second } -``` - -The code example provided shows how to initialize the buzzer and generate tones. The buzzer alternates between playing a 440 Hz tone for one second and staying silent for one second. -It can be easily adapted to play different melodies or to provide sound feedback for your projects based on specific conditions or events. +``` -### How To Change I2C Address +### Key Functions -An example sketch, AddressChanger, is also included with the library inside the `Utilities` folder and available [here](https://github.com/arduino-libraries/Modulino/blob/main/examples/Utilities/AddressChanger/AddressChanger.ino). This sketch changes the I²C address at a software level on the Module's microcontroller. +- `tone(frequency, duration)`: Generates a tone with the specified frequency (in Hz) and duration (in milliseconds) +- Setting frequency to 0 stops the tone -![Example location on the IDE](assets/addressChangeIDE.png) +### Advanced Example - Musical Melody -- Connect the module to your board, remove any other modules that might be in the chain. Connection must be via I²C. -- Upload the sketch. -- Open the Serial Monitor. -- Text should now appear. Make sure the correct bauld-rate is selected if the displayed characters seem corrupted. - - ![Expected console output](assets/adressChanger.png) +```arduino +#include -- Select the address and confirm. Valid I²C addresses range from 0x08 to 0x77 (7-bit values in hexadecimal format, e.g., 0x42). -- Your address should now have changed. Make sure to take note of the selected address. +ModulinoBuzzer buzzer; -To keep track of the address in use the module has a white rectangle on the back. Feel free to use this to write the address that was chosen. +// Musical notes (frequencies in Hz) +#define NOTE_C4 262 +#define NOTE_D4 294 +#define NOTE_E4 330 +#define NOTE_F4 349 +#define NOTE_G4 392 +#define NOTE_A4 440 +#define NOTE_B4 494 +#define NOTE_C5 523 +#define REST 0 + +// Simple melody: "Twinkle Twinkle Little Star" +int melody[] = { + NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4, REST, + NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4, REST +}; + +// Note durations: 4 = quarter note, 8 = eighth note, etc. +int noteDurations[] = { + 4, 4, 4, 4, 4, 4, 2, 4, + 4, 4, 4, 4, 4, 4, 2, 4 +}; + +void setup() { + Serial.begin(9600); + Modulino.begin(); + buzzer.begin(); + + Serial.println("Playing melody..."); + playMelody(); +} -When using a custom address in your sketch, you'll need to specify this address when creating the module object. For example: +void playMelody() { + for (int thisNote = 0; thisNote < 16; thisNote++) { + // Calculate the note duration + int noteDuration = 1000 / noteDurations[thisNote]; + + buzzer.tone(melody[thisNote], noteDuration); + + // Pause between notes + int pauseBetweenNotes = noteDuration * 1.30; + delay(pauseBetweenNotes); + + // Stop the tone + buzzer.tone(0, 10); + } +} -```arduino -ModulinoBuzzer buzzer(0x3E); // Replace 0x3E with your specific address +void loop() { + // Play melody every 5 seconds + delay(5000); + playMelody(); +} ``` +## Programming with MicroPython -## Troubleshooting +The Modulino Buzzer is fully compatible with MicroPython through the official Modulino MicroPython library. The following examples demonstrate how to generate tones, create sound patterns, and implement audio feedback in your MicroPython projects. -### Buzzer Not Sounding +### Prerequisites -If your Modulino's power LED isn't on or the buzzer isn't responsive, first check that the board is properly connected: +- Install the Modulino MicroPython library +- Ensure Arduino Lab for MicroPython is installed -- Ensure both the board and the Modulino are connected to your computer, and that the power LEDs on both are lit. -- If the issue persists, make sure the Qwiic cable is properly clicked into place. +For detailed instructions on setting up your MicroPython environment and installing packages, please refer to the [Getting Started with Modulinos guide](link-to-generic-guide). -### Library Not Installed Properly +### Basic Example -If you encounter an issue with the `#include "modulino.h"` command, verify that the Modulino library is correctly installed: +```python +from modulino import ModulinoBuzzer +from time import sleep -- Check your IDE to ensure the library is installed and up-to-date. -- Re-install the library through the Library Manager. +buzzer = ModulinoBuzzer() -### Distorted Sound +frequency = 440 # Frequency of the tone in Hz +duration = 1000 # Duration of the tone in milliseconds -If the buzzer sound is distorted or not playing as expected, make sure: +# Play the tone +buzzer.tone(frequency, duration, blocking=True) +sleep(1) # Wait for 1 second -- The correct frequency values are being used (typically between 20 Hz and 20 kHz for audible sounds). -- All exposed electronics are not touching any conductive surfaces, as this could interfere with the sound output. +# Stop the tone +buzzer.tone(0, duration, blocking=True) +sleep(1) # Wait for 1 second +``` -## Conclusion +### Key Functions + +- `tone(frequency, duration, blocking)`: Generates a tone with specified frequency and duration + - `blocking=True`: Waits for tone to complete before continuing + - `blocking=False`: Returns immediately while tone plays + +### Advanced Example - Alarm System + +```python +from modulino import ModulinoBuzzer +from time import sleep + +buzzer = ModulinoBuzzer() + +# Define different alarm patterns +def beep_pattern(): + """Simple beep pattern""" + for _ in range(3): + buzzer.tone(1000, 100, blocking=True) + sleep(0.1) + +def alarm_pattern(): + """Urgent alarm pattern""" + for i in range(5): + frequency = 800 + (i * 100) + buzzer.tone(frequency, 200, blocking=True) + sleep(0.05) + +def siren_pattern(): + """Police siren-like pattern""" + for _ in range(3): + # Rising tone + for freq in range(400, 800, 50): + buzzer.tone(freq, 50, blocking=True) + # Falling tone + for freq in range(800, 400, -50): + buzzer.tone(freq, 50, blocking=True) + +def notification_sound(): + """Pleasant notification sound""" + notes = [523, 659, 784, 1047] # C5, E5, G5, C6 + for note in notes: + buzzer.tone(note, 150, blocking=True) + sleep(0.05) + +def success_sound(): + """Success/completion sound""" + buzzer.tone(523, 100, blocking=True) # C5 + sleep(0.05) + buzzer.tone(659, 100, blocking=True) # E5 + sleep(0.05) + buzzer.tone(784, 200, blocking=True) # G5 + +# Demonstration menu +patterns = { + "1": ("Beep Pattern", beep_pattern), + "2": ("Alarm Pattern", alarm_pattern), + "3": ("Siren Pattern", siren_pattern), + "4": ("Notification", notification_sound), + "5": ("Success Sound", success_sound) +} -The **Modulino Buzzer** is a digital sound output device that communicates over I²C and follows the Modulino form factor. It includes standard Qwiic connectors for quick, solderless connections and easy daisy-chaining with other modules. Paired with the Modulino library, it makes generating sound feedback straightforward, allowing you to focus on experimenting or building your system logic. It's a small, reliable module suited for both interactive feedback and audio alert systems. +print("🔊 Buzzer Pattern Demo") +print("Select a pattern:") +for key, (name, _) in patterns.items(): + print(f" {key}: {name}") + +while True: + choice = input("\nEnter pattern number (1-5): ") + + if choice in patterns: + name, pattern_func = patterns[choice] + print(f"Playing: {name}") + pattern_func() + print("Done!") + else: + print("Invalid choice. Please enter 1-5.") + + sleep(1) +``` -## What Is Next? +## Troubleshooting -Now that you've learned how to use your Modulino Buzzer, you're all set to integrate it into your projects! +### Buzzer Not Sounding + +If your Modulino's power LED isn't on or the buzzer isn't responsive: +- Ensure both the board and the Modulino are connected properly +- Verify that the power LEDs on both are lit +- Check that the QWIIC cable is properly clicked into place -- Experiment with different frequencies to create various tones and melodies. -- Try creating a simple alarm system that triggers the buzzer when certain conditions are met. -- Use the buzzer to provide feedback in your interactive projects when a button is pressed or a threshold is reached. -- Create a music box that plays different tunes when specific inputs are detected! +### Distorted Sound +If the buzzer sound is distorted or not playing as expected: +- Verify correct frequency values are being used (typically 20 Hz to 20 kHz for audible sounds) +- Check that exposed electronics are not touching conductive surfaces +- Ensure stable power supply + +## Project Ideas + +- **Simple Alarm System**: Trigger the buzzer when certain conditions are met +- **Music Box**: Play different tunes based on sensor inputs +- **Timer Alert**: Create a pomodoro timer with audio notifications +- **Game Sound Effects**: Add audio feedback to interactive games +- **Morse Code Transmitter**: Send messages using Morse code patterns +- **Parking Sensor**: Combine with Modulino Distance for proximity alerts +- **Temperature Alert**: Use with Modulino Thermo for temperature warnings +- **Interactive Doorbell**: Create custom doorbell melodies \ No newline at end of file diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-distance/tutorials/how-distance-ardu/assets/distanceOverview.png b/content/hardware/11.accessories/modulino-nodes/modulino-distance/tutorials/how-distance-ardu/assets/distanceOverview.png new file mode 100644 index 0000000000..7b3b798588 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-distance/tutorials/how-distance-ardu/assets/distanceOverview.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-distance/tutorials/how-distance-ardu/content.md b/content/hardware/11.accessories/modulino-nodes/modulino-distance/tutorials/how-distance-ardu/content.md index 14d6e61714..a3b46f8b47 100644 --- a/content/hardware/11.accessories/modulino-nodes/modulino-distance/tutorials/how-distance-ardu/content.md +++ b/content/hardware/11.accessories/modulino-nodes/modulino-distance/tutorials/how-distance-ardu/content.md @@ -1,8 +1,11 @@ --- -title: "How To Use The Modulino Distance" -description: "Learn how to get the most out of your Modulino Distance." +title: "Modulino Distance" +description: "Complete guide for the Modulino Distance Time-of-Flight sensor module." tags: - Modulino + - Distance + - ToF + - Sensor - QWIIC - I2C author: 'Pedro Sousa Lima' @@ -11,14 +14,18 @@ hardware: software: - ide-v2 - web-editor + - micropython --- +![Distance Overview](assets/distanceOverview.png) + The Modulino Distance is a modular sensor that measures distance using Time-of-Flight (ToF) technology, making it perfect to add precise distance sensing and depth mapping to your projects! -The Modulino form factor is shaped with two QWIIC connectors and the I²C protocol integration, allowing the connection and programming of multiple Modulino nodes in a very simple way. In addition to the QWIIC's connectors, the Modulino nodes also expose solderable pins that can be used in multiple ways and make them compatible with boards that are not QWIIC compatible. -## General Characteristics +## Hardware Overview + +### General Characteristics -The Modulino Distance is capable of measuring distances using Time-of-Flight technology. Take a look at the following table to know more about its measuring ranges: +The Modulino Distance is capable of measuring distances using Time-of-Flight technology with the following specifications: | Parameter | Condition | Minimum | Typical | Maximum | Unit | |-----------------------|----------------------|---------|---------|---------|------| @@ -26,7 +33,6 @@ The Modulino Distance is capable of measuring distances using Time-of-Flight tec | Resolution | - | - | 1 | - | mm | | Operating Temperature | - | -30 | - | 85 | °C | - ### Sensor Details The VL53L4CDV0DH/1 sensor from STMicroelectronics is the core component of this module. This ToF sensor natively supports digital communication (I²C), meaning it connects directly to the I²C bus on the module without requiring additional conversion circuitry. @@ -44,13 +50,11 @@ The default address for the Module is: ***Note: Since the address cannot be changed on this Modulino specifically, using two or more identical modules on the same I²C bus will result in address conflicts and cause communication issues.*** -## Pinout - -The pinout for the Modulino Distance is shown below. Please note that the exposed solderable pins are directly connected to the QWIIC connectors using the same I²C interface. +### Pinout ![Arduino Distance Pinout](assets/DistancePinouts.png) -### 1x4 Header (Sensor GPIO) +#### 1x4 Header (Sensor GPIO) | Pin | Function | |-------|----------------| @@ -59,41 +63,28 @@ The pinout for the Modulino Distance is shown below. Please note that the expose | GPIO1 | Digital Output | | XSHUT | Xshutdown | -- **GND: Ground** – Ground connection for power and signal reference. -- **3V3: Power** – 3.3 V power supply input. -- **GPIO1: Digital Output** – General purpose digital output pin. -- **XSHUT: Xshutdown** – Shutdown control pin for the sensor. - -### 1x4 Header (I2C) - -The pinout for the Modulino Buzzer is shown below. While the recommended connection method is via the QWIIC connectors, this solderable header provides a connection option when using the modulino with a non-QWIIC compatible board. +#### 1x4 Header (I2C) | Pin | Function | |-------|--------------| | GND | Ground | -| 3V3 | Power Supply | +| 3.3 V | Power Supply | | SDA | I²C Data | | SCL | I²C Clock | -Depending on the board connected to the modulino, the I²C pin names to program it may differ. Please check the [board tutorials](https://docs.arduino.cc/hardware/) on your modulino's compatible board or the [Modulino library](https://github.com/arduino-libraries/Modulino/tree/main/docs) to learn more. - -## Power Specifications - -The board is typically powered by +3.3 VDC when using the QWIIC interface as per the I²C standard. +### Power Specifications | Parameter | Condition | Minimum | Typical | Maximum | Unit | -| --------------------- | ----------------------- | ------- | ----------- | ------- | ---- | +|-----------------------|-------------------------|---------|-------------|---------|------| | Supply Voltage | - | - | 3.3 (QWIIC) | - | V | | Current Consumption | Active measurement mode | - | 24 | 40 | mA | | Operating Temperature | - | -30 | - | 85 | °C | -The module additionally includes a power LED that draws 1 mA and turns on as soon as it is powered. J1 (Qwiic connector), J2 (Qwiic connector), and the headers all share the same power branch. The power distribution of the module is therefore as follows: +The module includes a power LED that draws 1 mA and turns on as soon as it is powered. -![Power Tree Modulino Distance](assets/Modulino_Distance_Power_Tree.png) +### Schematic -## Schematic - -The Modulino Distance uses a simple circuit, as shown in the schematic below: +The Modulino Distance uses a straightforward circuit built around the Time-of-Flight sensor. ![Full Schematic Modulino Distance](assets/schematic.png) @@ -103,130 +94,267 @@ You can connect to the I²C pins (SDA and SCL) using either the **QWIIC connecto There's also a small power indicator LED that lights up when the board is on. -You can grab the full schematic and PCB files from the [Modulino Distance](https://docs.arduino.cc/hardware/modulinos/modulino-distance) product page. - -## How To Connect Your Modulino - -The easiest and most reliable way to connect your Modulino is through the QWIIC Connect System. It’s plug-and-play, uses standard I²C, and makes it easy to join multiple modules. If your board supports QWIIC, this is the recommended way to go. - -Note that the dedicated I²C pins will differ from board to board meaning it is always a good idea to check your specific model. - - -![Modulino Wiring Options QWIIC(A - recommended) and Header(B)](assets/connection-guide-distance.png) - -### QWIIC Connector +You can grab the full schematic and PCB files from the [Modulino Distance product page](https://docs.arduino.cc/hardware/modulinos/modulino-distance). -Whenever available, the **QWIIC Connect System** is the preferred method. Connecting to the Modulino is extremely simple, just use a standard QWIIC cable to connect your board to either of the QWIIC connectors on the Modulino. Because the cable and connectors are polarized, there is no need to worry about accidentally swapping connections. +## Programming with Arduino -QWIIC is a plug-and-play I²C Connect System that uses standardized 4-pin connectors: +The Modulino Distance is fully compatible with the Arduino IDE and the official Modulino library. The following examples showcase how to read distance measurements and implement proximity-based features in your Arduino projects. -- GND -- 3.3 V -- SDA (Data) -- SCL (Clock) +### Prerequisites -![Connection Guide QWIIC](assets/connection-guide-distance-qwiik.png) +- Install the Modulino library via the Arduino IDE Library Manager +- Connect your Modulino Distance via QWIIC or solderable headers -The Modulino features two QWIIC connectors, which are internally connected in parallel. This means you can daisy-chain multiple modules easily by connecting additional QWIIC cables between them. +For detailed instructions on setting up your Arduino environment and installing libraries, please refer to the [Getting Started with Modulinos guide](link-to-generic-guide). -### Solderable Header +### Basic Example -When QWIIC is not available, you can use the exposed solderable pins on the module. You can solder pins to the unpopulated pads; just remember the pinout provided in this guide to connect to the right pins of your board. - -![Connection Guide Solder Pads](assets/connection-guide-distance-jumper.png) - -## Daisy-Chaining Multiple Modulino Nodes - -Regardless of whether you connect the first Modulino via QWIIC or through the solderable pins, you can still take advantage of the extra QWIIC connector to daisy-chain additional modules. Each Modulino includes two QWIIC connectors wired in parallel, allowing you to connect one module to the next in a chain. As long as each module is configured with a unique I²C address, they can all communicate on the same bus. This approach keeps your setup clean, modular, and expandable without adding extra wiring complexity. - -![Modulino Wiring Options](assets/connection-guide-distance-qwiic-chain.png) - -***The number of modules you can connect will depend on what modules you are chaining together, as this system allows for multiple sensors from different manufacturers to be added. Also, the cables you use for these connections will play a significant role in the setup's performance. Ensure your cables are correctly connected and capable of handling the required data transfer. -Each module should have a unique address on a chain if you plan to address them individually. Multiple modules with the same address will cause conflicts on the I²C bus.*** - -## How To Use Your Modulino - -### Installing The Modulino Library - -You need the official Modulino library available [here](https://docs.arduino.cc/libraries/modulino/) to use the Modulino Thermo. - -With the Arduino IDE you get some tools that make adding a library easier. To learn how to install the IDE please visit our [page](https://docs.arduino.cc/software/ide-v2/tutorials/getting-started/ide-v2-downloading-and-installing/). - -After opening the IDE, a tab should be visible on the left. Press the book icon for "library" as highlighted in the image. - -![IDE Library Tab](assets/IDE-Left-Tab.png) +```arduino +#include "Modulino.h" -The process should look like this: +// Create object instance +ModulinoDistance distance; -![Library Install](assets/library-install.gif) +void setup() { + Serial.begin(9600); -A message will appear after the installation is successful. + // Initialize the Modulino system and distance sensor + Modulino.begin(); + distance.begin(); +} -### Getting Distance Data +void loop() { + if (distance.available()) { + int measure = distance.get(); + Serial.println(measure); + } + delay(10); +} +``` -Getting data from the sensor is fairly simple using the ```Modulino``` library. For the **Modulino Distance** there are two important functions: +### Key Functions -- ```available()```: Checks if new distance data is available. -- ```get()```: Retrieves the measured distance from the sensor (default in cm). -- ```Modulino.begin();```: By default the Modulino library uses ```Wire1``` if your connection is in a different Wire you will have to edit it, check [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/) (by default the Modulino library uses ```Wire1``` if your board model has a different pinout for the dedicated I²C pins you might have to edit it. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/)) for the library's hardware compatibility. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/). +- `available()`: Checks if new distance data is available +- `get()`: Retrieves the measured distance from the sensor (default in cm) -Here is an example sketch of how to implement these functions to acquire data and show it using the serial monitor: +### Advanced Example - Parking Sensor ```arduino #include "Modulino.h" -// Create object instance ModulinoDistance distance; +// Distance thresholds in cm +const int DANGER_ZONE = 10; // Less than 10cm +const int WARNING_ZONE = 30; // 10-30cm +const int CAUTION_ZONE = 50; // 30-50cm +const int SAFE_ZONE = 100; // 50-100cm + void setup() { Serial.begin(9600); - - // Initialize the Modulino system and distance sensor Modulino.begin(); distance.begin(); + + Serial.println("Parking Sensor Active"); + Serial.println("==================="); } void loop() { if (distance.available()) { int measure = distance.get(); - Serial.println(measure); + + // Determine zone and provide feedback + if (measure < DANGER_ZONE) { + Serial.print("🔴 STOP! Distance: "); + Serial.print(measure); + Serial.println(" cm - TOO CLOSE!"); + } + else if (measure < WARNING_ZONE) { + Serial.print("🟠 WARNING - Distance: "); + Serial.print(measure); + Serial.println(" cm - Very close"); + } + else if (measure < CAUTION_ZONE) { + Serial.print("🟡 CAUTION - Distance: "); + Serial.print(measure); + Serial.println(" cm - Getting close"); + } + else if (measure < SAFE_ZONE) { + Serial.print("🟢 SAFE - Distance: "); + Serial.print(measure); + Serial.println(" cm - Good distance"); + } + else { + Serial.print("✓ Clear - Distance: "); + Serial.print(measure); + Serial.println(" cm"); + } } - delay(10); + + delay(100); // Update 10 times per second } ``` -## Troubleshooting +## Programming with MicroPython -### Sensor Not Reachable +The Modulino Distance is fully compatible with MicroPython through the official Modulino MicroPython library. The following examples demonstrate how to read distance measurements and create proximity-activated systems in your MicroPython projects. -If your Modulino's power LED isn't on or the sensor isn't responsive, first check that the board is properly connected: +### Prerequisites -- Ensure both the board and the Modulino are connected to your computer, and that the power LEDs on both are lit. -- If the issue persists, make sure the Qwiic cable is properly clicked into place. +- Install the Modulino MicroPython library +- Ensure Arduino Lab for MicroPython is installed -### Library Not Installed Properly +For detailed instructions on setting up your MicroPython environment and installing packages, please refer to the [Getting Started with Modulinos guide](link-to-generic-guide). -If you encounter an issue with the `#include "modulino.h"` command, verify that the Modulino library is correctly installed: +### Basic Example -- Check your IDE to ensure the library is installed and up-to-date. -- Re-install the library through the Library Manager. +```python +from modulino import ModulinoDistance +from time import sleep_ms -### Inaccurate Values +distance = ModulinoDistance() -If the sensor values are not accurate, make sure: +while True: + print(f"📏 Distance: {distance.distance} cm") + sleep_ms(50) +``` -- The sensor lens is clean and free from dust or obstructions. -- All exposed electronics are not touching any conductive surfaces, as this could interfere with readings. -- The object being measured is within the sensor's detection range. +### Key Properties + +- `.distance`: Provides the distance measurement from the sensor (default in cm) + +### Advanced Example - Proximity-Activated System + +```python +from modulino import ModulinoDistance +from time import sleep, ticks_ms + +distance = ModulinoDistance() + +# Configuration +ACTIVATION_DISTANCE = 20 # cm +DEACTIVATION_DISTANCE = 30 # cm +DEBOUNCE_TIME = 500 # milliseconds + +# State tracking +is_activated = False +last_activation_time = 0 +activation_count = 0 + +def check_proximity(): + """Check distance and manage activation state""" + global is_activated, last_activation_time, activation_count + + current_distance = distance.distance + current_time = ticks_ms() + + # Check if we should activate + if not is_activated and current_distance < ACTIVATION_DISTANCE: + # Debounce check + if current_time - last_activation_time > DEBOUNCE_TIME: + is_activated = True + activation_count += 1 + last_activation_time = current_time + print(f"\n✋ ACTIVATED! Object detected at {current_distance} cm") + print(f" Activation count: {activation_count}") + return True + + # Check if we should deactivate + elif is_activated and current_distance > DEACTIVATION_DISTANCE: + is_activated = False + duration = (current_time - last_activation_time) / 1000 + print(f"\n👋 DEACTIVATED after {duration:.1f} seconds") + return False + + return is_activated + +def hand_wave_detector(): + """Detect hand wave gestures""" + samples = [] + sample_time = 50 # ms + wave_threshold = 5 # minimum changes + + print("\nWave your hand in front of the sensor...") + + for _ in range(20): # Collect 1 second of samples + samples.append(distance.distance) + sleep(sample_time / 1000) + + # Detect changes in distance + changes = 0 + for i in range(1, len(samples)): + if abs(samples[i] - samples[i-1]) > 5: # 5cm change threshold + changes += 1 + + if changes >= wave_threshold: + print(f"👋 Wave detected! ({changes} movements)") + return True + + return False + +# Menu system +print("🎯 Distance Sensor Applications") +print("1. Proximity Activation Demo") +print("2. Hand Wave Detection") +print("3. Distance Monitor") + +while True: + choice = input("\nSelect mode (1-3): ") + + if choice == "1": + print(f"\nProximity activation mode") + print(f"Activation: < {ACTIVATION_DISTANCE} cm") + print(f"Deactivation: > {DEACTIVATION_DISTANCE} cm") + + while True: + activated = check_proximity() + if activated: + print(f" Status: ACTIVE | Distance: {distance.distance} cm", end='\r') + else: + print(f" Status: IDLE | Distance: {distance.distance} cm", end='\r') + sleep(0.1) + + elif choice == "2": + print("\nHand wave detection mode") + while True: + if hand_wave_detector(): + print(" Action triggered by wave!") + sleep(0.5) + + elif choice == "3": + print("\nDistance monitoring mode") + while True: + d = distance.distance + # Create visual bar graph + bar_length = min(d // 2, 50) # Scale to max 50 characters + bar = "█" * bar_length + print(f"Distance: {d:4d} cm |{bar}", end='\r') + sleep(0.05) +``` -## Conclusion +## Troubleshooting -The **Modulino Distance** is a digital Time-of-Flight distance sensor that communicates over I²C and follows the Modulino form factor. It includes standard Qwiic connectors for quick, solderless connections and easy daisy-chaining with other modules. Paired with the Modulino library, it makes accessing distance data straightforward, allowing you to focus on experimenting or building your system logic. It's a small, reliable module suited for both quick tests and longer-term setups. +### Sensor Not Reachable -## What Is Next? +If your Modulino's power LED isn't on or the sensor isn't responsive: +- Ensure both the board and the Modulino are connected properly +- Verify that the power LEDs on both are lit +- Check that the QWIIC cable is properly clicked into place -Now that you've learned how to use your Modulino Distance, you're all set to integrate it into your projects! +### Inaccurate Values -- Create a parking assistance system that provides audio feedback as objects get closer, similar to car parking sensors. -- Build a theremin-like musical instrument that changes pitch or volume based on hand movements in front of the sensor. -- Design an automatic dispenser that activates when hands are detected beneath it (for soap, sanitizer, etc.). \ No newline at end of file +If the sensor values are not accurate: +- Ensure the sensor lens is clean and free from dust or obstructions +- Verify the object being measured is within the sensor's detection range +- Check that exposed electronics are not touching conductive surfaces + +## Project Ideas + +- **Parking Assistance System**: Provide audio feedback as objects get closer +- **Theremin Musical Instrument**: Change pitch based on hand movements +- **Automatic Dispenser**: Activate when hands are detected +- **Security System**: Detect when someone approaches a protected area +- **Liquid Level Monitor**: Measure distance to liquid surface in a tank +- **Robot Obstacle Avoidance**: Help robots navigate around objects +- **Interactive Art Installation**: Trigger effects based on viewer proximity +- **Smart Trash Can**: Automatically open lid when someone approaches \ No newline at end of file diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-knob/tutorials/how-knob-ardu/assets/KnobOverview.png b/content/hardware/11.accessories/modulino-nodes/modulino-knob/tutorials/how-knob-ardu/assets/KnobOverview.png new file mode 100644 index 0000000000..5e7a267866 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-knob/tutorials/how-knob-ardu/assets/KnobOverview.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-knob/tutorials/how-knob-ardu/content.md b/content/hardware/11.accessories/modulino-nodes/modulino-knob/tutorials/how-knob-ardu/content.md index 44f4ad3ee5..14c93a7334 100644 --- a/content/hardware/11.accessories/modulino-nodes/modulino-knob/tutorials/how-knob-ardu/content.md +++ b/content/hardware/11.accessories/modulino-nodes/modulino-knob/tutorials/how-knob-ardu/content.md @@ -1,57 +1,55 @@ --- -title: "How To Use The Modulino Knob" -description: "Learn how to get the most out of your Modulino Knob." +title: "Modulino Knob" +description: "Complete guide for the Modulino Knob rotary encoder module." tags: - Modulino + - Knob + - Encoder + - Input - QWIIC - I2C -author: 'Christoher Méndez' +author: 'Christopher Méndez' hardware: - hardware/11.modulinos/modulinos/modulino-knob software: - ide-v2 - web-editor + - micropython --- -The Modulino Knob is a modular sensor based on a quadrature rotary encoder that translates angular motion (rotation) into a digital signal. The sensor value will increase or decrease according to the rotation direction. Also, it includes an SPST switch that is activated when the knob is pressed. +![Knob Overview](assets/KnobOverview.png) -It uses the Modulino form factor, streamlining integration through the I2C protocol. It provides QWIIC connectors and exposed solderable pins (for boards without a QWIIC interface). +The Modulino Knob is a modular sensor based on a quadrature rotary encoder that translates angular motion (rotation) into a digital signal. The sensor value will increase or decrease according to the rotation direction. Also, it includes an SPST switch that is activated when the knob is pressed. -## General Characteristics +## Hardware Overview -The Modulino Knob has the following measurement specifications: +### General Characteristics +The Modulino Knob has the following measurement specifications: -| **Parameter** | **Condition** | **Minimum** | **Typical** | **Maximum** | **Unit** | -| -------------- | ------------- | ----------- | ---------------- | ----------- | -------- | -| Sensor | Angle | - | 360 (continuous) | - | ° | -| Steps | - | - | 30 | - | - | -| Resolution | - | - | 12 | - | bit | +| Parameter | Condition | Minimum | Typical | Maximum | Unit | +|------------|-----------|---------|------------------|---------|------| +| Sensor | Angle | - | 360 (continuous) | - | ° | +| Steps | - | - | 30 | - | - | +| Resolution | - | - | 12 | - | bit | ### Sensor Details -The PEC11J-9215F-S0015 rotary encoder is the core component of this module. This sensor output is processed by an STM32C011F4 microcontroller for digital communication (I2C), meaning that the encoder is communicated through the I2C pins using the mentioned microcontroller as an intermediary. +The PEC11J-9215F-S0015 rotary encoder is the core component of this module. This sensor output is processed by an STM32C011F4 microcontroller for digital communication (I²C), meaning that the encoder is communicated through the I²C pins using the mentioned microcontroller as an intermediary. The default address for the Module is: -| **Modulino I2C Address** | **Hardware I2C Address** | -| ------------------------ | ------------------------ | -| 0x76 | 0x3A | - -When scanning for I²C address on the bus, you might find the modulino using the **Hardware I²C Address**. However, you should always use the **Modulino I²C Address** when using the official Modulino library. - -Later in this article we teach how to [change the address](#how-to-change-i2c-address). +| Modulino I²C Address | Hardware I²C Address | +|----------------------|----------------------| +| 0x76 | 0x3A | +The I²C address can be changed via software configuration. -## Pinout - -The rotary encoder is the core component of this module. This input device is controlled by an onboard STM32 microcontroller, which supports digital communication (I²C), meaning it connects directly to the I²C bus on the module without requiring additional conversion circuitry. +### Pinout ![Arduino Knob Pinout](assets/KnobPinouts.png) -The board also includes direct connections to the rotary encoder bypassing the built-in microcontroller. - -### 1x10 Header +#### 1x10 Header | Pin | Function | |-------|----------------| @@ -66,44 +64,29 @@ The board also includes direct connections to the rotary encoder bypassing the b | PA0 | Encoder A | | PA1 | Encoder B | -- **PA2: Button:**This pin connects directly to the built-in button of the rotary encoder. -- **GND: Ground:**Ground connection for power and signal reference. -- **3V3: Power:**3.3 V power supply input. -- **PF2: RESET:**The reset pin for the microcontroller, which can be used to reset the system. -- **SWCLK: SWD Clock:**Used for providing the clock signal in the SWD interface. -- **SWDIO: SWD Data:**Used for debugging, as part of the Serial Wire Debug (SWD) interface. -- **TX1: USART Transmit:**Used for transmitting data over UART communication. -- **RX1: USART Receive:**Used for receiving data over UART communication. -- **PA0: Encoder A:**These pins connect directly to the rotary encoder's quadrature outputs. -- **PA1: Encoder B:**These pins connect directly to the rotary encoder's quadrature outputs. +The board includes direct connections to the rotary encoder (PA0, PA1, PA2) bypassing the built-in microcontroller. -### 1x4 Header (I2C) +#### 1x4 Header (I2C) -The pinout for the Modulino Knob is shown below. While the recommended connection method is via the QWIIC connectors, this solderable header provides a connection option when using the modulino with a non-QWIIC compatible board. - -| Pin | Function | +| Pin | Function | |-------|--------------| -| GND | Ground | +| GND | Ground | | 3.3 V | Power Supply | -| SDA | I²C Data | -| SCL | I²C Clock | - -## Power Specifications +| SDA | I²C Data | +| SCL | I²C Clock | -The board must be powered **only** by +3.3 VDC when using the solderable pins or the QWIIC interface as per the standard. +### Power Specifications | Parameter | Typical | Unit | -| --------------- | ------- | ---- | +|-----------------|---------|------| | Supply Voltage | 3.3 | V | | Average Current | 3.4 | mA | -The module additionally includes a power LED that draws 1 mA and turns on as soon as it is powered. J1 (Qwiic connector), J2 (Qwiic connector), and the headers all share the same power branch. The power distribution of the module is therefore as follows: +The module includes a power LED that draws 1 mA and turns on as soon as it is powered. -![Power Tree Modulino Knob](assets/Modulino_Knob_Power_Tree.png) +### Schematic -## Schematic - -The Modulino Knob uses a simple circuit, as shown in the schematic below: +The Modulino Knob features a robust circuit design for rotational input and button detection. ![Full Schematic Modulino Knob](assets/schematic.png) @@ -113,80 +96,20 @@ You can connect to the I²C pins (SDA and SCL) using either the **QWIIC connecto There's also a small power LED indicator (green) that lights up when the board is on. -You can grab the full schematic and PCB files from the [Modulino Knob](https://docs.arduino.cc/hardware/modulinos/modulino-knob) product page. - -## How To Connect Your Modulino - -The easiest and most reliable way to connect your Modulino is through the QWIIC Connect System. It's plug-and-play, uses standard I²C, and makes it easy to join multiple modules. If your board supports QWIIC, this is the recommended way to go. Note that the dedicated I²C pins will differ from board to board meaning it is always a good idea to check your specific model. - -![Modulino Wiring Options QWIIC(A - recommended) and Header(B)](assets/connection-guide-knob.png) - -### QWIIC Connector - -Whenever available, the **QWIIC Connect System** is the preferred method. Connecting to the Modulino is extremely simple, just use a standard QWIIC cable to connect your board to either of the QWIIC connectors on the Modulino. Because the cable and connectors are polarized, there is no need to worry about accidentally swapping connections. - -QWIIC is a plug-and-play I²C Connect System that uses standardized 4-pin connectors: - -- GND -- 3.3V -- SDA (Data) -- SCL (Clock) - -![Connection Guide QWIIC](assets/connection-guide-knob-qwiic.png) - -The Modulino features two QWIIC connectors, which are internally connected in parallel. This means you can daisy-chain multiple modules easily by connecting additional QWIIC cables between them. - -### Solderable Header - -When QWIIC is not available, you can use the exposed solderable pins on the module. You can solder pins to the unpopulated pads; just remember the pinout provided in this guide to connect to the right pins of your board. - -![Connection Guide Solder Pads](assets/connection-guide-knob-jumper.png) - -### Daisy-Chaining Multiple Modulino Nodes - -Regardless of whether you connect the first Modulino via QWIIC or through the solderable pins, you can still take advantage of the extra QWIIC connector to daisy-chain additional modules. Each Modulino includes two QWIIC connectors wired in parallel, allowing you to connect one module to the next in a chain. As long as each module is configured with a unique I²C address, they can all communicate on the same bus. This approach keeps your setup clean, modular, and expandable without adding extra wiring complexity. - -![Modulino Wiring Options](assets/connection-guide-knob-qwiic-chain.png) - -***The number of modules you can connect will depend on what modules you are chaining together, as this system allows for multiple sensors from different manufacturers to be added. Also, the cables you use for these connections will play a significant role in the setup's performance. Ensure your cables are properly connected and capable of handling the required data transfer. -Each module should have a unique address on a chain if you plan to address them individually. Later in this article we teach how to [change the address](#how-to-change-i2c-address). Multiple modules with the same address will cause conflicts on the I²C bus and will not allow you to address them individually.*** - -## How To Use Your Modulino - -### Installing The Modulino Library - -You need the official Modulino library available [here](https://github.com/arduino-libraries/Modulino) to use the Modulino Knob. - -With the Arduino IDE, you get some tools that make adding a library easier. To learn how to install the IDE, please visit our [page](https://docs.arduino.cc/micropython/first-steps/install-guide/). - -After opening the IDE, a tab should be visible on the left. Press the book icon for "library" as highlighted in the image. +You can grab the full schematic and PCB files from the [Modulino Knob product page](https://docs.arduino.cc/hardware/modulinos/modulino-knob). -![IDE Library Tab](assets/library-menu.png) +## Programming with Arduino -You can now search for the library `Modulino` by filling in the `Filter your search` text box. A prompt might appear saying that additional dependencies are required. This is not a problem, as they will be automatically added when you confirm the prompt. +The Modulino Knob is fully compatible with the Arduino IDE and the official Modulino library. The following examples showcase how to read rotational input, detect button presses, and implement user interface controls in your Arduino projects. -![Add Dependencies Prompt](assets/library-dependencies.png) +### Prerequisites -The libraries should now start to install. A message will appear after the installation is successful. +- Install the Modulino library via the Arduino IDE Library Manager +- Connect your Modulino Knob via QWIIC or solderable headers -The process should be like this: +For detailed instructions on setting up your Arduino environment and installing libraries, please refer to the [Getting Started with Modulinos guide](link-to-generic-guide). -![Library Install](assets/library-install.gif) - -### Getting Knob Data - -Data can be obtained from the sensor using the `Modulino` library. - -For the **Knob** there are two important functions: - -- `get()`: Returns a numerical value relative to the knob rotation. -- `isPressed()`: Returns the state of the knob built-in button. -- `knob.get();` retrieves a unitless value relative to the knob rotation. -- `knob.isPressed();` retrieves the knob button state. -- `knob.set();` changes the initial position of the encoder. -- `Modulino.begin();`: By default the Modulino library uses ```Wire1``` if your connection is in a different Wire you will have to edit it, check [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/) (by default the Modulino library uses ```Wire1``` if your board model has a different pinout for the dedicated I²C pins you might have to edit it. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/)) for the library's hardware compatibility. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/). - -Here is an example sketch of how to implement these functions to acquire data: +### Basic Example ```arduino #include @@ -209,45 +132,268 @@ void loop(){ if(click){ Serial.println("Clicked!"); } +} +``` + +### Key Functions + +- `get()`: Returns a numerical value relative to the knob rotation +- `isPressed()`: Returns the state of the knob's built-in button +- `set()`: Changes the initial position of the encoder + +### Advanced Example - Menu Navigation + +```arduino +#include + +ModulinoKnob knob; +// Menu configuration +const int MENU_ITEMS = 5; +String menuOptions[] = {"Settings", "Display", "Audio", "Network", "Exit"}; +int currentSelection = 0; +int lastPosition = 0; +bool lastButtonState = false; + +void setup() { + Serial.begin(9600); + Modulino.begin(); + knob.begin(); + + // Set initial position to 0 + knob.set(0); + lastPosition = 0; + + displayMenu(); +} + +void displayMenu() { + Serial.println("\n======= MENU ======="); + for (int i = 0; i < MENU_ITEMS; i++) { + if (i == currentSelection) { + Serial.print("> "); // Selection indicator + } else { + Serial.print(" "); + } + Serial.println(menuOptions[i]); + } + Serial.println("=================="); + Serial.println("Rotate to navigate, press to select"); +} + +void selectMenuItem() { + Serial.print("\n✓ Selected: "); + Serial.println(menuOptions[currentSelection]); + + // Handle selection + switch(currentSelection) { + case 0: + Serial.println("Opening Settings..."); + break; + case 1: + Serial.println("Opening Display options..."); + break; + case 2: + Serial.println("Opening Audio settings..."); + break; + case 3: + Serial.println("Opening Network configuration..."); + break; + case 4: + Serial.println("Exiting menu..."); + break; + } + + delay(1000); + displayMenu(); +} + +void loop() { + int currentPosition = knob.get(); + bool buttonPressed = knob.isPressed(); + + // Check for rotation + int rotation = currentPosition - lastPosition; + + if (rotation != 0) { + // Update selection based on rotation direction + if (rotation > 0) { + currentSelection++; + if (currentSelection >= MENU_ITEMS) { + currentSelection = 0; // Wrap around + } + } else { + currentSelection--; + if (currentSelection < 0) { + currentSelection = MENU_ITEMS - 1; // Wrap around + } + } + + lastPosition = currentPosition; + displayMenu(); + } + + // Check for button press (on release to avoid multiple triggers) + if (!buttonPressed && lastButtonState) { + selectMenuItem(); + } + + lastButtonState = buttonPressed; + + delay(50); // Small delay for debouncing } ``` -### How To Change I2C Address +## Programming with MicroPython -An example sketch, AddressChanger, is also included with the library inside the `Utilities` folder and available [here](https://github.com/arduino-libraries/Modulino/blob/main/examples/Utilities/AddressChanger/AddressChanger.ino). This sketch changes the I²C address at a software level on the Module's microcontroller. +The Modulino Knob is fully compatible with MicroPython through the official Modulino MicroPython library. The following examples demonstrate how to read rotational input, handle button events, and create interactive controls in your MicroPython projects. -![Example location on the IDE](assets/AdressChangeIDE.png) +### Prerequisites -- Connect the module to your board, remove any other modules that might be in the chain. Connection must be via I²C. -- Upload the sketch. -- Open the Serial Monitor. -- Text should now appear. Make sure the correct bauld-rate is selected if the displayed characters seem corrupted. - - ![Expected console output](assets/adressChanger.png) +- Install the Modulino MicroPython library +- Ensure Arduino Lab for MicroPython is installed -- Select the address and confirm. Valid I²C addresses range from 0x08 to 0x77 (7-bit values in hexadecimal format, e.g., 0x42). -- Your address should now have changed. Make sure to take note of the selected address. +For detailed instructions on setting up your MicroPython environment and installing packages, please refer to the [Getting Started with Modulinos guide](link-to-generic-guide). -To keep track of the address in use the module has a white rectangle on the back. Feel free to use this to write the address that was chosen. +### Basic Example -When using a custom address in your sketch, you'll need to specify this address when creating the module object. For example: +```python +from modulino import ModulinoKnob +from time import sleep -```arduino -ModulinoKnob knob(0x3E); // Replace 0x3E with your specific address +knob = ModulinoKnob() +knob.value = 0 # (Optional) Set an initial value +knob.range = (-10, 10) # (Optional) Set a value range + +def on_release(): + knob.reset() + print("🔘 Released! Knob's value was reset.") + +knob.on_press = lambda: print("🔘 Pressed!") +knob.on_release = on_release +knob.on_rotate_clockwise = lambda steps, value: print(f"🎛️ Rotated {steps} steps clockwise! Value: {value}") +knob.on_rotate_counter_clockwise = lambda steps, value: print(f"🎛️ Rotated {steps} steps counter clockwise! Value: {value}") + +while True: + if(knob.update()): + print("👀 Knob value or state changed!") + + sleep(0.1) +``` + +### Key Functions and Properties + +- `.value`: Set/get the sensor's current value +- `.range`: Set the minimum and maximum possible value +- `.on_press`: Callback for button press +- `.on_release`: Callback for button release +- `.on_rotate_clockwise`: Callback for clockwise rotation +- `.on_rotate_counter_clockwise`: Callback for counter-clockwise rotation +- `.update()`: Check for new values and trigger callbacks +- `.reset()`: Reset the encoder value + +### Advanced Example - Volume Control with Visual Feedback + +```python +from modulino import ModulinoKnob +from time import sleep + +knob = ModulinoKnob() + +# Volume control configuration +knob.value = 50 # Start at 50% +knob.range = (0, 100) # Volume range 0-100% + +# State tracking +is_muted = False +last_volume = 50 + +def draw_volume_bar(volume, muted=False): + """Draw a visual representation of the volume""" + bar_length = 20 + filled = int((volume / 100) * bar_length) + empty = bar_length - filled + + if muted: + bar = "[" + "X" * bar_length + "]" + status = "🔇 MUTED" + else: + bar = "[" + "█" * filled + "░" * empty + "]" + if volume == 0: + status = "🔈" + elif volume < 33: + status = "🔉" + elif volume < 66: + status = "🔊" + else: + status = "🔊" + + print(f"\rVolume: {bar} {volume:3d}% {status} ", end="") + +def toggle_mute(): + """Toggle mute state""" + global is_muted, last_volume + + is_muted = not is_muted + + if is_muted: + last_volume = knob.value + knob.value = 0 + print("\n🔇 Muted!") + else: + knob.value = last_volume + print(f"\n🔊 Unmuted! Volume: {last_volume}%") + +def volume_change(steps, value): + """Handle volume changes""" + global is_muted + + if is_muted: + is_muted = False # Unmute when rotating + + draw_volume_bar(value) + +# Configure callbacks +knob.on_press = toggle_mute +knob.on_rotate_clockwise = volume_change +knob.on_rotate_counter_clockwise = volume_change + +print("🎛️ Volume Control System") +print("Rotate: Change volume | Press: Mute/Unmute") +print("-" * 40) + +# Initial display +draw_volume_bar(knob.value) + +# Main loop +while True: + knob.update() + sleep(0.01) ``` +## Troubleshooting -## Conclusion +### Knob Not Responding -The **Modulino Knob** provides a simple solution for UI interface, volume control or rotational measurement in any project. With its **I2C interface**, compact **Modulino form factor**, and **robustness**, it seamlessly integrates into both beginner and advanced applications. +If your Modulino's power LED isn't on or the knob isn't responsive: +- Ensure both the board and the Modulino are connected properly +- Verify that the power LEDs on both are lit +- Check that the QWIIC cable is properly clicked into place -By leveraging the **Modulino library**, users can quickly access sensor data and implement functionalities such as **user interface control and angle measurement tool**. With just a few lines of code, you can start **controlling your projects**, making it easier than ever to bring intelligent sensing to your applications. +### Erratic Values -## What Is Next? +If the encoder values jump unexpectedly: +- Check for loose connections +- Ensure the module is not near sources of electromagnetic interference +- Try adjusting the debounce time if using button events -After mastering the basics of the Modulino Knob, try these project ideas: +## Project Ideas -- Calculate what is the encoder rotation angle per step to convert the arbitrary output into a rotation angle output. -- Control the Arduino onboard LED with the press of the knob button. -- Use the Modulino Knob to control the navigation on a UI display on an LCD or OLED screen. \ No newline at end of file +- **Volume Control**: Adjust audio levels with tactile feedback +- **Menu Navigation**: Navigate through LCD or OLED display menus +- **Parameter Adjustment**: Fine-tune values in real-time applications +- **Game Controller**: Use rotation for steering or aiming in games +- **Light Dimmer**: Control LED brightness smoothly +- **Frequency Tuner**: Adjust frequencies for signal generators +- **Camera Control**: Pan/tilt control for camera systems +- **Smart Thermostat**: Set temperature with precise control \ No newline at end of file diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-movement/tutorials/how-movement-ardu/assets/MovementOverview.png b/content/hardware/11.accessories/modulino-nodes/modulino-movement/tutorials/how-movement-ardu/assets/MovementOverview.png new file mode 100644 index 0000000000..1dca7e801f Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-movement/tutorials/how-movement-ardu/assets/MovementOverview.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-movement/tutorials/how-movement-ardu/content.md b/content/hardware/11.accessories/modulino-nodes/modulino-movement/tutorials/how-movement-ardu/content.md index d7543e2756..95e7a39755 100644 --- a/content/hardware/11.accessories/modulino-nodes/modulino-movement/tutorials/how-movement-ardu/content.md +++ b/content/hardware/11.accessories/modulino-nodes/modulino-movement/tutorials/how-movement-ardu/content.md @@ -1,8 +1,12 @@ --- -title: "How To Use The Modulino Movement" -description: "Learn how to get the most out of your Modulino Movement." +title: "Modulino Movement" +description: "Complete guide for the Modulino Movement 6-axis IMU sensor module." tags: - Modulino + - Movement + - IMU + - Accelerometer + - Gyroscope - QWIIC - I2C author: 'Pedro Sousa Lima' @@ -11,16 +15,18 @@ hardware: software: - ide-v2 - web-editor + - micropython --- -The Modulino Movement is a modular sensor that measures acceleration and angular velocity, making it perfect to add motion sensing to your projects! The Modulino form factor is shaped with two QWIIC connectors and the I²C protocol integration, allowing the connection and programming of multiple Modulino nodes in a very simple way. In addition to the QWIIC's connectors, the Modulino nodes also expose solderable pins that can be used in multiple ways and make them compatible with boards that are not QWIIC compatible. +![Movement Overview](assets/MovementOverview.png) +The Modulino Movement is a modular sensor that measures acceleration and angular velocity, making it perfect to add motion sensing to your projects! It provides 6-axis motion detection through its integrated accelerometer and gyroscope. -The Modulino form factor is shaped with two QWIIC connectors and the I²C protocol integration, allowing the connection and programming of multiple modulinos in a very simple way. In addition to the QWIIC's connectors, the Modulinos also expose solderable pins that can be used in multiple ways and make them compatible with boards that are not QWIIC compatible. +## Hardware Overview -## General Characteristics +### General Characteristics -The Modulino Movement is capable of measuring acceleration and angular velocity. Take a look at the following table to know more about its measuring ranges: +The Modulino Movement is capable of measuring acceleration and angular velocity with the following specifications: | Parameter | Condition | Minimum | Typical | Maximum | Unit | |---------------------------------|-------------------------|---------|---------|---------|----------| @@ -37,24 +43,20 @@ The Modulino Movement is capable of measuring acceleration and angular velocity. ### Sensor Details The LSM6DSOXTR sensor from STMicroelectronics is the core component of this module. This 6-axis IMU (accelerometer and gyroscope) natively supports digital communication (I²C and SPI), meaning it connects directly to the I²C bus on the module without requiring additional conversion circuitry. + The default address for the Module is: | Modulino I²C Address | Hardware I²C Address | |----------------------|----------------------| | 0x6A or 0x7E | 0x6A or 0x7E | -When scanning for I²C address on the bus, you might find the modulino using the **Hardware I²C Address**. However, you should always use the **Modulino I²C Address** when using the official Modulino library. -Later in this article we teach how to [change the address](#how-to-change-i2c-address). - -## Pinout +The address can be changed through hardware modification (see the generic guide for details). -The pinout for the Modulino Movement is shown below. Please note that the exposed solderable pins are directly connected to the QWIIC connectors using the same I²C interface. +### Pinout ![Arduino Movement Pinout](assets/MovementPinouts.png) -Depending on the board connected to the modulino, the I²C pin names to program it may differ. Please check the [board tutorials](https://docs.arduino.cc/hardware/) on your modulino's compatible board or the [Modulino library](https://github.com/arduino-libraries/Modulino/tree/main/docs) to learn more. - -### 1x10 Header +#### 1x10 Header | Pin | Function | |---------|------------------| @@ -69,29 +71,16 @@ Depending on the board connected to the modulino, the I²C pin names to program | SDOAUX | Auxiliary Output | | OCSAUX | Auxiliary Output | -- **VDDIO: Power** – I/O voltage supply pin for the sensor. -- **GND: Ground** – Ground connection for power and signal reference. -- **INT1: Interrupt 1** – Programmable interrupt output pin. -- **INT2: Interrupt 2** – Programmable interrupt output pin. -- **SDO/SA0: SPI Data Out** – SPI data output pin, also used as I2C address selection. -- **SCx: SPI Clock** – Clock signal for SPI communication. -- **SDx: SPI Data** – SPI data input pin. -- **CS: SPI Chip Select** – Chip select pin for SPI communication. -- **SDOAUX: Auxiliary Output** – Auxiliary data output pin. -- **OCSAUX: Auxiliary Output** – Auxiliary output control signal pin. - -### 1x4 Header (I2C) +#### 1x4 Header (I2C) | Pin | Function | |-------|--------------| | GND | Ground | | 3.3 V | Power Supply | -| SDA | I2C Data | -| SCL | I2C Clock | +| SDA | I²C Data | +| SCL | I²C Clock | -## Power Specifications - -The board is typically powered by +3.3 VDC when using the QWIIC interface as per the I²C standard. +### Power Specifications | Parameter | Condition | Minimum | Typical | Maximum | Unit | |-----------------------------------------------|---------------------|---------|-------------|---------|------| @@ -102,134 +91,14 @@ The board is typically powered by +3.3 VDC when using the QWIIC interface as per | Accelerometer Current (Low Power Mode) | ODR = 50 Hz | - | 26 | - | µA | | Accelerometer Current (Ultra-Low Power Mode) | ODR = 50 Hz | - | 9.5 | - | µA | -The module additionally includes a power LED that draws 1 mA and turns on as soon as it is powered. J1 (Qwiic connector), J2 (Qwiic connector), and the headers all share the same power branch. The power distribution of the module is therefore as follows: - -![Power Tree Modulino Movement](assets/Modulino_Movement_Power_Tree.png) - -## Schematic - -The Modulino Movement uses a simple circuit, as shown in the schematic below: - -![Full Schematic Modulino Movement](assets/schematic.png) - -The main component is the **LSM6DSOXTR** sensor (U1), which handles both acceleration and gyroscope measurements, as well as I²C communication. - -You can connect to the I²C pins (SDA and SCL) using either the **QWIIC connectors** (J1 and J2, this is the recommended method) or the **solderable pins** (J4). The board runs on **3.3V**, which comes from the QWIIC cable or the **3V3 pin** on J4. - -There's also a small power indicator LED that lights up when the board is on. - -Some options for customizing the module's features via onboard solder jumpers are available: - -### **VDDIO Independence:** - -- By default, **VDDIO is connected to +3V3**. -- To make **VDDIO independent**, cut the corresponding solder jumper. - -### SPI Mode Selection: - -- The LSM6DSOXTR supports both **3-wire and 4-wire SPI**. -- You can configure SPI communication and connect additional sensors by cutting or soldering the appropriate jumpers. Please take a look at the IMU's datasheet for more information. - -You can grab the full schematic and PCB files from the [Modulino Movement](https://docs.arduino.cc/hardware/modulinos/modulino-movement) product page. - -## How To Connect Your Modulino - -The easiest and most reliable way to connect your Modulino is through the QWIIC Connect System. It's plug-and-play, uses standard I²C, and makes it easy to join multiple modules. If your board supports QWIIC, this is the recommended way to go. Note that the dedicated I²C pins will differ from board to board meaning it is always a good idea to check your specific model. - -If your board doesn't have a QWIIC connector, you can still access the same I²C bus and power the module using the solderable header pads just make sure you wire it to 3.3V and match the I²C pinout. - -![Modulino Wiring Options QWIIC(A - recommended) and Header(B)](assets/connection-guide-movement.png) - -### QWIIC Connector - -Whenever available, the **QWIIC Connect System** is the preferred method. Connecting to the Modulino is extremely simple, just use a standard QWIIC cable to connect your board to either of the QWIIC connectors on the Modulino. Because the cable and connectors are polarized, there is no need to worry about accidentally swapping connections. - -QWIIC is a plug-and-play I²C Connect System that uses standardized 4-pin connectors: - -- GND -- 3.3V -- SDA (Data) -- SCL (Clock) +## Programming with Arduino -![Connection Guide QWIIC](assets/connection-guide-movement-qwiik.png) +### Prerequisites -The Modulino features two QWIIC connectors, which are internally connected in parallel. This means you can daisy-chain multiple modules easily by connecting additional QWIIC cables between them. +- Install the Modulino library via the Arduino IDE Library Manager +- Connect your Modulino Movement via QWIIC or solderable headers -When connecting multiple I²C devices, address conflicts may occur if two or more devices share the same default I²C address. The Modulino addresses this potential issue by allowing you to select a different address through a simple hardware modification. We cover this process in detail in the [**Changing I²C Address**](#changing-i2c-address) section, enabling you to integrate multiple identical modules or different devices that share the same default address in your project. - -### Solderable Header - -When QWIIC is not available, you can use the exposed solderable pins on the module. You can solder pins to the unpopulated pads; just remember the pinout provided in this guide to connect to the right pins of your board. - -![Connection Guide Solder Pads](assets/connection-guide-movement-jumper.png) - -## Daisy-Chaining Multiple Modulino Nodes - -Regardless of whether you connect the first Modulino via QWIIC or through the solderable pins, you can still take advantage of the extra QWIIC connector to daisy-chain additional modules. Each Modulino includes two QWIIC connectors wired in parallel, allowing you to connect one module to the next in a chain. As long as each module is configured with a unique I²C address, they can all communicate on the same bus as long as you select the correct I²C pins depending on your board. This approach keeps your setup clean, modular, and expandable without adding extra wiring complexity. - -![Modulino Wiring Options](assets/connection-guide-movement-qwiic-chain.png) - -***The number of modules you can connect will depend on what modules you are chaining together, as this system allows for multiple sensors from different manufacturers to be added. Also, the cables you use for these connections will play a significant role in the setup's performance. Ensure your cables are correctly connected and capable of handling the required data transfer. -Each module should have a unique address on a chain if you plan to address them individually. Later in this article we teach how to [change the address](#how-to-change-i2c-address). Multiple modules with the same address will cause conflicts on the I²C bus and will not allow you to address them individually.*** - -### Changing I2C Address - -The Modulino Movement can be configured to use an alternative I2C address (0x6B) instead of the default address (0x6A). To change the address, follow these steps carefully: - -1. Disconnect all power from the module -2. Locate the address selection solder jumpers on the back of the board -3. Cut the trace on the jumper marked **Default** (0x6A) -4. Solder closed the jumper marked **0x6B** - -After completing these modifications, your module will use the new address (0x6B) when powered on again. - -**IMPORTANT**: Ensure the module remains unpowered during this entire process. Never have both jumpers closed simultaneously when power is applied, as this will create a short circuit between power and ground that could damage your module. - -![I2C Address Change](assets/I2C-change-movement.png) - -When using a custom address in your sketch, you'll need to specify this address when creating the module object. For example: -```arduino -ModulinoMovement movement(0x7E); -``` - - - -## How To Use Your Modulino - -### Installing The Modulino Library - -You need the official Modulino library available [here](https://docs.arduino.cc/libraries/modulino/) to use the Modulino Movement. With the Arduino IDE you get some tools that make adding a library easier. To learn how to install the IDE please visit our [page](https://www.support.arduino.cc/hc/en-us/articles/360019833020-Download-and-install-Arduino-IDE). - -After opening the IDE, a tab should be visible on the left. Press the book icon for "library" as highlighted in the image. - -![IDE Library Tab](assets/IDE-Left-Tab.png) - -You can now look for the library ```Modulino``` by filling in the ```Filter your search``` textbox. - -A prompt might appear saying that additional dependencies are required. This is not a problem, as they will be automatically added when you confirm the prompt. - -![Add Dependencies Prompt](assets/library-dependencies.png) - -The process should look like this: - -![Library Install](assets/library-install.gif) - -A message will appear after the installation is successful. - -### Getting Acceleration Data - -Getting data from the sensor is fairly simple using the ```Modulino``` library. For the **Modulino Movement** there are four important functions: - -- ```update()```: Updates the sensor readings. -- ```getX()```: Retrieves the acceleration value on the **X-axis** in **g**. -- ```getY()```: Retrieves the acceleration value on the **Y-axis** in **g**. -- ```getZ()```: Retrieves the acceleration value on the **Z-axis** in **g**. -- ```getRoll()```: Retrieves the angular rotation around the X-axis in **dps**. -- ```getPitch()```: Retrieves the angular rotation around the Y-axis in **dps**. -- ```getYaw()```: Retrieves the angular rotation around the Z-axis in **dps**. -- ```Modulino.begin();```: By default the Modulino library uses ```Wire1``` if your connection is in a different Wire you will have to edit it, check [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/) (by default the Modulino library uses ```Wire1``` if your board model has a different pinout for the dedicated I²C pins you might have to edit it. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/)) for the library's hardware compatibility. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/). - -Here is an example sketch of how to implement these functions to acquire data and show it using the serial monitor: +### Basic Example ```arduino #include "Modulino.h" @@ -237,11 +106,9 @@ Here is an example sketch of how to implement these functions to acquire data an // Create a ModulinoMovement ModulinoMovement movement; - float x, y, z; float roll, pitch, yaw; - void setup() { Serial.begin(9600); // Initialize Modulino I2C communication @@ -284,43 +151,312 @@ void loop() { } ``` -The code example provided shows how to initialize the sensor, read the acceleration data, and display it on the serial monitor. The data is continuously updated, showing the current acceleration values in real time. +### Key Functions -It can be easily adapted to trigger actions at certain movement thresholds or to detect specific motion patterns in your projects. +- `update()`: Updates the sensor readings +- `getX()`, `getY()`, `getZ()`: Retrieve acceleration values in g +- `getRoll()`, `getPitch()`, `getYaw()`: Retrieve angular rotation in dps -## Troubleshooting +### Advanced Example - Motion Detection System -### Sensor Not Reachable +```arduino +#include "Modulino.h" -If your Modulino's power LED isn't on or the sensor isn't responsive, first check that the board is properly connected: +ModulinoMovement movement; -- Ensure both the board and the Modulino are connected to your computer, and that the power LEDs on both are lit. -- If the issue persists, make sure the Qwiic cable is properly clicked into place. +// Motion detection thresholds +const float MOTION_THRESHOLD = 0.15; // g units for acceleration +const float ROTATION_THRESHOLD = 20.0; // degrees per second -### Library Not Installed Properly +// Calibration variables +float baseX = 0, baseY = 0, baseZ = 1.0; // Expect 1g on Z when flat +float baseRoll = 0, basePitch = 0, baseYaw = 0; +bool isCalibrated = false; -If you encounter an issue with the `#include "modulino.h"` command, verify that the Modulino library is correctly installed: +// Motion state tracking +bool inMotion = false; +unsigned long motionStartTime = 0; +unsigned long stillStartTime = 0; +const unsigned long STILL_TIMEOUT = 2000; // 2 seconds to detect stillness -- Check your IDE to ensure the library is installed and up-to-date. -- Re-install the library through the Library Manager. +void setup() { + Serial.begin(9600); + Modulino.begin(); + movement.begin(); + + Serial.println("Motion Detection System"); + Serial.println("======================"); + Serial.println("Keep device still for calibration..."); + + delay(2000); + calibrateSensor(); +} -### Inaccurate Values +void calibrateSensor() { + const int samples = 50; + float sumX = 0, sumY = 0, sumZ = 0; + float sumRoll = 0, sumPitch = 0, sumYaw = 0; + + for (int i = 0; i < samples; i++) { + movement.update(); + sumX += movement.getX(); + sumY += movement.getY(); + sumZ += movement.getZ(); + sumRoll += movement.getRoll(); + sumPitch += movement.getPitch(); + sumYaw += movement.getYaw(); + delay(20); + } + + baseX = sumX / samples; + baseY = sumY / samples; + baseZ = sumZ / samples; + baseRoll = sumRoll / samples; + basePitch = sumPitch / samples; + baseYaw = sumYaw / samples; + + isCalibrated = true; + Serial.println("✓ Calibration complete!"); + Serial.println(); +} + +void detectMotion() { + movement.update(); + + // Calculate deltas from baseline + float deltaX = abs(movement.getX() - baseX); + float deltaY = abs(movement.getY() - baseY); + float deltaZ = abs(movement.getZ() - baseZ); + float deltaRoll = abs(movement.getRoll() - baseRoll); + float deltaPitch = abs(movement.getPitch() - basePitch); + float deltaYaw = abs(movement.getYaw() - baseYaw); + + // Check if any threshold is exceeded + bool motionDetected = (deltaX > MOTION_THRESHOLD || + deltaY > MOTION_THRESHOLD || + deltaZ > MOTION_THRESHOLD || + deltaRoll > ROTATION_THRESHOLD || + deltaPitch > ROTATION_THRESHOLD || + deltaYaw > ROTATION_THRESHOLD); + + // State machine for motion detection + if (motionDetected && !inMotion) { + // Motion just started + inMotion = true; + motionStartTime = millis(); + Serial.println("🏃 MOTION DETECTED!"); + + // Identify type of motion + if (deltaRoll > ROTATION_THRESHOLD || deltaPitch > ROTATION_THRESHOLD) { + Serial.println(" Type: Rotation"); + } + if (deltaX > MOTION_THRESHOLD || deltaY > MOTION_THRESHOLD) { + Serial.println(" Type: Linear movement"); + } + if (deltaZ > MOTION_THRESHOLD * 2) { + Serial.println(" Type: Vertical movement"); + } + } + else if (!motionDetected && inMotion) { + // Motion might have stopped + if (stillStartTime == 0) { + stillStartTime = millis(); + } + else if (millis() - stillStartTime > STILL_TIMEOUT) { + // Device has been still for timeout period + inMotion = false; + unsigned long duration = (millis() - motionStartTime) / 1000; + Serial.print("✋ Motion stopped. Duration: "); + Serial.print(duration); + Serial.println(" seconds"); + stillStartTime = 0; + } + } + else if (motionDetected && inMotion) { + // Still in motion, reset still timer + stillStartTime = 0; + } +} + +void loop() { + if (isCalibrated) { + detectMotion(); + delay(50); + } +} +``` + +## Programming with MicroPython -If the sensor values are not accurate, make sure: +The Modulino Movement is fully compatible with MicroPython through the official Modulino MicroPython library. The following examples demonstrate how to read motion data from the 6-axis IMU and implement motion detection features in your MicroPython projects. -- The sensor is not placed on an unstable surface that might cause unwanted vibrations. -- All exposed electronics are not touching any conductive surfaces, as this could interfere with readings. -- The board is mounted securely when measuring precise movements. +### Prerequisites -## Conclusion +- Install the Modulino MicroPython library +- Ensure Arduino Lab for MicroPython is installed -The **Modulino Movement** is a digital 6-axis IMU sensor that communicates over I²C and follows the Modulino form factor. It includes standard Qwiic connectors for quick, solderless connections and easy daisy-chaining with other modules. Paired with the Modulino library, it makes accessing motion data straightforward, allowing you to focus on experimenting or building your system logic. It's a small, reliable module suited for both quick tests and longer-term setups. +For detailed instructions on setting up your MicroPython environment and installing packages, please refer to the [Getting Started with Modulinos guide](link-to-generic-guide). -## What Is Next? +### Basic Example -Now that you've learned how to use your Modulino Movement, you're all set to integrate it into your projects! +```python +from modulino import ModulinoMovement +from time import sleep_ms + +movement = ModulinoMovement() + +while True: + acc = movement.accelerometer + gyro = movement.gyro + + print(f"🏃 Accelerometer: x:{acc.x:>8.3f} y:{acc.y:>8.3f} z:{acc.z:>8.3f} g") + print(f"🌀 Gyroscope: x:{gyro.x:>8.3f} y:{gyro.y:>8.3f} z:{gyro.z:>8.3f} dps") + print("") + sleep_ms(100) +``` + +### Key Properties + +- `.accelerometer`: Returns acceleration values (x, y, z) in g +- `.gyro`: Returns angular velocity (x, y, z) in dps + +### Advanced Example - Step Counter + +```python +from modulino import ModulinoMovement +from time import sleep_ms, ticks_ms +import math + +movement = ModulinoMovement() + +# Step detection parameters +STEP_THRESHOLD = 1.2 # Magnitude threshold for step detection +MIN_STEP_INTERVAL = 300 # Minimum time between steps (ms) +MAX_STEP_INTERVAL = 2000 # Maximum time between steps (ms) + +# State tracking +step_count = 0 +last_step_time = 0 +last_magnitude = 0 +peak_detected = False + +# Calibration +calibration_samples = [] +baseline_magnitude = 1.0 + +def calculate_magnitude(x, y, z): + """Calculate the magnitude of acceleration vector""" + return math.sqrt(x*x + y*y + z*z) + +def calibrate(): + """Calibrate the baseline acceleration magnitude""" + global baseline_magnitude + + print("Calibrating... Keep device still") + samples = [] + + for _ in range(50): + acc = movement.accelerometer + mag = calculate_magnitude(acc.x, acc.y, acc.z) + samples.append(mag) + sleep_ms(20) + + baseline_magnitude = sum(samples) / len(samples) + print(f"Calibration complete. Baseline: {baseline_magnitude:.3f}g") + +def detect_step(): + """Detect steps based on acceleration patterns""" + global step_count, last_step_time, last_magnitude, peak_detected + + current_time = ticks_ms() + acc = movement.accelerometer + + # Calculate acceleration magnitude + magnitude = calculate_magnitude(acc.x, acc.y, acc.z) + + # Detect peaks in acceleration + if magnitude > STEP_THRESHOLD and magnitude > last_magnitude and not peak_detected: + # Check if enough time has passed since last step + time_since_last = current_time - last_step_time + + if time_since_last > MIN_STEP_INTERVAL: + if time_since_last < MAX_STEP_INTERVAL or step_count == 0: + step_count += 1 + last_step_time = current_time + peak_detected = True + + # Calculate step rate + if step_count > 1: + step_rate = 60000 / time_since_last # steps per minute + print(f"👣 Step {step_count} detected! Rate: {step_rate:.0f} spm") + else: + print(f"👣 Step {step_count} detected!") + + # Reset peak detection when magnitude drops + if magnitude < last_magnitude: + peak_detected = False + + last_magnitude = magnitude + +def calculate_distance(steps, stride_length=0.7): + """Estimate distance traveled based on steps""" + return steps * stride_length + +def calculate_calories(steps, weight_kg=70): + """Estimate calories burned based on steps""" + # Rough estimate: 0.04 calories per step per kg of body weight + return steps * 0.04 * weight_kg / 70 + +# Main program +print("🚶 Step Counter Application") +print("=" * 30) + +calibrate() +print("\nStart walking!") +print("Press Ctrl+C to see statistics\n") + +try: + while True: + detect_step() + sleep_ms(50) + +except KeyboardInterrupt: + # Display statistics + distance = calculate_distance(step_count) + calories = calculate_calories(step_count) + + print("\n" + "=" * 30) + print("📊 Walking Statistics:") + print(f" Total Steps: {step_count}") + print(f" Distance: {distance:.2f} meters") + print(f" Calories: {calories:.1f} kcal") + print("=" * 30) +``` + +## Troubleshooting + +### Sensor Not Reachable + +If your Modulino's power LED isn't on or the sensor isn't responsive: +- Ensure both the board and the Modulino are connected properly +- Verify that the power LEDs on both are lit +- Check that the QWIIC cable is properly clicked into place + +### Inaccurate Values -- Use the movement data to detect different patterns and use these as inputs for your projects. -- Create a motion-activated alarm that triggers when unexpected movement is detected. -- Build a balance game that challenges players to keep the sensor level within certain parameters. -- Make a pedometer that counts steps based on the characteristic motion patterns of walking. \ No newline at end of file +If the sensor values are not accurate: +- Ensure the sensor is not on an unstable surface causing unwanted vibrations +- Verify exposed electronics are not touching conductive surfaces +- Mount the board securely when measuring precise movements +- Consider calibrating the sensor before use + +## Project Ideas + +- **Motion-Activated Alarm**: Trigger alerts when unexpected movement is detected +- **Balance Game**: Challenge players to keep the sensor level +- **Pedometer**: Count steps based on characteristic motion patterns +- **Gesture Recognition**: Detect specific motion patterns for control +- **Tilt Controller**: Use tilt angles to control games or robots +- **Vibration Monitor**: Detect and log vibrations in machinery +- **Fall Detection**: Identify sudden acceleration changes indicating falls +- **Orientation Tracker**: Monitor device orientation in 3D space \ No newline at end of file diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-pixels/tutorials/how-pixels-ardu/assets/pixelsOverview.png b/content/hardware/11.accessories/modulino-nodes/modulino-pixels/tutorials/how-pixels-ardu/assets/pixelsOverview.png new file mode 100644 index 0000000000..13526c3f7d Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-pixels/tutorials/how-pixels-ardu/assets/pixelsOverview.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-pixels/tutorials/how-pixels-ardu/content.md b/content/hardware/11.accessories/modulino-nodes/modulino-pixels/tutorials/how-pixels-ardu/content.md index 5850c78318..ea503323fa 100644 --- a/content/hardware/11.accessories/modulino-nodes/modulino-pixels/tutorials/how-pixels-ardu/content.md +++ b/content/hardware/11.accessories/modulino-nodes/modulino-pixels/tutorials/how-pixels-ardu/content.md @@ -1,8 +1,10 @@ --- -title: "How To Use The Modulino Pixels" -description: "Learn how to get the most out of your Modulino Pixels." +title: "Modulino Pixels" +description: "Complete guide for the Modulino Pixels RGB LED module." tags: - Modulino + - LED + - RGB - QWIIC - I2C author: 'Pedro Sousa Lima' @@ -11,29 +13,42 @@ hardware: software: - ide-v2 - web-editor + - micropython --- -The Modulino Pixels is a modular sensor that generates RGB light effects, making it perfect to add colorful visual feedback to your projects! -The Modulino form factor is shaped with two QWIIC connectors and the I²C protocol integration, allowing the connection and programming of multiple Modulino nodes in a very simple way. In addition to the QWIIC's connectors, the Modulino nodes also expose solderable pins that can be used in multiple ways and make them compatible with boards that are not QWIIC compatible. +![Pixels Overview](assets/pixelsOverview.png) +The Modulino Pixels is a modular sensor that generates RGB light effects, making it perfect to add colourful visual feedback to your projects! It features 8 individually addressable RGB LEDs controlled through I2C. -## Hardware Specifications +## Hardware Overview -The Modulino Pixels based on 8 LC8822-2020 addressable LEDs is capable of generating colorful light patterns and effects. Take a look at the following table to know more about its characteristics: +### General Characteristics -| Parameter | Condition | Minimum | Typical | Maximum | Unit | -|------------------|-------------------|---------|---------|---------|------| -| Supply Voltage | - | 2.0 | 3.3 | 3.6 | V | -| Resolution (ADC) | Default | - | 12-bit | - | mcd | -| Communication | I²C,USART,SPI | - | I²C | - | - | +The Modulino Pixels is based on 8 LC8822-2020 addressable LEDs capable of generating colourful light patterns and effects. -## Pinout +| Parameter | Condition | Minimum | Typical | Maximum | Unit | +|------------------|----------------|---------|---------|---------|------| +| Supply Voltage | - | 2.0 | 3.3 | 3.6 | V | +| Resolution (ADC) | Default | - | 12-bit | - | - | +| Communication | I2C,USART,SPI | - | I2C | - | - | -The LC8822-2020 addressable LEDs are the core components of this module. These RGB light output devices are controlled by an onboard STM32C011F4U6TR microcontroller, which supports digital communication (I²C), meaning it connects directly to the I²C bus on the module without requiring additional conversion circuitry. +### Module Details + +The **Modulino Pixels** module uses **LC8822-2020** addressable LEDs, which do not have native I2C capabilities. Instead, the LED array is controlled by the Modulino's onboard microcontroller (STM32C011F4U6TR). This microcontroller provides I2C communication, allowing for flexible control of the LEDs. + +One unique feature of this setup is the ability to change the I2C address via software, making it adaptable to different system configurations. + +The default I2C address for the **Modulino Pixels** module is: + +| Modulino I2C Address | Hardware I2C Address | Editable Addresses (HEX) | +|----------------------|----------------------|-----------------------------------| +| 0x6C | 0x36 | Any custom address (via software) | + +### Pinout ![Modulino Pixels Pinout](assets/PixelsPinouts.png) -### 1x10 Header (LC8822-2020 and Microcontroller Signals) +#### 1x10 Header (LC8822-2020 and Microcontroller Signals) | Pin | Function | |--------|-----------------| @@ -48,42 +63,19 @@ The LC8822-2020 addressable LEDs are the core components of this module. These R | D0 | Pixels Data Out | | C0 | Pixels Clock Out| -- **GND: Ground**: Provides ground reference for the circuit. Multiple ground pins ensure stable power distribution. -- **3V3: 3.3V Power**: Supplies 3.3V power to connected components and modules. -- **RESET: Reset**: Used to reset the microcontroller or connected system. -- **SWCLK and SWDIO: SWD Interface**: Used for debugging, programming, and reprogramming the microcontroller via Serial Wire Debug protocol. -- **TX1 and RX1: USART Communication**: Enable serial communication for data transmission and reception with other devices or modules. -- **D0: Pixels Data Out**: Sends pixel data to addressable LED strips in a daisy chain configuration for lighting control. -- **C0: Pixels Clock Out**: Provides clock signal synchronization for addressable LED strips, ensuring proper timing for pixel data. +The **D0** and **C0** pins allow for expansion by daisy-chaining additional LED strips. +![Expantion Pins](assets/expansion-guide-pixels.png) -### 1x4 Header (I2C) - -The pinout for the Modulino Pixels is shown below. While the recommended connection method is via the QWIIC connectors, this solderable header provides a connection option when using the modulino with a non-QWIIC compatible board. +#### 1x4 Header (I2C) | Pin | Function | |-------|--------------| | GND | Ground | | 3.3 V | Power Supply | -| SDA | I²C Data | -| SCL | I²C Clock | - -## I2C Address - -The **Modulino Pixels** module uses **LC8822-2020** addressable LEDs, which do not have native I²C capabilities. Instead, the LED array is controlled by the Modulino's onboard microcontroller (STM32C011F4U6TR). This microcontroller provides I²C communication, allowing for flexible control of the LEDs. +| SDA | I2C Data | +| SCL | I2C Clock | -One unique feature of this setup is the ability to change the I²C address via software. This means the address can be modified based on your application needs, making it adaptable to different system configurations. The default I²C address for the **Modulino Pixels** module is: - -| Modulino I²C Address | Hardware I²C Address | Editable Addresses (HEX) | -|----------------------|----------------------|-----------------------------------| -| 0x6C | 0x36 | Any custom address (via software) | - -When scanning for I²C address on the bus, you might find the modulino using the **Hardware I²C Address**. However, you should always use the **Modulino I²C Address** when using the official Modulino library. - -Later in this article we teach how to [change the address](#how-to-change-i2c-address). - -## Power Specifications - -The board is typically powered by +3.3 VDC when using the QWIIC interface as per the I²C standard. +### Power Specifications | Parameter | Condition | Typical | Maximum | Unit | |------------------------|----------------|---------|---------|------| @@ -92,104 +84,16 @@ The board is typically powered by +3.3 VDC when using the QWIIC interface as per | Standby Current | No data signal | - | 1 | mA | | Max LED Output Current | Per Channel | 18 | - | mA | +The module includes a power LED that draws 1 mA and turns on as soon as it is powered. -The module additionally includes a power LED that draws 1 mA and turns on as soon as it is powered. - -J1 (Qwiic connector), J2 (Qwiic connector), and the headers all share the same power branch. The power distribution of the module is therefore as follows: - -![Power Tree Modulino Pixels](assets/Modulino_Pixels_Power_Tree.png) - -## Schematic - -The Modulino Pixels uses a simple circuit, as shown in the schematic below: - -![Full Schematic Modulino Pixels](assets/schematic.png) - -The main components are the **8 LC8822-2020 addressable LEDs** and the **STM32C011F4U6TR** microcontroller (U1), which handles LED control as well as I²C communication. - -You can connect to the I²C pins (SDA and SCL) using either the **QWIIC connectors** (J1 and J2, this is the recommended method) or the **solderable pins** (J4). The board runs on **3.3V**, which comes from the QWIIC cable or the **3V3 pin** on J4. - -The **LC8822-2020** LEDs are connected in a daisy chain, with the first LED receiving clock and data signals from the microcontroller. The **CO (Clock Out)** and **DO (Data Out)** of the last LED in the chain are accessible via the **1x10 header**, allowing for expansion. ![LED Expantion](assets/expansion-guide-pixels.png) - -These can also be found in small pads near the STM32 microcontroller alongside a few user defines pads that can be used by editing the firmware: - -![Exposed user-defined and LED expansion pads](assets/pixel-expantion-mc.png) - -There's also a small power LED indicator that lights up when the board is on. - -You can grab the full schematic and PCB files from the [Modulino Pixels](https://docs.arduino.cc/hardware/modulinos/modulino-pixels) product page. - -## How To Connect Your Modulino - -The easiest and most reliable way to connect your Modulino is through the QWIIC Connect System. It’s plug-and-play, uses standard I²C, and makes it easy to join multiple modules. If your board supports QWIIC, this is the recommended way to go. -Note that the dedicated I²C pins will differ from board to board meaning it is always a good idea to check your specific model. - - -![Modulino Wiring Options QWIIC(A - recommended) and Header(B)](assets/connection-guide-pixels.png) - -### QWIIC Connector - -Whenever available, the **QWIIC Connect System** is the preferred method. Connecting to the Modulino is extremely simple, just use a standard QWIIC cable to connect your board to either of the QWIIC connectors on the Modulino. Because the cable and connectors are polarized, there is no need to worry about accidentally swapping connections. - -QWIIC is a plug-and-play I²C Connect System that uses standardized 4-pin connectors: - -- GND -- 3.3V -- SDA (Data) -- SCL (Clock) - -![Connection Guide QWIIC](assets/connection-guide-pixels-qwiik.png) - -The Modulino features two QWIIC connectors, which are internally connected in parallel. This means you can daisy-chain multiple modules easily by connecting additional QWIIC cables between them. - -### Solderable Header - -When QWIIC is not available, you can use the exposed solderable pins on the module. You can solder pins to the unpopulated pads; just remember the pinout provided in this guide to connect to the right pins of your board. - -![Connection Guide Solder Pads](assets/connection-guide-pixels-jumper.png) - -## Daisy-Chaining Multiple Modulino Nodes - -Regardless of whether you connect the first Modulino via QWIIC or through the solderable pins, you can still take advantage of the extra QWIIC connector to daisy-chain additional modules. - -Each Modulino includes two QWIIC connectors wired in parallel, allowing you to connect one module to the next in a chain. As long as each module is configured with a unique I²C address, they can all communicate on the same bus. - -This approach keeps your setup clean, modular, and expandable without adding extra wiring complexity. - -![Modulino Wiring Options](assets/connection-guide-pixels-qwiic-chain.png) - -***The number of modules you can connect will depend on what modules you are chaining together, as this system allows for multiple sensors from different manufacturers to be added. Also, the cables you use for these connections will play a significant role in the setup’s performance. Ensure your cables are properly connected and capable of handling the required data transfer. -Each module should have a unique address on a chain if you plan to address them individually. Later in this article we teach how to [change the address](#how-to-change-i2c-address). Multiple modules with the same address will cause conflicts on the I²C bus and will not allow you to address them individually.*** - -## How To Use Your Modulino +## Programming with Arduino -### Installing The Modulino Library +### Prerequisites -You need the official Modulino library available [here](https://github.com/arduino-libraries/Modulino) to use the Modulino Thermo. +- Install the Modulino library via the Arduino IDE Library Manager +- Connect your Modulino Pixels via QWIIC or solderable headers -With the Arduino IDE you get some tools that make adding a library easier. To learn how to install the IDE please visit our [page](https://docs.arduino.cc/software/ide-v2/tutorials/getting-started/ide-v2-downloading-and-installing/). - -After opening the IDE, a tab should be visible on the left. Press the book icon for "library" as highlighted in the image. - -![IDE Library Tab](assets/IDE-Left-Tab.png) - -The process should look like this: - -![Library Install](assets/library-install.gif) - -A message will appear after the installation is successful. - -### Set LED Colors - -Controlling RGB LEDs using the **Modulino Pixels** module is straightforward with the `Modulino` library. - -For the **Pixels**, there are two important functions: - -- `set(index, color, brightness)`: Sets a specific LED to a chosen color and brightness level. (`RED`,`BLUE`,`GREEN`,`VIOLET`,`WHITE`) -- `show()`: Applies the changes to the LEDs. -- ```Modulino.begin();```: By default the Modulino library uses ```Wire1``` if your connection is in a different Wire you will have to edit it, check [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/) (by default the Modulino library uses ```Wire1``` if your board model has a different pinout for the dedicated I²C pins you might have to edit it. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/)) for the library's hardware compatibility. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/). - -Here is an example of how to implement these functions to control the LEDs: +### Basic Example ```arduino #include @@ -212,65 +116,328 @@ void loop(){ } ``` -The code example provided demonstrates how to initialize the LED module and set all 8 LEDs to blue with a brightness level of 25%. The for-loop cycles through each LED (indexed 0-7), sets its color and brightness, and then uses the show() function to apply the change. This creates a simple blue light display that can be easily modified to create more complex lighting patterns or visual indicators for your projects. +### Key Functions + +- `set(index, color, brightness)`: Sets a specific LED (0-7) to a colour with brightness +- `show()`: Applies the changes to the LEDs +- Available colours: `RED`, `BLUE`, `GREEN`, `VIOLET`, `WHITE` -### How To Change I²C Address +### Advanced Example - Rainbow Animation -An example sketch, AddressChanger, is also included with the library inside the `Utilities` folder and available [here](https://github.com/arduino-libraries/Modulino/blob/main/examples/Utilities/AddressChanger/AddressChanger.ino). This sketch changes the I²C address at a software level on the Module's microcontroller. +```arduino +#include -![Example location on the IDE](assets/addressChangeIDE.png) +ModulinoPixels leds; -- Connect the module to your board, remove any other modules that might be in the chain. Connection must be via I²C. -- Upload the sketch. -- Open the Serial Monitor. -- Text should now appear. Make sure the correct bauld-rate is selected if the displayed characters seem corrupted. +// Color definitions for rainbow +const int NUM_LEDS = 8; +int colors[][3] = { + {255, 0, 0}, // Red + {255, 127, 0}, // Orange + {255, 255, 0}, // Yellow + {0, 255, 0}, // Green + {0, 0, 255}, // Blue + {75, 0, 130}, // Indigo + {148, 0, 211}, // Violet + {255, 0, 0} // Back to Red +}; + +void setup() { + Serial.begin(9600); + Modulino.begin(); + leds.begin(); - ![Expected console output](assets/adressChanger.png) + Serial.println("Rainbow Animation Started"); +} -- Select the address and confirm. -- Your address should now have changed. Make sure to take note of the selected address. +void rainbowCycle() { + static int offset = 0; + + for (int i = 0; i < NUM_LEDS; i++) { + int colorIndex = (i + offset) % NUM_LEDS; + + // Custom color setting using RGB values + // Since the library uses predefined colors, we'll use + // the closest match or cycle through available colors + switch(colorIndex) { + case 0: + case 7: + leds.set(i, RED, 50); + break; + case 1: + case 2: + leds.set(i, GREEN, 50); + break; + case 3: + case 4: + leds.set(i, BLUE, 50); + break; + case 5: + case 6: + leds.set(i, VIOLET, 50); + break; + } + } + + leds.show(); + offset = (offset + 1) % NUM_LEDS; +} -To keep track of the address in use the module has a white rectangle on the back. Feel free to use this to write the address that was chosen. +void breathingEffect() { + static int brightness = 0; + static int direction = 1; + + // Update brightness + brightness += direction * 5; + + if (brightness >= 100 || brightness <= 0) { + direction = -direction; + } + + // Set all LEDs to same color with varying brightness + for (int i = 0; i < NUM_LEDS; i++) { + leds.set(i, BLUE, brightness); + } + leds.show(); +} -When using a custom address in your sketch, you'll need to specify this address when creating the module object. For example: +void chaseEffect() { + static int position = 0; + + // Turn off all LEDs + for (int i = 0; i < NUM_LEDS; i++) { + leds.set(i, WHITE, 0); + } + + // Light up current position and trailing LEDs + leds.set(position, WHITE, 100); + if (position > 0) { + leds.set(position - 1, WHITE, 30); + } else { + leds.set(NUM_LEDS - 1, WHITE, 30); + } + + leds.show(); + position = (position + 1) % NUM_LEDS; +} -```arduino -ModulinoPixels pixels(0x3E); // Replace 0x3E with your specific address +void loop() { + // Cycle through different effects + for (int i = 0; i < 50; i++) { + rainbowCycle(); + delay(100); + } + + for (int i = 0; i < 100; i++) { + breathingEffect(); + delay(30); + } + + for (int i = 0; i < 30; i++) { + chaseEffect(); + delay(80); + } +} ``` -## Troubleshooting +## Programming with MicroPython -### LEDs Not Lighting +### Prerequisites + +- Install the Modulino MicroPython library +- Ensure Arduino Lab for MicroPython is installed -If your Modulino's power LED isn't on or the RGB LEDs aren't responsive, first check that the board is properly connected: +### Basic Example -- Ensure both the board and the Modulino are connected to your computer, and that the power LEDs on both are lit. -- If the issue persists, make sure the Qwiic cable is properly clicked into place. +```python +from modulino import ModulinoPixels, ModulinoColor +from time import sleep -### Library Not Installed Properly +pixels = ModulinoPixels() -If you encounter an issue with the `#include "modulino.h"` command, verify that the Modulino library is correctly installed: +# Set all LEDs to green +pixels.set_all_color(ModulinoColor.GREEN, 100) +pixels.show() +sleep(1) -- Check your IDE to ensure the library is installed and up-to-date. -- Re-install the library through the Library Manager. +# Turn off all LEDs +pixels.clear_all().show() +``` -### Incorrect Colors or Flickering +### Key Functions + +- `set_rgb(index, r, g, b, brightness)`: Set specific LED to RGB colour +- `set_all_rgb(r, g, b, brightness)`: Set all LEDs to RGB colour +- `set_all_color(color, brightness)`: Set all LEDs to predefined colour +- `clear_all()`: Turn off all LEDs +- `show()`: Send updated data to LEDs + +### Advanced Example - Interactive Light Patterns + +```python +from modulino import ModulinoPixels, ModulinoColor +from time import sleep, ticks_ms + +pixels = ModulinoPixels() + +def wheel(pos): + """Generate rainbow colors across 0-255 positions""" + if pos < 85: + return (255 - pos * 3, pos * 3, 0) + elif pos < 170: + pos -= 85 + return (0, 255 - pos * 3, pos * 3) + else: + pos -= 170 + return (pos * 3, 0, 255 - pos * 3) + +def rainbow_cycle(wait=0.01): + """Draw rainbow that uniformly distributes itself across all LEDs""" + for j in range(256): + for i in range(8): + pixel_index = (i * 256 // 8) + j + r, g, b = wheel(pixel_index & 255) + pixels.set_rgb(i, r, g, b, 50) + pixels.show() + sleep(wait) + +def color_wipe(r, g, b, wait=0.05): + """Wipe color across display a pixel at a time""" + for i in range(8): + pixels.set_rgb(i, r, g, b, 100) + pixels.show() + sleep(wait) + +def theater_chase(r, g, b, wait=0.1): + """Movie theater light style chaser animation""" + for q in range(3): + for i in range(0, 8, 3): + if i + q < 8: + pixels.set_rgb(i + q, r, g, b, 100) + pixels.show() + sleep(wait) + + for i in range(0, 8, 3): + if i + q < 8: + pixels.set_rgb(i + q, 0, 0, 0, 0) + +def pulse_color(r, g, b, duration=2): + """Pulse all LEDs with specified color""" + steps = 50 + for i in range(steps): + brightness = int((1 + i) * 100 / steps) + pixels.set_all_rgb(r, g, b, brightness) + pixels.show() + sleep(duration / (steps * 2)) + + for i in range(steps, 0, -1): + brightness = int(i * 100 / steps) + pixels.set_all_rgb(r, g, b, brightness) + pixels.show() + sleep(duration / (steps * 2)) + +def fire_effect(): + """Simulate fire/flame effect""" + import random + + # Base fire colors + base_r = 255 + base_g = 80 + base_b = 0 + + for _ in range(100): + for i in range(8): + # Add random flicker + flicker = random.randint(-40, 40) + r = max(0, min(255, base_r + flicker)) + g = max(0, min(255, base_g + flicker // 2)) + b = base_b + + brightness = random.randint(30, 100) + pixels.set_rgb(i, r, g, b, brightness) + + pixels.show() + sleep(0.05) + +def progress_bar(percentage, color_r=0, color_g=255, color_b=0): + """Display a progress bar""" + pixels.clear_all() + + # Calculate how many LEDs to light + leds_to_light = int((percentage / 100) * 8) + + for i in range(leds_to_light): + pixels.set_rgb(i, color_r, color_g, color_b, 100) + + # Partial LED for precise percentage + if leds_to_light < 8 and percentage > 0: + remainder = (percentage / 100 * 8) - leds_to_light + if remainder > 0: + brightness = int(remainder * 100) + pixels.set_rgb(leds_to_light, color_r, color_g, color_b, brightness) + + pixels.show() + +# Demo menu +print("LED Pattern Showcase") +print("====================") +patterns = [ + ("Rainbow Cycle", lambda: rainbow_cycle()), + ("Color Wipe - Red", lambda: color_wipe(255, 0, 0)), + ("Color Wipe - Green", lambda: color_wipe(0, 255, 0)), + ("Color Wipe - Blue", lambda: color_wipe(0, 0, 255)), + ("Theater Chase", lambda: theater_chase(127, 127, 127)), + ("Pulse White", lambda: pulse_color(255, 255, 255)), + ("Fire Effect", lambda: fire_effect()), + ("Progress Demo", lambda: [progress_bar(i) for i in range(0, 101, 5)]) +] + +for i, (name, _) in enumerate(patterns, 1): + print(f"{i}. {name}") + +while True: + choice = input("\nSelect pattern (1-8): ") + + try: + idx = int(choice) - 1 + if 0 <= idx < len(patterns): + name, pattern_func = patterns[idx] + print(f"Running: {name}") + pattern_func() + pixels.clear_all().show() + else: + print("Invalid selection") + except ValueError: + print("Please enter a number") + except KeyboardInterrupt: + pixels.clear_all().show() + print("\nExiting...") + break +``` -If the LED colors are incorrect or the LEDs are flickering unexpectedly, make sure: +## Troubleshooting -- The brightness values are within the appropriate range (typically 0-255). -- All exposed electronics are not touching any conductive surfaces, as this could interfere with the LED output. -- The power supply is stable and providing sufficient current for all LEDs at the desired brightness. +### LEDs Not Lighting -## Conclusion +If your Modulino's power LED isn't on or the RGB LEDs aren't responsive: +- Ensure both the board and the Modulino are connected properly +- Verify that the power LEDs on both are lit +- Check that the QWIIC cable is properly clicked into place -The **Modulino Pixels** is a digital RGB LED control module that communicates over I²C and follows the Modulino form factor. It includes standard Qwiic connectors for quick, solderless connections and easy daisy-chaining with other modules. Paired with the Modulino library, it makes generating colorful light effects straightforward, allowing you to focus on experimenting or building your system logic. It's a small, reliable module suited for both visual feedback and creative lighting projects. +### Incorrect Colours or Flickering -## What Is Next? +If the LED colours are incorrect or the LEDs are flickering: +- Verify brightness values are within the appropriate range (0-255) +- Check that exposed electronics are not touching conductive surfaces +- Ensure stable power supply with sufficient current for all LEDs -Now that you've learned how to use your Modulino Pixels, you're all set to integrate it into your projects! +## Project Ideas -- Create an animated progress bar that visually displays status, or battery charge level using a gradient of colors. -- Build a live sound level indicator that responds to ambient noise. -- Design a pomodoro timer with color coded work and rest periods to boost your productivity. -- Program an interactive game where players must match patterns of colors in the correct sequence, with difficulty increasing as they progress. +- **Progress Bar**: Visually display status or battery charge level +- **Sound Level Indicator**: Respond to ambient noise with light +- **Pomodoro Timer**: Colour-coded work and rest periods +- **Simon Game**: Match colour patterns in sequence +- **Notification System**: Different colours for different alerts +- **Mood Lighting**: Create ambient lighting effects +- **Temperature Indicator**: Use with Modulino Thermo for visual temperature feedback +- **Music Visualiser**: Sync lights to music or sounds \ No newline at end of file diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/ThermoOverview.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/ThermoOverview.png new file mode 100644 index 0000000000..31fd0ba8e5 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/ThermoOverview.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/IDE-Left-Tab.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/IDE-Left-Tab.png new file mode 100644 index 0000000000..c7bb86575e Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/IDE-Left-Tab.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/Modulino_Thermo_Power_Tree.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/Modulino_Thermo_Power_Tree.png new file mode 100644 index 0000000000..75ecb8a8e7 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/Modulino_Thermo_Power_Tree.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/ThermoPinouts.jpg b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/ThermoPinouts.jpg new file mode 100644 index 0000000000..22c8b59c70 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/ThermoPinouts.jpg differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-gen.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-gen.png new file mode 100644 index 0000000000..b9b45cb39f Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-gen.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo-jumper.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo-jumper.png new file mode 100644 index 0000000000..0742e36a31 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo-jumper.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo-qwiic-chain.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo-qwiic-chain.png new file mode 100644 index 0000000000..28d62417a5 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo-qwiic-chain.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo-qwiik.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo-qwiik.png new file mode 100644 index 0000000000..e10a27ebdb Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo-qwiik.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo.png new file mode 100644 index 0000000000..35591967a9 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/connection-guide-thermo.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/library-install.gif b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/library-install.gif new file mode 100644 index 0000000000..16f396c353 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/library-install.gif differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/schematic.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/schematic.png new file mode 100644 index 0000000000..b094fac53d Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/assets/schematic.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/connection-guide-gen-qwiic.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/connection-guide-gen-qwiic.png new file mode 100644 index 0000000000..c49ac03586 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/connection-guide-gen-qwiic.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/content.md b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/content.md new file mode 100644 index 0000000000..af8439b553 --- /dev/null +++ b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/content.md @@ -0,0 +1,250 @@ +--- +title: "Getting Started with Modulinos" +description: "Learn the fundamentals of connecting, configuring, and programming Modulino sensors and actuators." +tags: + - Modulino + - QWIIC + - I2C +author: 'Arduino Team' +hardware: + - hardware/11.modulinos/modulinos +software: + - ide-v2 + - web-editor + - micropython +--- + +The Modulino ecosystem provides modular sensors and actuators that streamline prototyping and development. Each module follows a standardised form factor with QWIIC connectors and I²C protocol integration, allowing simple connection and programming of multiple nodes. In addition to QWIIC connectors, Modulinos expose solderable pins for compatibility with boards that don't support QWIIC. + +## The Modulino System + +Modulinos are designed to work seamlessly together through: +- **Standardised QWIIC connectors** for plug-and-play connectivity +- **I²C communication** for simple two-wire data transfer +- **Daisy-chain capability** for connecting multiple modules +- **Compact form factor** for space-efficient designs +- **Cross-platform support** for Arduino and MicroPython + +## How To Connect Your Modulino + +The easiest and most reliable way to connect your Modulino is through the QWIIC Connect System. It's plug-and-play, uses standard I²C, and makes it easy to join multiple modules. If your board supports QWIIC, this is the recommended way to go. + +Note that the dedicated I²C pins will differ from board to board, meaning it is always a good idea to check your specific model. + +![Connection Options](assets/connection-guide-gen.png) + +### QWIIC Connector (Recommended) + +Whenever available, the **QWIIC Connect System** is the preferred method. Connecting to the Modulino is extremely simple—just use a standard QWIIC cable to connect your board to either of the QWIIC connectors on the Modulino. Because the cable and connectors are polarised, there is no need to worry about accidentally swapping connections. + +![QWIIC Connection](connection-guide-gen-qwiic.png) + +QWIIC is a plug-and-play I²C Connect System that uses standardised 4-pin connectors: +- GND +- 3.3V +- SDA (Data) +- SCL (Clock) + +The Modulino features two QWIIC connectors, which are internally connected in parallel. This means you can daisy-chain multiple modules easily by connecting additional QWIIC cables between them. + +### Solderable Header + +When QWIIC is not available, you can use the exposed solderable pins on the module. You can solder pins to the unpopulated pads; just remember the pinout provided in each module's guide to connect to the right pins of your board. + +### Daisy-Chaining Multiple Modulino Nodes + +Regardless of whether you connect the first Modulino via QWIIC or through the solderable pins, you can still take advantage of the extra QWIIC connector to daisy-chain additional modules. + +Each Modulino includes two QWIIC connectors wired in parallel, allowing you to connect one module to the next in a chain. As long as each module is configured with a unique I²C address, they can all communicate on the same bus. + +This approach keeps your setup clean, modular, and expandable without adding extra wiring complexity. + +***Important considerations for daisy-chaining:*** +- The number of modules you can connect will depend on what modules you are chaining together, as this system allows for multiple sensors from different manufacturers to be added +- The cables you use for these connections will play a significant role in the setup's performance +- Ensure your cables are properly connected and capable of handling the required data transfer +- Each module should have a unique address on a chain if you plan to address them individually +- Multiple modules with the same address will cause conflicts on the I²C bus and will not allow you to address them individually + +## Power Specifications + +All Modulinos are typically powered by **+3.3 VDC** when using the QWIIC interface as per the I²C standard. Each module includes: +- Power LED indicator (typically draws 1 mA) +- Shared power distribution between QWIIC connectors and headers +- Protection against reverse polarity (on most modules) + +Always check your specific module's documentation for detailed power consumption specifications. + +## Installing The Modulino Library + +### For Arduino IDE + +You need the official Modulino library to use any Modulino module with Arduino. The Arduino IDE provides tools that make adding a library straightforward. + +To install the IDE, please visit our [getting started page](https://docs.arduino.cc/software/ide-v2/tutorials/getting-started/ide-v2-downloading-and-installing/). + +After opening the IDE: +1. Look for the tab on the left side +2. Click the book icon for "Library Manager" +3. Search for "Modulino" in the search box +4. Click "Install" + +A prompt might appear saying that additional dependencies are required. This is not a problem, as they will be automatically added when you confirm the prompt. + +**Important Wire Configuration:** +By default, the Modulino library uses `Wire1`. If your board model has a different pinout for the dedicated I²C pins, you might have to edit it. Check [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/) for more information on Wire configuration. + +### For MicroPython + +To program your Modulino with MicroPython, use the official `Modulino` MicroPython library available [here](https://github.com/arduino/arduino-modulino-mpy). The library is fully compatible with the Arduino Lab for MicroPython. + +For information on installing the **Arduino Lab for MicroPython**, please visit our [installation guide](https://docs.arduino.cc/micropython/first-steps/install-guide/). + +The `Modulino` library is not available by default on MicroPython devices, hence installation is needed. + +#### Using the MicroPython Package Installer + +To simplify the process, the [MicroPython Package Installer](https://github.com/arduino/lab-micropython-package-installer/releases) is recommended as it provides a graphical interface to guide installation. + +1. Open the tool +2. Plug in your board to the computer + - If the board does not appear in the Detected Boards section, click Reload + - If the board is still undetected, ensure no other programs are using the board's COM port +3. Search for the `Modulino` package by filling in the text box on the search feature +4. Click Install and wait for the installation confirmation +5. Disconnect the board from the tool before returning to your code editor to avoid conflicts due to a busy COM port + +After installation, you can import modules using: +```python +from modulino import ModulinoThermo, ModulinoBuzzer, ModulinoButtons +# Import the specific modules you need +``` + +**Wire Configuration for MicroPython:** +By default, the Modulino library uses `Wire1`. If your board model has a different pinout for the dedicated I²C pins, you might have to edit it as instructed [here](https://github.com/arduino/arduino-modulino-mpy/tree/main/docs#ℹ️-using-3rd-party-boards). + +## How To Change I²C Address + +Some Modulinos support software-configurable I²C addresses, allowing multiple identical modules to work on the same bus. Modules with fixed addresses cannot be changed and will require alternative solutions for multiple units. + +### For Arduino (Software-Configurable Modules) + +An example sketch, `AddressChanger`, is included with the library inside the `Utilities` folder and available [here](https://github.com/arduino-libraries/Modulino/blob/main/examples/Utilities/AddressChanger/AddressChanger.ino). + +To change the address: +1. Connect the module to your board (remove any other modules from the chain) +2. Upload the AddressChanger sketch +3. Open the Serial Monitor +4. Ensure the correct baud rate is selected if displayed characters seem corrupted +5. Select the new address and confirm +6. Valid I²C addresses range from 0x08 to 0x77 (7-bit values in hexadecimal format) + +When using a custom address in your sketch, specify this address when creating the module object: +```arduino +ModulinoBuzzer buzzer(0x3E); // Replace 0x3E with your specific address +``` + +### For MicroPython (Software-Configurable Modules) + +A script is available [here](https://github.com/arduino/arduino-modulino-mpy/blob/main/examples/change_address.py). + +To change the address: +1. Connect the module to your board via I²C (ensure no other modules are in the chain) +2. Run the script in a MicroPython environment +3. Follow the on-screen instructions (REPL) to select the device and enter a new address +4. The script will attempt to change the address and confirm success + +When using a custom address in MicroPython: +```python +buzzer_module = ModulinoBuzzer(address=0x45) # Replace 0x45 with your specific address +``` + +### Hardware Address Selection (Movement Module) + +The Modulino Movement can be configured to use an alternative I²C address through hardware modification: + +1. Disconnect all power from the module +2. Locate the address selection solder jumpers on the back of the board +3. Cut the trace on the jumper marked **Default** (0x6A) +4. Solder closed the jumper marked **0x6B** + +**IMPORTANT**: Never have both jumpers closed simultaneously when power is applied, as this will create a short circuit that could damage your module. + +### Tracking Address Changes + +To keep track of the address in use, modules have a white rectangle on the back. Use this space to write the selected address for future reference. + +## Module Addressing Reference + +| Module | Default Modulino Address | Hardware Address | Configurable | +|--------|-------------------------|------------------|--------------| +| Buttons | 0x7C | 0x3E | Software | +| Buzzer | 0x3C | 0x1E | Software | +| Distance | 0x52 | 0x52 | No | +| Knob | 0x76 | 0x3A | Software | +| Movement | 0x6A | 0x6A | Hardware (0x6A/0x6B) | +| Pixels | 0x6C | 0x36 | Software | +| Thermo | 0x44 | 0x44 | No | + +When scanning for I²C addresses on the bus, you might find the modulino using the **Hardware I²C Address**. However, you should always use the **Modulino I²C Address** when using the official Modulino library. + +## General Troubleshooting + +### Module Not Responding + +If your Modulino's power LED isn't on or the module isn't responsive: +- Ensure both the board and the Modulino are connected to your computer +- Verify that the power LEDs on both are lit +- Check that the QWIIC cable is properly clicked into place +- Verify the module is receiving 3.3V power + +### Library Not Installed Properly + +**Arduino IDE:** +If you encounter an issue with the `#include "Modulino.h"` command: +- Check your IDE to ensure the library is installed and up-to-date +- Re-install the library through the Library Manager +- Verify all dependencies were installed + +**MicroPython:** +If you encounter an issue with `from modulino import` commands: +- Check the package installer to ensure the library is installed +- Re-install the library through the Package Installer +- Ensure the board was disconnected from other programs during installation + +### I²C Communication Issues + +- Verify correct Wire configuration (Wire vs Wire1) +- Check for address conflicts between modules +- Ensure pull-up resistors are present on the I²C bus +- Verify cable length isn't exceeding I²C specifications +- Check that all connections are secure + +### Inaccurate Sensor Values + +- Ensure all exposed electronics are not touching conductive surfaces +- Verify the module is not placed near interference sources +- Check that power supply is stable and within specifications +- Allow sensors time to stabilise after power-on + +## Best Practices + +1. **Power Management**: Always use 3.3V for QWIIC connections. Never exceed voltage specifications. + +2. **Cable Management**: Use appropriate length QWIIC cables. Excessive cable length can cause signal degradation. + +3. **Address Management**: Document all address changes on the white label provided on each module. + +4. **Environmental Considerations**: Keep modules away from sources of electromagnetic interference, excessive heat, or moisture unless specifically rated for such conditions. + +5. **Development Workflow**: Test modules individually before connecting them in a chain to isolate any issues. + +## What's Next? + +Now that you understand the fundamentals of the Modulino system: +- Explore individual module guides for specific features and capabilities +- Experiment with combining multiple modules in your projects +- Share your creations with the Arduino community +- Check for updates and new modules in the Modulino ecosystem + +For detailed information about specific modules, refer to their individual documentation pages, which include pinouts, specifications, and programming examples for both Arduino and MicroPython. \ No newline at end of file diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/image.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/image.png new file mode 100644 index 0000000000..bceefec75d Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-general/image.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-thermo-ardu/ThermoOverview.png b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-thermo-ardu/ThermoOverview.png new file mode 100644 index 0000000000..31fd0ba8e5 Binary files /dev/null and b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-thermo-ardu/ThermoOverview.png differ diff --git a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-thermo-ardu/content.md b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-thermo-ardu/content.md index f54ced5150..e9250f6a8b 100644 --- a/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-thermo-ardu/content.md +++ b/content/hardware/11.accessories/modulino-nodes/modulino-thermo/tutorials/how-thermo-ardu/content.md @@ -1,8 +1,10 @@ --- -title: "How To Use The Modulino Thermo" -description: "Learn how to get the most out of your Modulino Thermo." +title: "Modulino Thermo" +description: "Complete guide for the Modulino Thermo temperature and humidity sensor." tags: - Modulino + - Temperature + - Humidity - QWIIC - I2C author: 'Pedro Sousa Lima' @@ -11,152 +13,78 @@ hardware: software: - ide-v2 - web-editor + - micropython --- -The Modulino Thermo is a modular sensor that measures temperature and humidity, making it perfect to add environmental monitoring to your projects! -The Modulino form factor is shaped with two QWIIC connectors and the I²C protocol integration, allowing the connection and programming of multiple Modulino nodes in a very simple way. In addition to the QWIIC's connectors, the Modulino nodes also expose solderable pins that can be used in multiple ways and make them compatible with boards that are not QWIIC compatible. +![Thermo Overview](ThermoOverview.png) -## General Characteristics +The Modulino Thermo is a modular sensor that measures temperature and humidity, making it perfect to add environmental monitoring to your projects! It uses the standardised Modulino form factor with QWIIC connectors for easy integration. -The Modulino Thermo is capable of measuring temperature and relative humidity. Take a look at the following table to know more about its measuring ranges: +## Hardware Overview +### General Characteristics + +The Modulino Thermo is capable of measuring temperature and relative humidity with the following specifications: | Parameter | Condition | Minimum | Typical | Maximum | Unit | |-----------|-------------|---------|---------|---------|------| -| Range | Temperature | \-40 | \- | +125 | °C | -| \- | Humidity | 0 | \- | 100% | φ RH | -| Accuracy | Temperature | \- | ±0,25 | \- | °C | -| \- | Humidity | \- | ±2.8% | \- | φ | +| Range | Temperature | -40 | - | +125 | °C | +| - | Humidity | 0 | - | 100 | φ RH | +| Accuracy | Temperature | - | ±0.25 | - | °C | +| - | Humidity | - | ±2.8 | - | φ | ### Sensor Details -The HS3003 sensor from Renesas is the core component of this module. This temperature and humidity sensor natively supports digital communication (I²C), meaning it connects directly to the I²C bus on the module without requiring additional conversion circuitry. +The **HS3003** sensor from Renesas is the core component of this module. This temperature and humidity sensor natively supports digital communication (I2C), meaning it connects directly to the I2C bus on the module without requiring additional conversion circuitry. The default address for the Module is: -| Modulino I²C Address | Hardware I²C Address | +| Modulino I2C Address | Hardware I2C Address | |----------------------|----------------------| | 0x44 | 0x44 | -***Note: Since the address cannot be changed on this Modulino specifically, using two or more identical modules on the same I²C bus will result in address conflicts and cause communication issues.*** - -## Pinout +***Note: Since the address cannot be changed on this Modulino specifically, using two or more identical modules on the same I2C bus will result in address conflicts and cause communication issues.*** -The pinout for the Modulino Thermo is shown below. Please note that the exposed solderable pins are directly connected to the QWIIC connectors using the same I²C interface. +### Pinout ![Arduino Thermo Pinout](assets/ThermoPinouts.jpg) -Depending on the board connected to the modulino, the I²C pin names to program it may differ. Please check the [board tutorials](https://docs.arduino.cc/hardware/) on your modulino's compatible board or the [Modulino library](https://github.com/arduino-libraries/Modulino/tree/main/docs) to learn more. - -### 1x4 Header (I2C) - -The pinout for the Modulino Buzzer is shown below. While the recommended connection method is via the QWIIC connectors, this solderable header provides a connection option when using the modulino with a non-QWIIC compatible board. +#### 1x4 Header (I2C) | Pin | Function | |-------|--------------| | GND | Ground | | 3.3 V | Power Supply | -| SDA | I²C Data | -| SCL | I²C Clock | - -## Power Specifications - -The board is typically powered by +3.3 VDC when using the QWIIC interface as per the I²C standard. - -| Parameter | Condition | Minimum | Typical | Maximum | Unit | -|-----------------|-------------------------------------------------------------------|---------|-------------|---------|------| -| Supply Voltage | \- | 2.3 | 3.3 (QWIIC) | 5.5 | V | -| Average Current | 1 humidity + temperature measurement/s 3.3 VDD - Max 5,5@ 3.3 VDD | \- | 1024.4 | 24.4 | µA | - -The module additionally includes a power LED that draws 1 mA and turns on as soon as it is powered. - -J1 (Qwiic connector), J2 (Qwiic connector), and the headers all share the same power branch. The power distribution of the module is therefore as follows: - -![Power Tree Modulino Thermo](assets/Modulino_Thermo_Power_Tree.png) - -## Schematic - -The Modulino Thermo uses a simple circuit, as shown in the schematic below: - -![Full Schematic Modulino Thermo](assets/schematic.png) - -The main component is the **HS3003** sensor (U1), which handles both temperature and humidity measurements, as well as I²C communication. - -You can connect to the I²C pins (SDA and SCL) using either the **QWIIC connectors** (J1 and J2, this is the recommended method) or the **solderable pins** (J4). The board runs on **3.3V**, which comes from the QWIIC cable or the **3V3 pin** on J4. - -There's also a small power indicator LED that lights up when the board is on. -You can grab the full schematic and PCB files from the [Modulino Thermo](https://docs.arduino.cc/hardware/modulinos/modulino-thermo) product page. - -## How To Connect Your Modulino - -The easiest and most reliable way to connect your Modulino is through the QWIIC Connect System. It’s plug-and-play, uses standard I²C, and makes it easy to join multiple modules. If your board supports QWIIC, this is the recommended way to go. Note that the dedicated I²C pins will differ from board to board meaning it is always a good idea to check your specific model. - -If your board doesn’t have a QWIIC connector, you can still access the same I²C bus and power the module using the solderable header pads just make sure you wire it to 3.3V and match the I²C pinout. - -![Modulino Wiring Options QWIIC(A - recommended) and Header(B)](assets/connection-guide-thermo.png) - -### QWIIC Connector - -Whenever available, the **QWIIC Connect System** is the preferred method. Connecting to the Modulino is extremely simple, just use a standard QWIIC cable to connect your board to either of the QWIIC connectors on the Modulino. Because the cable and connectors are polarized, there is no need to worry about accidentally swapping connections. - -QWIIC is a plug-and-play I²C Connect System that uses standardized 4-pin connectors: - -- GND -- 3.3V -- SDA (Data) -- SCL (Clock) - -![Connection Guide QWIIC](assets/connection-guide-thermo-qwiik.png) - -The Modulino features two QWIIC connectors, which are internally connected in parallel. This means you can daisy-chain multiple modules easily by connecting additional QWIIC cables between them. - -### Solderable Header - -When QWIIC is not available, you can use the exposed solderable pins on the module. You can solder pins to the unpopulated pads; just remember the pinout provided in this guide to connect to the right pins of your board. - -![Connection Guide Solder Pads](assets/connection-guide-thermo-jumper.png) - -## Daisy-Chaining Multiple Modulino Nodes - -Regardless of whether you connect the first Modulino via QWIIC or through the solderable pins, you can still take advantage of the extra QWIIC connector to daisy-chain additional modules. - -Each Modulino includes two QWIIC connectors wired in parallel, allowing you to connect one module to the next in a chain. As long as each module is configured with a unique I²C address, they can all communicate on the same bus as long as you select the correct I²C pins depending on your board. - -This approach keeps your setup clean, modular, and expandable without adding extra wiring complexity. - -![Modulino Wiring Options](assets/connection-guide-thermo-qwiic-chain.png) - -***The number of modules you can connect will depend on what modules you are chaining together, as this system allows for multiple sensors from different manufacturers to be added. Also, the cables you use for these connections will play a significant role in the setup’s performance. Ensure your cables are correctly connected and capable of handling the required data transfer. -Each module should have a unique address on a chain if you plan to address them individually. Multiple modules with the same address will cause conflicts on the I²C bus.*** - -## How To Use Your Modulino +| SDA | I2C Data | +| SCL | I2C Clock | -### Installing The Modulino Library +### Power Specifications -You need the official Modulino library available [here](https://docs.arduino.cc/libraries/modulino/) to use the Modulino Thermo. +The board is typically powered by +3.3 VDC when using the QWIIC interface as per the I2C standard. -With the Arduino IDE you get some tools that make adding a library easier. To learn how to install the IDE please visit our [page](https://docs.arduino.cc/software/ide-v2/tutorials/getting-started/ide-v2-downloading-and-installing/). +| Parameter | Condition | Minimum | Typical | Maximum | Unit | +|-----------------|---------------------------------------------------|---------|-------------|---------|------| +| Supply Voltage | - | 2.3 | 3.3 (QWIIC) | 5.5 | V | +| Average Current | 1 humidity + temperature measurement/s @ 3.3 VDD | - | 24.4 | 1024.4 | µA | -After opening the IDE, a tab should be visible on the left. Press the book icon for "library" as highlighted in the image. +The module includes a power LED that draws 1 mA and turns on as soon as it is powered. J1 (QWIIC connector), J2 (QWIIC connector), and the headers all share the same power branch. -![IDE Library Tab](assets/IDE-Left-Tab.png) +### Schematic -The process should look like this: +The Modulino Thermo uses a simple circuit built around the **HS3003** sensor (U1), which handles both temperature and humidity measurements, as well as I2C communication. -![Library Install](assets/library-install.gif) +You can connect to the I2C pins (SDA and SCL) using either the **QWIIC connectors** (J1 and J2, recommended) or the **solderable pins** (J4). The board runs on **3.3V** from the QWIIC cable or the **3V3 pin** on J4. -A message will appear after the installation is successful. +Full schematic and PCB files are available from the [Modulino Thermo product page](https://docs.arduino.cc/hardware/modulinos/modulino-thermo). +## Programming with Arduino -### Getting Temperature And Humidity Data +### Prerequisites -Getting data from the sensor is fairly simple using the ```Modulino``` library. For the **Modulino Thermo** there are two important functions: +- Install the Modulino library via the Arduino IDE Library Manager (see [Getting Started with Modulinos](link-to-generic-guide) for detailed instructions) +- Connect your Modulino Thermo via QWIIC or solderable headers -- ```getTemperature()```: Provides the temperature measurement from the sensor. (default in Celsius C) -- ```getHumidity()```: Provides the relative humidity measurement from the sensor. (default in Relative Percentage %) -- ```Modulino.begin();```: By default the Modulino library uses ```Wire1``` if your connection is in a different Wire you will have to edit it, check [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/) (by default the Modulino library uses ```Wire1``` if your board model has a different pinout for the dedicated I²C pins you might have to edit it. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/)) for the library's hardware compatibility. More information on **Wire** can be found [here](https://docs.arduino.cc/language-reference/en/functions/communication/wire/). - -Here is an example sketch of how to implement these functions to acquire data and show it using the serial monitor: +### Basic Example ```arduino #include @@ -170,7 +98,6 @@ float humidity = 0; void setup(){ // Initialization of the serial port, modulino object and thermo one - Serial.begin(115200); Modulino.begin(); thermo.begin(); @@ -190,42 +117,204 @@ void loop(){ } ``` -The code example provided shows how to initialize the sensor, read the data, and display it on the serial monitor. The data is updated every second, showing the current temperature and humidity values in real time. +### Key Functions -It can be easily adapted to trigger actions at certain temperature/humidity thresholds or to log data for analysis. +- `getTemperature()`: Returns temperature measurement in Celsius +- `getHumidity()`: Returns relative humidity as a percentage +- `Modulino.begin()`: Initialises the Modulino system (uses `Wire1` by default) -## Troubleshooting +### Advanced Example - Temperature Alert System -### Sensor Not Reachable - -If your Modulino's power LED isn't on or the sensor isn't responsive, first check that the board is properly connected: +```arduino +#include + +ModulinoThermo thermo; +const float TEMP_THRESHOLD = 25.0; // Alert above 25°C +const float HUMIDITY_THRESHOLD = 70.0; // Alert above 70% humidity -- Ensure both the board and the Modulino are connected to your computer, and that the power LEDs on both are lit. -- If the issue persists, make sure the Qwiic cable is properly clicked into place. +void setup(){ + Serial.begin(115200); + Modulino.begin(); + thermo.begin(); + + Serial.println("Environmental Monitor Started"); +} -### Library Not Installed Properly +void loop(){ + float temp = thermo.getTemperature(); + float hum = thermo.getHumidity(); + + // Check temperature threshold + if(temp > TEMP_THRESHOLD) { + Serial.print("⚠️ HIGH TEMPERATURE: "); + Serial.print(temp); + Serial.println("°C"); + } + + // Check humidity threshold + if(hum > HUMIDITY_THRESHOLD) { + Serial.print("⚠️ HIGH HUMIDITY: "); + Serial.print(hum); + Serial.println("%"); + } -If you encounter an issue with the `#include "modulino.h"` command, verify that the Modulino library is correctly installed: + // Normal readings + if(temp <= TEMP_THRESHOLD && hum <= HUMIDITY_THRESHOLD) { + Serial.print("Normal - Temp: "); + Serial.print(temp); + Serial.print("°C, Humidity: "); + Serial.print(hum); + Serial.println("%"); + } + + delay(5000); // Check every 5 seconds +} +``` + +## Programming with MicroPython + +### Prerequisites + +- Install the Modulino MicroPython library (see [Getting Started with Modulinos](link-to-generic-guide) for detailed instructions) +- Ensure Arduino Lab for MicroPython is installed + +### Basic Example + +```python +from modulino import ModulinoThermo +from time import sleep + +thermo_module = ModulinoThermo() -- Check your IDE to ensure the library is installed and up-to-date. -- Re-install the library through the Library Manager. +while True: + temperature = thermo_module.temperature + humidity = thermo_module.relative_humidity + + if temperature != None and humidity != None: + print(f"🌡️ Temperature: {temperature:.1f} °C") + print(f"💧 Humidity: {humidity:.1f} %") + print() + + sleep(2) +``` + +### Key Properties + +- `.temperature`: Returns temperature measurement in Celsius +- `.relative_humidity`: Returns relative humidity as a percentage + +### Advanced Example - Data Logger + +```python +from modulino import ModulinoThermo +from time import sleep, ticks_ms + +thermo = ModulinoThermo() + +# Configuration +LOG_INTERVAL = 60000 # Log every minute (in milliseconds) +SAMPLES_TO_KEEP = 60 # Keep last hour of data + +# Data storage +data_log = [] +last_log_time = ticks_ms() + +def calculate_average(values): + """Calculate average of a list of values""" + if not values: + return 0 + return sum(values) / len(values) + +def log_data(): + """Log temperature and humidity data""" + temp = thermo.temperature + hum = thermo.relative_humidity + + if temp is not None and hum is not None: + timestamp = ticks_ms() + data_log.append({ + 'time': timestamp, + 'temp': temp, + 'humidity': hum + }) + + # Keep only recent samples + if len(data_log) > SAMPLES_TO_KEEP: + data_log.pop(0) + + return True + return False + +def print_statistics(): + """Print statistics from logged data""" + if not data_log: + print("No data collected yet") + return + + temps = [d['temp'] for d in data_log] + hums = [d['humidity'] for d in data_log] + + print("\n📊 Statistics (last hour):") + print(f" Samples: {len(data_log)}") + print(f" Avg Temp: {calculate_average(temps):.1f}°C") + print(f" Min Temp: {min(temps):.1f}°C") + print(f" Max Temp: {max(temps):.1f}°C") + print(f" Avg Humidity: {calculate_average(hums):.1f}%") + print(f" Min Humidity: {min(hums):.1f}%") + print(f" Max Humidity: {max(hums):.1f}%") + +# Main loop +print("🌡️ Environmental Data Logger Started") +print("Logging data every minute...") + +while True: + current_time = ticks_ms() + + # Log data at intervals + if current_time - last_log_time >= LOG_INTERVAL: + if log_data(): + print(f"✅ Data logged: {thermo.temperature:.1f}°C, {thermo.relative_humidity:.1f}%") + print_statistics() + last_log_time = current_time + + # Show current readings + temp = thermo.temperature + hum = thermo.relative_humidity + if temp is not None and hum is not None: + print(f"Current: {temp:.1f}°C, {hum:.1f}%", end='\r') + + sleep(1) +``` + +## Troubleshooting + +### Sensor Not Reachable + +If your Modulino's power LED isn't on or the sensor isn't responsive: +- Ensure both the board and the Modulino are connected to your computer +- Verify that the power LEDs on both are lit +- Check that the QWIIC cable is properly clicked into place ### Inaccurate Values - -If the sensor values are not accurate, make sure: -- The sensor is not placed near any components that might generate heat (like motors or power supplies). -- All exposed electronics are not touching any conductive surfaces, as this could interfere with readings. +If the sensor values are not accurate: +- Ensure the sensor is not placed near heat-generating components (motors, power supplies) +- Verify all exposed electronics are not touching conductive surfaces +- Allow the sensor time to stabilise after power-on -## Conclusion +### Library Issues -The **Modulino Thermo** is a digital temperature and humidity sensor that communicates over I²C and follows the Modulino form factor. It includes standard Qwiic connectors for quick, solderless connections and easy daisy-chaining with other modules. Paired with the Modulino library, it makes accessing sensor data straightforward, allowing you to focus on experimenting or building your system logic. It’s a small, reliable module suited for both quick tests and longer-term setups. +See the [Getting Started with Modulinos](link-to-generic-guide) guide for library installation troubleshooting. -## What Is Next? +## Project Ideas -Now that you've learned how to use your Modulino Thermo, you're all set to integrate it into your projects! +Now that you've learned how to use your Modulino Thermo, try these projects: -- Experiment with temperature and humidity. What happens if you place your Modulino in the refrigerator? -- Try breathing near the sensor. Does the humidity change? -- Place your Modulino on the outside of your mug and fill it with a hot beverage. Can you create an automatic system to know when your tea has cooled down? -- How does the temperature change throughout the day at home? Let your Modulino run for an entire day and check out the data! \ No newline at end of file +- **Smart Greenhouse Monitor**: Track temperature and humidity for optimal plant growth +- **Weather Station**: Combine with other Modulinos to create a complete weather monitoring system +- **HVAC Controller**: Monitor room conditions and trigger heating/cooling systems +- **Food Storage Monitor**: Ensure proper conditions in pantries or wine cellars +- **Data Logger**: Record environmental conditions over time for analysis +- **Comfort Zone Indicator**: Use with Modulino Pixels to show comfort levels with colours +- **Morning Routine Assistant**: Check if the bathroom is warm enough before your shower +- **Pet Habitat Monitor**: Ensure reptile or tropical fish environments stay optimal \ No newline at end of file