Jump to content
Electronics-Lab.com Community

CETECH

Members
  • Posts

    47
  • Joined

  • Last visited

  • Days Won

    3

CETECH last won the day on October 4

CETECH had the most liked content!

2 Followers

Recent Profile Visitors

The recent visitors block is disabled and is not being shown to other users.

CETECH's Achievements

  1. In this detailed tutorial, we will walk through the process of integrating the Wio LoRa-E5 module with The Things Network (TTN) using MicroPython and Xiao ESP32-S3. This project will enable you to transmit data via LoRaWAN using the TTN as the backend for processing your LoRa data. The Wio LoRa-E5 module supports long-range LoRaWAN communication, while the Xiao ESP32-S3 is a powerful microcontroller with WiFi, Bluetooth, and enough power to run MicroPython efficiently. By the end of this tutorial, you'll have a functional IoT system capable of sending sensor data over LoRa to the TTN and visualizing it on a dashboard or storing it in the cloud. 📦 Prerequisites 🛠️ Hardware: 🛰️ Wio LoRa-E5 Module(STM32-based LoRa module) 🖥️ XIAO ESP32-S3 (compact ESP32 board) 🔗 Jumper wires for connecting the modules 📏 Breadboard for prototyping 🔌 USB Cables for flashing and power 🖥️ Software: Python 3.x installed on your PC for firmware flashing and serial communication Thonny IDE (or any MicroPython IDE of your choice) esptool (for flashing MicroPython firmware onto the ESP32-S3) MicroPython firmware for XIAO ESP32-S3 from [MicroPython.org](https://micropython.org/download/esp32/ Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. 🔧 Step 1: Flashing MicroPython on XIAO ESP32-S3 and Wio LoRa E5 🔥 Flashing MicroPython on XIAO ESP32-S3: 1. Download the MicroPython firmware for ESP32-S3 from (https://micropython.org/download/esp32/). Make sure to download the **ESP32-S3 specific firmware. 2. Install esptool: You'll need the esptool package to flash MicroPython on the ESP32-S3. Install it with: pip install esptool 3. Erase existing firmware on the XIAO ESP32-S3 by connecting it to your PC and running the following command: esptool.py --chip esp32s3 --port <your-port> erase_flash 4. Flash the MicroPython firmware: Replace `<your-port>` with the port the ESP32-S3 is connected to (e.g., `COM4` on Windows or `/dev/ttyUSB0` on Linux). Then, run: esptool.py --chip esp32s3 --port <your-port> write_flash -z 0x1000 esp32s3-<your-firmware>.bin 🚀 Flashing Wio LoRa-E5: The Wio LoRa-E5 module communicates primarily over UART using AT commands. You won't flash MicroPython onto it but will communicate with it through AT commands from the XIAO ESP32-S3. For detailed instructions on setting up the Wio-E5 with firmware, refer to the [Seeed Studio documentation] 🔌 Step 2: Wiring Connections Here’s how you can connect the **XIAO ESP32-S3** to the **Wio LoRa-E5** module using UART: Ensure that you connect the pins correctly, especially the TX and RX, as this will facilitate communication between the devices. 🔧 Step 3: Setting Up Thonny IDE for ESP32-S3 1. Download and install Thonny IDE if you haven't already. 2. Select **ESP32** as your MicroPython interpreter. 3. Plug in your XIAO ESP32-S3, and in Thonny, go to Tools > Options > Interpreter, then select the correct Port corresponding to your device (e.g., `COM3` on Windows or `/dev/ttyUSB0` on Linux). Verify the connection by running: print("Hello from XIAO ESP32-S3!") If the message prints to the terminal, you are connected! 🧑‍💻 Step 4: MicroPython Code to Communicate with LoRaWAN Network Now, we’ll write MicroPython code on the Xiao ESP32-S3 to send and receive data to/from the Wio-E5 for LoRa communication. # Connect to The Things Network (TTN) and publish some test data # Put your key here (string). This should match the AppKey generated by your application. #For example: app_key = 'E08B834FB0866939FC94CDCC15D0A0BE' app_key = 'E08B834FB0866939FC94CDCC15D0A0BE' # Regional LoRaWAN settings. You may need to modify these depending on your region. # If you are using AU915: Australia # band='AU915' # channels='8-15' # If you are using US915 # band='US915' # channels='8-15' # # If you are using EU868 band='EU868' channels='0-2' from machine import UART, Pin from utime import sleep_ms from sys import exit uart1 = UART(1, baudrate=9600, tx=Pin(43), rx=Pin(44)) join_EUI = None # These are populated by this script device_EUI = None ### Function Definitions def receive_uart(): '''Polls the uart until all data is dequeued''' rxData=bytes() while uart1.any()>0: rxData += uart1.read(1) sleep_ms(2) return rxData.decode('utf-8') def send_AT(command): '''Wraps the "command" string with AT+ and \r\n''' buffer = 'AT' + command + '\r\n' uart1.write(buffer) sleep_ms(300) def test_uart_connection(): '''Checks for good UART connection by querying the LoRa-E5 module with a test command''' send_AT('') # empty at command will query status data = receive_uart() if data == '+AT: OK\r\n' : print('LoRa radio is ready\n') else: print('LoRa-E5 detected\n') exit() def get_eui_from_radio(): '''Reads both the DeviceEUI and JoinEUI from the device''' send_AT('+ID=DevEui') data = receive_uart() device_EUI = data.split()[2] send_AT('+ID=AppEui') data = receive_uart() join_EUI = data.split()[2] print(f'JoinEUI: {join_EUI}\n DevEUI: {device_EUI}') def set_app_key(app_key): if app_key is None or app_key == 'None': print('\nGenerate an AppKey on cloud.thethings.network and enter it at the top of this script to proceed') exit() send_AT('+KEY=APPKEY,"' + app_key + '"') receive_uart() print(f' AppKey: {app_key}\n') def configure_regional_settings(band=None, DR='0', channels=None): ''' Configure band and channel settings''' send_AT('+DR=' + band) send_AT('+DR=' + DR) send_AT('+CH=NUM,' + channels) send_AT('+MODE=LWOTAA') receive_uart() # flush send_AT('+DR') data = receive_uart() print(data) def join_the_things_network(): '''Connect to The Things Network. Retry on failure.''' max_retries = 5 retry_count = 0 while retry_count < max_retries: send_AT('+JOIN') data = receive_uart() print(data) status = 'not connected' while status == 'not connected': data = receive_uart() if len(data) > 0: print(data) if 'joined' in data.split(): status = 'connected' break if 'failed' in data.split(): print('Join Failed. Retrying...') break sleep_ms(1000) if status == 'connected': break else: retry_count += 1 print(f"Retry {retry_count}/{max_retries} in 5 seconds...") sleep_ms(5000) if retry_count >= max_retries: print("Max retries exceeded. Giving up.") exit() def send_message(message): '''Send a string message''' send_AT('+MSG="' + message + '"') done = False while not done: data = receive_uart() if 'Done' in data or 'ERROR' in data: done = True if len(data) > 0: print(data) sleep_ms(1000) def send_hex(message): send_AT('+MSGHEX="' + message + '"') done = False while not done: data = receive_uart() if 'Done' in data or 'ERROR' in data: done = True if len(data) > 0: print(data) sleep_ms(1000) test_uart_connection() get_eui_from_radio() set_app_key(app_key) configure_regional_settings(band=band, DR='0', channels=channels) join_the_things_network() while True: # Send example data print("sending test messages") # Convert the random number to a hexadecimal string temp=100 payload = '{:04x}'.format(temp) payload1 = '{:04x}'.format(temp) CP = payload + payload1 print("payload : ", CP) # send_message("Hello World!") send_hex(CP) sleep_ms(5000) The device will attempt to join the LoRaWAN network. The response should confirm whether the join was successful. ⚙️ Step 5: Set Up The Things Network (TTN) Before we get into the hardware setup, let’s configure the application on **The Things Network** (TTN). TTN is a free, community-driven platform for LoRaWAN network services. 🛠️ 5.1 Create a TTN Account 1. Go to the [TTN Console](https://console.thethingsnetwork.org/), and sign up or log in. 2. Choose your **cluster** based on your region (e.g., **EU1**, **US1**). 🛠️ 5.2 Create an Application 1. In the TTN console, click on Applications and then Create an Application. 2. Fill in the details: - Application ID: A unique identifier for your application (e.g., `my-lora-project`). - Description: Optional, but a brief description is helpful (e.g., `Wio-E5 LoRa project`). 3. Once created, navigate to the application overview page. 🛠️ 5.3 Register Your Device 1. Under your application, click Devices → Register end device. 2. Choose a Manually registered device. 3. Fill in the fields: - DevEUI: A unique device identifier. This can be generated or obtained from your Wio-E5. - AppEUI: Use a standard TTN AppEUI or generate one. - AppKey Generate the application key. This key is essential for securely connecting your device to the network. 🧪 Step 6: Receiving Data via TTN Now look into the TTN console, you can see your device response. Next, we have to add a payload formatted to view our data. function Decoder(bytes, port) { var decoded = {}; if (port === 8) { decoded.temp = bytes[0] <<8 | bytes[1]; decoded.humi = bytes[2] <<8 | bytes[3]; } return decoded; } Finally, you can see your actual data in the TTN console. 🚀 Future Expansions: - Add Sensors: Connect sensors like temperature, humidity, or GPS to your Xiao ESP32-S3 and send this data to TTN. - Cloud Integration: Forward data from TTN to cloud platforms like AWS, Azure, or Google Cloud for further processing. - Data Visualization: Use platforms like Qubitro to visualize the incoming data from TTN. 🎉 Conclusion You’ve successfully integrated the Wio LoRa-E5 with The Things Network (TTN) using MicroPython and the Xiao ESP32-S3. You can now send data over LoRaWAN to the TTN, where it can be forwarded to cloud services, stored in databases, or visualized on a dashboard. Happy coding and building your LoRaWAN IoT applications! 🌍📡
  2. In this tutorial, we'll walk you through integrating **LoRa Wio E5** (a low-power, long-range LoRa module) with the **XIAO ESP32-S3** (a compact microcontroller with built-in WiFi and Bluetooth) using **MicroPython**. The goal is to establish LoRa communication between the devices, allowing you to create IoT applications with long-range, low-power data transfer capabilities. 📦 Prerequisites 🛠️ Hardware: 🛰️ Wio LoRa-E5 Module(STM32-based LoRa module) 🖥️ XIAO ESP32-S3 (compact ESP32 board) 🔗 Jumper wires for connecting the modules 📏 Breadboard for prototyping 🔌 USB Cables for flashing and power 🖥️ Software: Python 3.x installed on your PC for firmware flashing and serial communication Thonny IDE (or any MicroPython IDE of your choice) esptool (for flashing MicroPython firmware onto the ESP32-S3) MicroPython firmware for XIAO ESP32-S3 from [MicroPython.org](https://micropython.org/download/esp32/) UART AT command reference for Wio-E5 from Seeed Studio Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. 🔧 Step 1: Flashing MicroPython on XIAO ESP32-S3 and Wio LoRa E5 🔥 Flashing MicroPython on XIAO ESP32-S3: 1. Download the MicroPython firmware for ESP32-S3 from (https://micropython.org/download/esp32/). Make sure to download the **ESP32-S3 specific firmware. 2. Install esptool: You'll need the esptool package to flash MicroPython on the ESP32-S3. Install it with: pip install esptool 3. Erase existing firmware on the XIAO ESP32-S3 by connecting it to your PC and running the following command: esptool.py --chip esp32s3 --port <your-port> erase_flash 4. Flash the MicroPython firmware: Replace `<your-port>` with the port the ESP32-S3 is connected to (e.g., `COM4` on Windows or `/dev/ttyUSB0` on Linux). Then, run: esptool.py --chip esp32s3 --port <your-port> write_flash -z 0x1000 esp32s3-<your-firmware>.bin 🚀 Flashing Wio LoRa-E5: The Wio LoRa-E5 module communicates primarily over UART using AT commands. You won't flash MicroPython onto it but will communicate with it through AT commands from the XIAO ESP32-S3. For detailed instructions on setting up the Wio-E5 with firmware, refer to the [Seeed Studio documentation] 🔌 Step 2: Wiring Connections Here’s how you can connect the **XIAO ESP32-S3** to the **Wio LoRa-E5** module using UART: Ensure that you connect the pins correctly, especially the TX and RX, as this will facilitate communication between the devices. 🔧 Step 3: Setting Up Thonny IDE for ESP32-S3 1. Download and install Thonny IDE if you haven't already. 2. Select **ESP32** as your MicroPython interpreter. 3. Plug in your XIAO ESP32-S3, and in Thonny, go to Tools > Options > Interpreter, then select the correct Port corresponding to your device (e.g., `COM3` on Windows or `/dev/ttyUSB0` on Linux). Verify the connection by running: print("Hello from XIAO ESP32-S3!") If the message prints to the terminal, you are connected! 🧑‍💻 Step 4: Sending AT Commands from XIAO ESP32-S3 to Wio LoRa-E5 To communicate with the Wio LoRa-E5, you will use UART on the XIAO ESP32-S3 to send AT commands. Here’s a basic MicroPython script to initialize UART communication and send commands. MicroPython UART Communication Script: # P2P Transmitter Example from machine import UART, Pin from utime import sleep_ms uart1 = UART(1, baudrate=9600, tx=Pin(43), rx=Pin(44)) def echo(): rxData=bytes() while uart1.any()>0: rxData += uart1.read(1) print(rxData.decode('utf-8')) uart1.write('at+mode=test\n') # enter test mode sleep_ms(100) data = 0 while True: print("Send data:",data) uart1.write('at+test=txlrpkt,"{}"\n'.format(data)) # send test data sleep_ms(100) echo() # show debug data from LoRa-E5 module data += 1 # increment and loop test-data data = data % 255 print("") sleep_ms(1000) This script initializes UART communication on the XIAO ESP32-S3 and sends an AT command to the Wio LoRa-E5. The response is printed to the console. 🛠️ Step 5: Receiving Data on XIAO ESP32-S3 To receive data from the Wio LoRa-E5, you’ll need to listen for incoming messages using UART. The following script listens for LoRa messages: # P2P Receiver Example from machine import UART, Pin from utime import sleep_ms uart1 = UART(1, baudrate=9600, tx=Pin(4), rx=Pin(5)) def echo(): rxData=bytes() while uart1.any()>0: rxData += uart1.read(1) data = rxData.decode('utf-8') out = data.replace('+TEST: RXLRPKT','') print(out) uart1.write('at+mode=test\n') # enter test mode sleep_ms(100) while True: uart1.write('at+test=rxlrpkt\n') echo() # show debug data from LoRa-E5 module sleep_ms(1000) This script puts the Wio-E5 in receive mode and continuously listens for incoming messages. 🧪 Step 6: Testing Your Setup Now that both sending and receiving are set up: 1. Power up both devices. 2. Send a message from one device (e.g., "Hello LoRa!"). 3. Receive the message on the other device. 4. Verify that the message appears correctly on the receiving device's console. You can also monitor communication through Thonny IDE. 📚 Additional Enhancements Add Sensors: Connect environmental sensors (like temperature or humidity) to your XIAO ESP32-S3 to send real-world data over LoRa. Wi-Fi Gateway: Use the Wi-Fi capability of the ESP32-S3 to forward LoRa data to a cloud service like MQTT -Deep Sleep: Implement power-saving techniques by putting the ESP32-S3 in deep sleep mode to save battery life in remote applications. 🎉 Conclusion Congratulations! You've successfully integrated LoRa Wio-E5 with XIAO ESP32-S3 using MicroPython. This project enables you to build a wide range of long-range IoT applications, such as environmental monitoring, smart agriculture, or asset tracking. 🚀 Feel free to extend this project, add sensors, and explore the vast possibilities of LoRa and ESP32-S3.
  3. Hey, sound seekers and light chasers! 🎶👩‍🔧 Today, we’re diving into an electrifying project where sound meets lights: PDM microphone + NeoPixels + Xiao nRF52840 Sense. This project will turn sound waves into visual rainbows using the magic of electronics. And yes, we’ll make it as fun as possible because, honestly, flashing lights and sound-reactive gadgets are life. 😎 Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. What You'll Need 🛠️ First, let’s gather all the cool components you’ll need to bring this project to life: 1. Seeed Studio Xiao nRF52840 Sense 🌟 This microcontroller is a pocket-sized wizard! It’s got an onboard PDM microphone, Bluetooth, and an IMU. This means it can hear, move, and talk—kind of like a robot dog, but smaller. 🐕 Why this one? It’s the tiny titan for low-power, wireless projects. It’s also just about the size of a postage stamp—so it’ll fit anywhere! 2. NeoPixel LED Strip 🌈 These addressable RGB LEDs are the life of the party! 🎉 With these, we’ll light up based on sound levels picked up by the PDM microphone. Pro tip: The more LEDs, the more dramatic the light show. Let’s make it a mini-rave, shall we? 🎶💡 3. USB-C Cable, Jumper Wires, and a Breadboard 📦 Because we’re civilized makers, we’ll need a USB-C cable for programming and jumper wires for easy connections. Breadboards make things less messy—though messy is kinda fun too. 🤷‍♂️ Step 1: Flashing the Xiao nRF52840 Sense 🚀 Before diving into the exciting stuff, we’ve gotta get our Xiao ready. This step is like waking up your Xiao with a nice cup of coffee—let’s get that brain buzzing. ☕ Install Arduino IDE if you haven’t already. Don’t worry, it’s quick and painless. Install the Seeed Xiao nRF52840 boards via the Arduino IDE board manager. You’ll also need the Adafruit PDM and Adafruit NeoPixel libraries. Got it? Awesome! High-five! ✋ Now, plug in your Xiao using the USB-C cable, and let's get that code cooking. 🍳 Step 2: Connecting the NeoPixels and Microphone 🎤💡 Now let’s wire things up before jumping into the code. Connecting the NeoPixel Strip: VCC to 3.3V: Give the LEDs some juice! Hook up the VCC of your NeoPixel to the 3.3V pin on the Xiao. Ground to Ground: Can’t forget the GND connection—it’s like the BFF connection between components. 😇 Data to D6: Finally, connect the DIN (data input) on your NeoPixel strip to D6 on the Xiao. This is how your Xiao tells the NeoPixels to dance! Your wiring should now look like an electrical symphony 🎶 (or spaghetti, depending on your skills with jumper wires). Step 3: The Code – Making Lights Dance to Sound 💃✨ Now comes the magic trick: we turn sound into light. Using the PDM microphone on the Xiao nRF52840 Sense, we’ll capture sound and make our NeoPixels react accordingly. Here’s the code that does it all. Pop this into your Arduino IDE: #include <Adafruit_NeoPixel.h> #include <PDM.h> #define PIN 0 #define NUMPIXELS 64 Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); // buffer to read samples into, each sample is 16-bits short sampleBuffer[256]; // number of samples read volatile int samplesRead; void setup() { Serial.begin(9600); while (!Serial); pixels.begin(); pixels.setBrightness(51); // Set brightness to 20% (255 * 0.2 = 51) pixels.show(); // Initialize all pixels to 'off' // configure the data receive callback PDM.onReceive(onPDMdata); // initialize PDM with: // - one channel (mono mode) // - a 16 kHz sample rate if (!PDM.begin(1, 16000)) { Serial.println("Failed to start PDM!"); while (1) yield(); } } void loop() { // wait for samples to be read if (samplesRead) { // print samples to the serial monitor or plotter for (int i = 0; i < samplesRead; i++) { Serial.println(sampleBuffer[i]); } // Visualize the audio data on the NeoPixel matrix visualizeAudio(); // clear the read count samplesRead = 0; } } void onPDMdata() { // query the number of bytes available int bytesAvailable = PDM.available(); // read into the sample buffer PDM.read(sampleBuffer, bytesAvailable); // 16-bit, 2 bytes per sample samplesRead = bytesAvailable / 2; } void visualizeAudio() { // Find the maximum sample value int16_t maxSample = 0; for (int i = 0; i < samplesRead; i++) { if (abs(sampleBuffer[i]) > maxSample) { maxSample = abs(sampleBuffer[i]); } } // Increase sensitivity by adjusting the mapping range uint8_t brightness = map(maxSample, 0, 16384, 0, 255); // Adjusted from 32767 to 16384 uint32_t color = pixels.Color(brightness, 0, 255 - brightness); // Set all pixels to the mapped color for (int i = 0; i < NUMPIXELS; i++) { pixels.setPixelColor(i, color); } pixels.show(); } What’s Happening in the Code? 🤔 PDM Microphone Setup: We’re using Adafruit’s PDM library to capture sound. The microphone listens to the sound levels and records it as amplitude values. Sound to Light Mapping: We take the sound amplitude and map it to a color value, so louder sounds produce brighter or different-colored lights. 🎤🌈 NeoPixel Control: We use these color values to change the color of each NeoPixel based on how loud it is. The louder it gets, the more the lights go crazy! 💥 Step 4: Testing Time – Let’s Get Loud! 🔊 Time to plug and play: Plug the Xiao back in and upload the code. Clap, speak, or crank up your music! 🎶 Watch the NeoPixels react to the sound. The louder the noise, the more vibrant and crazy the colors will be. Your lights should be doing a mini dance show by now! 🙌 Pro Tip: If your lights aren’t reacting much, try increasing the gain on your PDM microphone in the code by using pdm.setGain(30) (or higher). Step 5: Add Some Flair! 🎨 Now that you’ve got the basic sound-reactive lights working, it’s time to spice things up a bit. Here are some ideas to take this project to the next level: 1. Use Bluetooth to Control Colors Remotely 📱 You’ve got Bluetooth onboard, so why not? Connect your phone to the Xiao and control the NeoPixels wirelessly. 2. Create a Wearable! 👗 Who wouldn’t want sound-reactive lights on a jacket or hat? Simply hook everything up to a portable battery, and you’re now a walking disco. Just… don’t wear it to meetings. 😅 3. Add Different Sound Effects 🎶 Modify the code to display different patterns or colors for specific sound frequencies (like bass, treble, etc.). You could even add different modes like “Bass Blast” or “Rainbow Dance”. Conclusion: Let the Party Begin! 🎉 Congratulations! 🎊 You’ve just turned sound into a colorful light show with PDM, NeoPixels, and the Xiao nRF52840 Sense. Now every sound in your room has a little more pizazz, and you’ve got a project you can show off to your friends! Remember: whether it’s a whisper or a booming bass, the lights will follow. 🌈 And now, it's your turn to experiment: try different light patterns, and sound effects, or even build an entire sound-reactive installation. The sky’s the limit, and the only rule is: the louder, the better. 💥
  4. Hey there, future Bluetooth Jedi! 🌟 Welcome to an electrifying project where we combine the magic of Web Bluetooth, the flashy brilliance of NeoPixels, and the awesome power of the Seeed Studio Xiao nRF52840 Sense. By the end of this journey, you'll be able to control a strip of NeoPixels right from your web browser. Yep, no more complicated apps or cables—just pure wireless awesomeness. 🎮✨ So, grab your soldering iron, a cup of coffee (or tea ☕), and let’s light things up! 🛠️ What You’ll Need: Before we dive into code and soldering, let's check if you have all the necessary gadgets to make this magic happen! 1. Seeed Studio Xiao nRF52840 Sense ⚡ Why this? It’s like a pocket-sized superhero! 💪 It's BLE-capable, has a built-in IMU, microphone, and is powered by the ARM Cortex-M4 processor. Small but mighty! 2. NeoPixel LED Strip 🌈 These RGB LEDs are the stars of our show. They can display millions of colors and are individually addressable. We’ll be using them to dazzle our friends (or just our cat 🐱). 3. Web Browser with Bluetooth Support 🌐 For this project, we need a web browser that supports Web Bluetooth API. Chrome, Edge, or Chromium-based browsers are perfect. Sorry, Firefox lovers... you'll have to switch sides for this one! 😅 4. Jumper Wires, Soldering Kit, and USB-C Cable 🔌 Standard build-essentials. These will help you hook up everything without blowing things up (which we totally don’t want). Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. Step 1: Setting Up Your Xiao nRF52840 Sense 📦 First, we need to make sure your Xiao is ready for action. Time to upload some code! Install the Development Environment: Install Arduino IDE from the official website if you already have it. Next, install the Seeed nRF52 boards in Arduino: Go to File > Preferences. Add this URL to Additional Boards Manager URLs: https://files.seeedstudio.com/arduino/package_seeeduino_boards_index.json Now head to Tools > Board > Boards Manager, search for Seeed nRF52 and install the package. Install Libraries: You’ll need to grab a couple of libraries to work with NeoPixels and BLE: Adafruit NeoPixel Library (to handle our shiny lights 💡) ArduinoBLE Library (for Bluetooth communication) Head to Tools > Manage Libraries and search for these to install them. Step 2: Wiring it Up 🧑‍🔧🔌 Alright, it's time to connect the Xiao to the NeoPixel strip. Don’t worry, this part is easier than figuring out which wire your headphones use! 🎧 Connect the NeoPixels to Xiao: Power (VCC): Connect this to the 3.3V pin on the Xiao. Ground (GND): GND to GND (these two are like peanut butter and jelly 🥪—inseparable). Data In (DIN): Hook this up to Pin D0 on the Xiao. Everything wired up? Awesome! Now the fun begins. 🧙‍♂️✨ Step 3: Code Time! ⌨️💻 Let's dive into the code that will make your Xiao and NeoPixels dance to your commands (remotely via Bluetooth!). 🕺💃 Here's the plan: The Xiao will advertise itself as a Bluetooth device. Your browser (with Web Bluetooth) will connect to it and control the NeoPixel strip by sending color commands Here's the Arduino Sketch: #include <ArduinoBLE.h> #include <Adafruit_NeoPixel.h> #define NEOPIXEL_PIN 0 #define NUM_PIXELS 64 Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_PIXELS, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800); BLEService ledService("19b10000-e8f2-537e-4f6c-d104768a1214"); BLEByteCharacteristic ledCharacteristic("19b10001-e8f2-537e-4f6c-d104768a1214", BLEWrite | BLERead); void setup() { Serial.begin(115200); if (!BLE.begin()) { Serial.println("starting BLE failed!"); while (1); } BLE.setLocalName("XIAO-LED"); BLE.setAdvertisedService(ledService); ledService.addCharacteristic(ledCharacteristic); BLE.addService(ledService); ledCharacteristic.writeValue(0); strip.begin(); strip.show(); BLE.advertise(); Serial.println("Bluetooth device active, waiting for connections..."); } void loop() { BLEDevice central = BLE.central(); if (central) { Serial.print("Connected to central: "); Serial.println(central.address()); while (central.connected()) { if (ledCharacteristic.written()) { uint8_t ledState = ledCharacteristic.value(); if (ledState == 1) { digitalWrite(LED_BUILTIN, HIGH); // Turn LED on for (int i = 0; i < NUM_PIXELS; i++) { strip.setPixelColor(i, strip.Color(255, 255, 255)); strip.show(); } } else { digitalWrite(LED_BUILTIN, LOW); // Turn LED off for (int i = 0; i < NUM_PIXELS; i++) { strip.setPixelColor(i, strip.Color(0, 0, 0)); strip.show(); } } } } Serial.print("Disconnected from central: "); Serial.println(central. Address()); } } What Does This Code Do? 🧐 BLE Advertising: Your Xiao advertises itself as "NeoPixelController" via Bluetooth. BLE Service: We create a custom Bluetooth service that listens for commands (color changes) from a web browser. NeoPixel Control: Based on the color data sent by the browser, the NeoPixel LEDs change colors accordingly. Step 4: Build the Web Bluetooth Interface 🌐 Now we move to the browser side, creating a simple webpage that will scan for your Xiao and send color commands via Bluetooth. Here’s a basic HTML + JavaScript setup: <!DOCTYPE html> <html> <head> <title>Web Bluetooth LED Control</title> </head> <body> <button id="connect">Connect</button> <button id="on">Turn On</button> <button id="off">Turn Off</button> <script> let ledCharacteristic; document.getElementById('connect').addEventListener('click', async () => { try { const device = await navigator.bluetooth.requestDevice({ filters: [{ name: 'XIAO-LED' }], optionalServices: ['19b10000-e8f2-537e-4f6c-d104768a1214'] }); const server = await device.gatt.connect(); const service = await server.getPrimaryService('19b10000-e8f2-537e-4f6c-d104768a1214'); ledCharacteristic = await service.getCharacteristic('19b10001-e8f2-537e-4f6c-d104768a1214'); console.log('Connected to device'); } catch (error) { console.error('Error:', error); } }); document.getElementById('on').addEventListener('click', async () => { if (ledCharacteristic) { try { await ledCharacteristic.writeValue(Uint8Array.of(1)); console.log('LED turned on'); } catch (error) { console.error('Error turning on LED:', error); } } }); document.getElementById('off').addEventListener('click', async () => { if (ledCharacteristic) { try { await ledCharacteristic.writeValue(Uint8Array.of(0)); console.log('LED turned off'); } catch (error) { console.error('Error turning off LED:', error); } } }); </script> </body> </html> How This Works: The page contains a button to connect to the Xiao via Bluetooth. Once connected, you can use the on and off buttons to control the LED. Step 5: Time to Shine! ✨💡 Now for the moment of truth: test your project! 🚀 Upload the Arduino code to your Xiao nRF52840 Sense. Open the HTML file in a supported browser (like Chrome). Click the "Connect to Xiao" button, and select the device from the Bluetooth device list. Slide the color picker, and watch the magic happen! 🪄✨ Your NeoPixels should change colors as you adjust the slider. Wireless LED control, baby! Step 6: Add Your Own Magic ✨ Congrats, you've just controlled a strip of NeoPixels via Web Bluetooth! 🎉 But why stop there? Here are some ways to level up: Add color animations: How about some rainbow patterns or breathing effects? 🌈 IMU Integration: Use the onboard IMU to control the lights based on motion. You can dance and let the LEDs react to your moves! 🕺 Build a Web Dashboard: Make the webpage more interactive by adding buttons for pre-defined light patterns (disco mode, anyone?). Conclusion: The Wireless Wonderland 🎆 With Web Bluetooth and the Xiao nRF52840, you’ve unlocked the secret to controlling LEDs without touching a wire! 🎮 Whether you're jazzing up your living room, building smart home gadgets, or just flexing at your next tech meetup, you're officially in control of the light show! 👨‍💻👩‍💻 So go on, experiment, and make your project shine brighter than a disco ball at a retro party! 💃✨ Happy hacking, and keep shining! 🌟
  5. Hello tech adventurers! 🧑‍🔧👩‍💻 If you're here, you're probably itching to light up the world, or at least your room, with some rainbow colors! And how? By combining a motion sensor (IMU), a tiny powerhouse microcontroller, and some shiny NeoPixels. 🌈 Buckle up—it's going to be fun and flashy (literally)! What You'll Need 🛠️ Let's kick off by grabbing all the cool gear for this project. Make sure your toolbox is stocked with: 1. Seeed Studio Xiao nRF52840 Sense ⚡ This tiny microcontroller is a superstar! It’s Bluetooth-capable, runs on a Cortex-M4 processor, and is small enough to get lost in your pocket! Not that you'd want that... 🙄 Why this one? It's packed with an onboard microphone, IMU (Inertial Measurement Unit), and Bluetooth LE, which means we’re going wireless, baby! 🎤🏃‍♂️ 2. NeoPixel LED Panel 💡 These are individually addressable RGB LEDs that can light up in any color your heart desires. We’ll be using these bad boys to visualize our IMU's data. They’re essentially the party piece of this project! 🎉 3. IMU (Inertial Measurement Unit) 📐 Already built into the Xiao nRF52840 Sense! This sensor detects motion, so you can do cool stuff like control your NeoPixels based on tilts and shakes. Think of it like a magic wand for LEDs. 4. Jumper Wires, Soldering Kit, and USB-C Cable 🧰 You know the drill. We need these to hook up everything without too much of a spaghetti mess on your desk. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. Step 1: Flashing the Xiao nRF52840 Sense 🚀 Getting it Talking! Start by setting up your development environment. You’ll want to upload the code to your Xiao, but first, you need to flash the microcontroller with the right firmware. Install the necessary tools: Head to Seeed Studio and grab their official setup guide for the Xiao nRF52840 Sense. You’ll need Arduino IDE and Xiao's board libraries. Piece of cake, right? 🍰 Pro Tip: When uploading code, if your microcontroller throws a tantrum and doesn’t show up on your PC, double-tap the reset button to enter bootloader mode. It’s like giving it a calming tea break. 🫖 Step 2: Wiring it up 🧑‍🔧 Time to bring these components together like a superhero team-up! 🦸‍♂️ Connect the NeoPixel to the Xiao: Power: Connect the VCC pin of the NeoPixel to the 3.3V pin of the Xiao. Ground: GND to GND (it’s like their secret handshake 🤝). Data: Hook the DIN (data in) pin from the NeoPixel to Pin D6 on the Xiao. Voilà, you’ve wired up your light show! Now, don’t plug it in just yet. Patience, young padawan. 🧘‍♂️ Step 3: Code Time! ⌨️👾 We’re diving into the fun part—the code! This is where the Xiao's IMU will tell the NeoPixels how to light up depending on the motion. Setting Up Libraries: Make sure you have these libraries installed in your Arduino IDE: Adafruit NeoPixel (to control those flashy lights) 🌈 Wire.h (for I2C communication) Seeed nRF52 board libraries (to work with Xiao) Adafruit Sensor for handling IMU data. #include <Adafruit_NeoPixel.h> #include <LSM6DS3.h> #include <Wire.h> #define PIN 0 #define NUMPIXELS 64 Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); LSM6DS3 myIMU(I2C_MODE, 0x6A); // I2C device address 0x6A float aX, aY, aZ, gX, gY, gZ; const float accelerationThreshold = 2.5; // threshold of significant in G's const int numSamples = 119; int samplesRead = numSamples; void setup() { Serial.begin(9600); while (!Serial); pixels.begin(); pixels.show(); // Initialize all pixels to 'off' // Call .begin() to configure the IMU if (myIMU.begin() != 0) { Serial.println("Device error"); } else { Serial.println("aX,aY,aZ,gX,gY,gZ"); } } void loop() { // wait for significant motion while (samplesRead == numSamples) { // read the acceleration data aX = myIMU.readFloatAccelX(); aY = myIMU.readFloatAccelY(); aZ = myIMU.readFloatAccelZ(); // sum up the absolutes float aSum = fabs(aX) + fabs(aY) + fabs(aZ); // check if it's above the threshold if (aSum >= accelerationThreshold) { // reset the sample read count samplesRead = 0; break; } } // check if all the required samples have been read since // the last time the significant motion was detected while (samplesRead < numSamples) { // read the acceleration and gyroscope data aX = myIMU.readFloatAccelX(); aY = myIMU.readFloatAccelY(); aZ = myIMU.readFloatAccelZ(); gX = myIMU.readFloatGyroX(); gY = myIMU.readFloatGyroY(); gZ = myIMU.readFloatGyroZ(); samplesRead++; // print the data in CSV format Serial.print(aX, 3); Serial.print(','); Serial.print(aY, 3); Serial.print(','); Serial.print(aZ, 3); Serial.print(','); Serial.print(gX, 3); Serial.print(','); Serial.print(gY, 3); Serial.print(','); Serial.print(gZ, 3); Serial.println(); // Visualize the IMU data on the NeoPixel matrix visualizeIMU(aX, aY, aZ, gX, gY, gZ); if (samplesRead == numSamples) { // add an empty line if it's the last sample Serial.println(); } } } void visualizeIMU(float aX, float aY, float aZ, float gX, float gY, float gZ) { // Map the acceleration and gyroscope data to colors uint8_t red = map(fabs(aX) * 100, 0, 250, 0, 255); uint8_t green = map(fabs(aY) * 100, 0, 250, 0, 255); uint8_t blue = map(fabs(aZ) * 100, 0, 250, 0, 255); // Set all pixels to the mapped color for (int i = 0; i < NUMPIXELS; i++) { pixels.setPixelColor(i, pixels.Color(red, green, blue)); } pixels. Show(); } What's Happening in the Code? 🤔 The IMU is your sensor. We’re reading acceleration data on all three axes: X, Y, and Z. The NeoPixels are the output. We map the motion detected by the IMU into a color value (RGB). Mapping Motion to Color: We sum up the absolute values of the accelerations to determine how hard you shake or tilt the Xiao. More movement = crazier colors! 🎨 Step 4: Test, Shake, and Dance! 🕺 Once your code is uploaded, unplug the USB and plug it back in (just to give your Xiao a little reset!). Now the magic begins. 🤹‍♂️ Testing the Tilt: Pick up your Xiao nRF52840 and gently tilt it. You’ll see the NeoPixels lighting up in different colors. Shake it a bit more—see the color change? Now you’re in charge of the show! If everything worked out, congrats, you’re now officially a NeoPixel DJ! 🎧🎶 Want to sync it with music and start a rave? Go ahead! The only limit is your creativity (and the brightness tolerance of your neighbors... 😅). Step 5: Going Wireless with Bluetooth! 📡 Now let’s take it one step further. What if you could control this with your phone? Here’s where the Bluetooth capability of the Xiao nRF52840 Sense comes into play. Using Bluetooth Low Energy (BLE), you can send motion data directly from your Xiao to an app on your phone—or even control the colors remotely! The Xiao makes it super easy to set up BLE communication, and you can find libraries in Arduino to help with this. Conclusion: Welcome to the Sparkle Party! 🎆🎉 Now that you've brought your NeoPixels to life with motion-sensing IMU data, it's time to celebrate! This project opens up a world of possibilities—from creating interactive lighting for your room, and costumes, or even building motion-reactive wearables. The only thing left is to challenge yourself—can you use this setup to control music lights at a party? Sync with game controllers? Make a dancing robot? The world’s your oyster, and the lights are your magic wand! 🧙‍♂️✨ Happy making, and may your LEDs forever shine bright!
  6. Imagine having a device that can measure the intensity of sunlight and send you alerts on Telegram whenever the sunlight reaches a certain level. This project will guide you through building such a device using the Beetle ESP32 C6 and the Grove Sunlight Intensity Sensor. Let’s get started! 🚀 Materials Needed 🛠️ Beetle ESP32 C6: A compact and powerful microcontroller. Grove Sunlight Intensity Sensor: A sensor capable of detecting UV, visible, and infrared light. Jumper wires: For connections. USB Type-C cable: To power and program the Beetle ESP32 C6. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. Step 1: Hardware Setup 🔧 Connect the Sunlight Sensor: Plug the Grove Sunlight Intensity Sensor into one of the Beetle. The I2C ports are usually labeled and color-coded for convenience. Power the Board: Connect the Beetle ESP32 C6 to a power source using the USB Type-C cable. You can use a battery or a USB power bank if you want to make your setup portable. Step 2: Software Setup 💻 Install Arduino IDE: If you haven’t already, download and install the Arduino IDE from the official website. Add ESP32 Board to Arduino IDE: Open Arduino IDE and go to File > Preferences. In the “Additional Board Manager URLs” field, add: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json. Go to Tools > Board > Board Manager, search for “ESP32”, and install the ESP32 board package. Select the Beetle ESP32 C6 Board: Go to Tools > Board and select Beetle ESP32 C6. Choose the correct port from Tools > Port. Step 3: Coding 👨‍💻 Install Required Libraries: Open Arduino IDE and go to Sketch > Include Library > Manage Libraries. Search for and install the following libraries: Grove_Sunlight_Sensor WiFi UniversalTelegramBot Write the Sunlight Intensity Detection Code: #include "Si115X.h" Si115X si1151; void setup() { Serial.begin(115200); if (!si1151.Begin()) { Serial.println("Si1151 is not ready!"); while (1) { delay(1000); Serial.print("."); }; } else { Serial.println("Si1151 is ready!"); } } void loop() { Serial.print("IR: "); Serial.println(si1151.ReadIR()); Serial.print("Visible: "); Serial.println(si1151.ReadVisible()); delay(500); } Step 4: Upload and Test 🚀 Upload the Code: Connect your Beetle ESP32 C6 to your computer and upload the code using the Arduino IDE. Test the Sensor: Once the code is uploaded, the sensor will start measuring sunlight intensity. Step 5: Setting Up Telegram Bot 📲 Create a Telegram Bot: Open Telegram and search for BotFather. Start a chat with BotFather and use the command /newbot to create a new bot. Follow the instructions to get your bot token. Get Your Chat ID: Start a chat with your bot and send any message. Look for the chat object in the response to find your chat ID. Final Sketch #include <WiFi.h> #include <WiFiClientSecure.h> #include <UniversalTelegramBot.h> // Universal Telegram Bot Library written by Brian Lough: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot #include <ArduinoJson.h> #include "Si115X.h" // Replace with your network credentials const char* ssid = "ELDRADO"; const char* password = "amazon123"; // Use @myidbot to find out the chat ID of an individual or a group // Also note that you need to click "start" on a bot before it can #define CHAT_ID "XXXXXXXXXXXXX" // Initialize Telegram BOT #define BOTtoken "XXXXXXXXXXXXX" // your Bot Token (Get from Botfather) float uv; float light; Si115X si1151; WiFiClientSecure client; UniversalTelegramBot bot(BOTtoken, client); //Checks for new messages every 1 second. int botRequestDelay = 1000; unsigned long lastTimeBotRan; // Get BME280 sensor readings and return them as a String variable String getReadings(){ uv = si1151.ReadIR(); light = si1151.ReadVisible(); String message = "UV Intencity: " + String(uv) + " \n"; message += "Visible Light: " + String (light) + " \n"; return message; } //Handle what happens when you receive new messages void handleNewMessages(int numNewMessages) { Serial.println("handleNewMessages"); Serial.println(String(numNewMessages)); for (int i=0; i<numNewMessages; i++) { // Chat id of the requester String chat_id = String(bot.messages[i].chat_id); if (chat_id != CHAT_ID){ bot.sendMessage(chat_id, "Unauthorized user", ""); continue; } // Print the received message String text = bot.messages[i].text; Serial.println(text); String from_name = bot.messages[i].from_name; if (text == "/start") { String welcome = "Welcome, " + from_name + ".\n"; welcome += "Use the following command to get current readings.\n\n"; welcome += "/readings \n"; bot.sendMessage(chat_id, welcome, ""); } if (text == "/readings") { String readings = getReadings(); bot.sendMessage(chat_id, readings, ""); } } } void setup() { Serial.begin(115200); if (!si1151.Begin()) { Serial.println("Si1151 is not ready!"); while (1) { delay(1000); Serial.print("."); }; } else { Serial.println("Si1151 is ready!"); } // Connect to Wi-Fi WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); #ifdef ESP32 client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org #endif while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } // Print ESP32 Local IP Address Serial.println(WiFi.localIP()); } void loop() { if (millis() > lastTimeBotRan + botRequestDelay) { int numNewMessages = bot.getUpdates(bot.last_message_received + 1); while(numNewMessages) { Serial.println("got response"); handleNewMessages(numNewMessages); numNewMessages = bot.getUpdates(bot.last_message_received + 1); } lastTimeBotRan = millis(); } } Detailed Explanation of the Code 📝 Libraries and Credentials: The code includes the necessary sensor, Wi-Fi, and Telegram bot libraries. Replace the placeholders with your Wi-Fi credentials and Telegram bot token. #include <WiFi.h> #include <WiFiClientSecure.h> #include <UniversalTelegramBot.h> // Universal Telegram Bot Library written by Brian Lough: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot #include <ArduinoJson.h> #include "Si115X.h" // Replace with your network credentials const char* ssid = "ELDRADO"; const char* password = "amazon123"; // Use @myidbot to find out the chat ID of an individual or a group // Also note that you need to click "start" on a bot before it can #define CHAT_ID "77777777" // Initialize Telegram BOT #define BOTtoken "jkjkklkkllkl:ffghhyjjkkjkkkl" // your Bot Token (Get from Botfather) Sensor Initialization: The setup() function initializes the serial communication, connects to Wi-Fi, and sets up the sunlight sensor. void setup() { Serial.begin(115200); if (!si1151.Begin()) { Serial.println("Si1151 is not ready!"); while (1) { delay(1000); Serial.print("."); }; } else { Serial.println("Si1151 is ready!"); } // Connect to Wi-Fi WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); #ifdef ESP32 client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org #endif while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } // Print ESP32 Local IP Address Serial.println(WiFi.localIP()); } Reading Sensor Data: In the loop() function, the sensor readings for UV, visible, and IR light are obtained and printed to the serial monitor. String getReadings(){ uv = si1151.ReadIR(); light = si1151.ReadVisible(); String message = "UV Intencity: " + String(uv) + " \n"; message += "Visible Light: " + String (light) + " \n"; return message; } Sending Telegram Alerts: If the UV index exceeds a specified threshold (e.g., 5.0), a message is sent to your Telegram bot with the current UV index. } void handleNewMessages(int numNewMessages) { Serial.println("handleNewMessages"); Serial.println(String(numNewMessages)); for (int i=0; i<numNewMessages; i++) { // Chat id of the requester String chat_id = String(bot.messages[i].chat_id); if (chat_id != CHAT_ID){ bot.sendMessage(chat_id, "Unauthorized user", ""); continue; } // Print the received message String text = bot.messages[i].text; Serial.println(text); String from_name = bot.messages[i].from_name; if (text == "/start") { String welcome = "Welcome, " + from_name + ".\n"; welcome += "Use the following command to get current readings.\n\n"; welcome += "/readings \n"; bot.sendMessage(chat_id, welcome, ""); } if (text == "/readings") { String readings = getReadings(); bot.sendMessage(chat_id, readings, ""); } } Delay: The delay(10000) function ensures that the sensor readings and alerts are checked every minute. Conclusion 🎉 Congratulations! You’ve successfully built a sunlight intensity detector with the Beetle ESP32 C6 and the Grove Sunlight Intensity Sensor, complete with Telegram alerts. This project can be expanded further by adding sensors or integrating with other IoT platforms. Feel free to share your project and any modifications you make. Happy building! 🛠️
  7. In this project, we’ll build a wireless UV intensity monitor that uses the Beetle ESP32 C6 and the Grove Sunlight Sensor. We’ll leverage the ESP-NOW protocol for efficient, low-latency communication between devices. This setup will allow you to monitor UV intensity remotely and receive real-time updates. Let’s dive into the details! 🚀 Materials Needed 🛠️ Beetle ESP32 C6: A compact and powerful microcontroller. Grove Sunlight Intensity Sensor: A sensor capable of detecting UV, visible, and infrared light. Grove Base Shield: To easily connect the sensor to the Beetle ESP32 C6. Jumper wires: For connections. USB Type-C cable: To power and program the Beetle ESP32 C6. Power source: A battery or USB power bank for portability. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. Step 1: Hardware Setup 🔧 Connect the TFT Display to the FireBeetle: Attach the TFT screen to the FireBeetle ESP32 C6. This shield simplifies the data visualization form Grove sensors and modules. Connect the Sunlight Sensor: Plug the Grove Sunlight Intensity Sensor into one of the I2C ports on the Beetle ESP32 C6. The I2C ports are usually labeled and color-coded for convenience. Power the Board: Connect the boards to a power source using the USB Type-C cable. You can use a battery or a USB power bank if you want to make your setup portable. Step 2: Software Setup 💻 Install Arduino IDE: If you haven’t already, download and install the Arduino IDE from the official website. Add ESP32 Board to Arduino IDE: Open Arduino IDE and go to File > Preferences. In the “Additional Board Manager URLs” field, add: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json. Go to Tools > Board > Board Manager, search for “ESP32”, and install the ESP32 board package. Select the Beetle ESP32 C6 Board: Go to Tools > Board and select Beetle ESP32 C6. Choose the correct port from Tools > Port. Step 3: Setting Up ESP-NOW Communication 📡 Understanding ESP-NOW: ESP-NOW is a wireless communication protocol developed by Espressif. It allows multiple ESP32 devices to communicate with each other without the need for Wi-Fi or a router. It operates as a peer-to-peer (P2P) protocol, meaning it allows direct communication between devices. Configuring ESP-NOW: In the setup function, initialize ESP-NOW and register a callback function to handle the status of sent data. Add peers to the ESP-NOW network by specifying their MAC addresses. Change the receiver FireBeetles MAC address in the transmitter code. Step 4: Coding 👨‍💻 Install Required Libraries: Open Arduino IDE and go to Sketch > Include Library > Manage Libraries. Search for and install the following libraries: Grove_Sunlight_Sensor WiFi ESP-NOW Write the UV Intensity Monitoring Transmitter Code: #include <esp_now.h> #include <WiFi.h> #include "Si115X.h" Si115X si1151; // REPLACE WITH YOUR RECEIVER MAC Address uint8_t broadcastAddress[] = {0x54, 0x32, 0x04, 0x08, 0x1E, 0xFC}; // Structure example to send data // Must match the receiver structure typedef struct struct_message { float a; float b; } struct_message; // Create a struct_message called myData struct_message myData; esp_now_peer_info_t peerInfo; // callback when data is sent void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { Serial.print("\r\nLast Packet Send Status:\t"); Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); } void setup() { // Init Serial Monitor Serial.begin(115200); if (!si1151.Begin()) { Serial.println("Si1151 is not ready!"); while (1) { delay(1000); Serial.print("."); }; } else { Serial.println("Si1151 is ready!"); } // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); // Init ESP-NOW if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; } // Once ESPNow is successfully Init, we will register for Send CB to // get the status of Trasnmitted packet esp_now_register_send_cb(OnDataSent); // Register peer memcpy(peerInfo.peer_addr, broadcastAddress, 6); peerInfo.channel = 0; peerInfo.encrypt = false; // Add peer if (esp_now_add_peer(&peerInfo) != ESP_OK) { Serial.println("Failed to add peer"); return; } } void loop() { Serial.print("IR: "); Serial.println(si1151.ReadIR()); Serial.print("Visible: "); Serial.println(si1151.ReadVisible()); // Set values to send myData.a = si1151.ReadIR(); myData.b = si1151.ReadVisible(); // Send message via ESP-NOW esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData)); if (result == ESP_OK) { Serial.println("Sent with success"); } else { Serial.println("Error sending the data"); } delay(2000); } Write the UV Intensity Monitoring Receiver Code: #include <esp_now.h> #include <WiFi.h> #include "DFRobot_GDL.h" #define TFT_DC D2 #define TFT_CS D6 #define TFT_RST D3 DFRobot_ST7789_240x320_HW_SPI screen(/*dc=*/TFT_DC, /*cs=*/TFT_CS, /*rst=*/TFT_RST); int led = 15; // Structure example to receive data // Must match the sender structure typedef struct struct_message { float a; float b; } struct_message; // Create a struct_message called myData struct_message myData; // callback function that will be executed when data is received void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) { memcpy(&myData, incomingData, sizeof(myData)); Serial.print("Bytes received: "); Serial.println(myData.a); float a1 =myData.a; Serial.print("Float: "); Serial.println(myData.b); Serial.print("Float: "); float b1 =myData.b; Serial.println(); int16_t color = 0x00FF; screen.setTextWrap(false); screen.setRotation(1); screen.fillScreen(COLOR_RGB565_BLACK); screen.setTextColor(COLOR_RGB565_GREEN); screen.setFont(&FreeMono9pt7b); screen.setTextSize(1.5); screen.setCursor(20, 30); screen.println(" --UV Intensity Meter-- "); screen.setCursor(0, 60); screen.println("UV: "); screen.setCursor(0, 90); screen.println("Light: "); screen.setTextColor(COLOR_RGB565_RED); screen.setCursor(135, 60); screen.println(a1); screen.setCursor(195, 60); screen.setCursor(135, 90); screen.println(b1); screen.setCursor(195, 90); digitalWrite(led, HIGH); } void setup() { // Initialize Serial Monitor Serial.begin(115200); screen.begin(); Wire.begin(); pinMode(led, OUTPUT); // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); // Init ESP-NOW if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; } // Once ESPNow is successfully Init, we will register for recv CB to // get recv packer info esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv)); } void loop() { } Step 5: Upload and Test 🚀 Upload the Code: Connect your Transmitter code Beetle ESP32 C6 and Receiver code to FireBeetle ESP32 C6 to your computer and upload the code using the Arduino IDE. Test the Sensor: Once the code is uploaded, the sensor will start measuring UV intensity and send the data wirelessly using the ESP-NOW protocol let's see the response from the serial terminal. Transmitter Response: Receiver Response: Detailed Explanation of the Code 📝 Libraries and Initialization: The code includes the necessary sensor, Wi-Fi, and ESP-NOW libraries. The sensor is initialized in the setup() function. Reading Sensor Data: In the loop() function, the sensor readings for UV, visible, and IR light are obtained and printed to the serial monitor. Sending Data via ESP-NOW: The sensor data is sent to a peer device using the ESP-NOW protocol. The OnDataSent callback function handles the status of the sent data. Delay: The delay(10000) function ensures that the sensor readings and data transmission occur every minute. Conclusion 🎉 Congratulations! You’ve successfully built a wireless UV intensity monitor with the Beetle ESP32 C6 and the Grove Sunlight Intensity Sensor, using the ESP-NOW protocol for communication. This project can be expanded further by adding sensors or integrating with other IoT platforms. Feel free to share your project and any modifications you make. Happy building! 🛠️
  8. Ever wanted to capture the beauty of a sunset, the hustle and bustle of a busy street, or the growth of a plant in a fun and creative way? With the Xiao ESP32 S3 Sense, you can build your very own timelapse camera! This tiny yet powerful board is perfect for capturing stunning timelapse videos. Let’s dive into this exciting project step-by-step. 🚀 Materials Needed 🛠️ Xiao ESP32 S3 Sense: The brain of our project. Camera module: Included with the Xiao ESP32 S3 Sense. MicroSD card: For storing your amazing timelapse photos (formatted to FAT32). USB Type-C cable: To power up your board. Power source: A battery or USB power bank for portability. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. Step 1: Hardware Setup 🔧 Connect the Camera Module: Attach the camera module to the Xiao ESP32 S3 Sense board. Make sure it’s snug and secure. Insert the MicroSD Card: Pop the formatted MicroSD card into the slot on the Xiao ESP32 S3 Sense. Power the Board: Plug in the Xiao ESP32 S3 Sense using the USB Type-C cable. You can use a battery or a USB power bank if you want to take your camera on the go. Step 2: Software Setup 💻 Install Arduino IDE: If you haven’t already, download and install the Arduino IDE from the official website. Add ESP32 Board to Arduino IDE: Open Arduino IDE and go to File > Preferences. In the “Additional Board Manager URLs” field, add: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json. Go to Tools > Board > Board Manager, search for “ESP32”, and install the ESP32 board package. Select the Xiao ESP32 S3 Sense Board: Go to Tools > Board and select Xiao ESP32 S3 Sense. Choose the correct port from Tools > Port. Step 3: Coding 👨‍💻 Install Required Libraries: Open Arduino IDE and go to examples and ESP32 CAM then Camera Web Server: Just replace the complete ino file with the following code Arduino Code: #include "esp_camera.h" #include "FS.h" #include "SD.h" #include "SPI.h" #define CAMERA_MODEL_XIAO_ESP32S3 // Has PSRAM #include "camera_pins.h" unsigned long lastCaptureTime = 0; // Last shooting time int imageCount = 1; // File Counter bool camera_sign = false; // Check camera status bool sd_sign = false; // Check sd status // Save pictures to SD card void photo_save(const char * fileName) { // Take a photo camera_fb_t *fb = esp_camera_fb_get(); if (!fb) { Serial.println("Failed to get camera frame buffer"); return; } // Save photo to file writeFile(SD, fileName, fb->buf, fb->len); // Release image buffer esp_camera_fb_return(fb); Serial.println("Photo saved to file"); } // SD card write file void writeFile(fs::FS &fs, const char * path, uint8_t * data, size_t len){ Serial.printf("Writing file: %s\n", path); File file = fs.open(path, FILE_WRITE); if(!file){ Serial.println("Failed to open file for writing"); return; } if(file.write(data, len) == len){ Serial.println("File written"); } else { Serial.println("Write failed"); } file.close(); } void setup() { Serial.begin(115200); while(!Serial); // When the serial monitor is turned on, the program starts to execute camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = 20000000; config.frame_size = FRAMESIZE_UXGA; config.pixel_format = PIXFORMAT_JPEG; // for streaming config.grab_mode = CAMERA_GRAB_WHEN_EMPTY; config.fb_location = CAMERA_FB_IN_PSRAM; config.jpeg_quality = 12; config.fb_count = 1; // if PSRAM IC present, init with UXGA resolution and higher JPEG quality // for larger pre-allocated frame buffer. if(config.pixel_format == PIXFORMAT_JPEG){ if(psramFound()){ config.jpeg_quality = 10; config.fb_count = 2; config.grab_mode = CAMERA_GRAB_LATEST; } else { // Limit the frame size when PSRAM is not available config.frame_size = FRAMESIZE_SVGA; config.fb_location = CAMERA_FB_IN_DRAM; } } else { // Best option for face detection/recognition config.frame_size = FRAMESIZE_240X240; #if CONFIG_IDF_TARGET_ESP32S3 config.fb_count = 2; #endif } // camera init esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { Serial.printf("Camera init failed with error 0x%x", err); return; } camera_sign = true; // Camera initialization check passes // Initialize SD card if(!SD.begin(21)){ Serial.println("Card Mount Failed"); return; } uint8_t cardType = SD.cardType(); // Determine if the type of SD card is available if(cardType == CARD_NONE){ Serial.println("No SD card attached"); return; } Serial.print("SD Card Type: "); if(cardType == CARD_MMC){ Serial.println("MMC"); } else if(cardType == CARD_SD){ Serial.println("SDSC"); } else if(cardType == CARD_SDHC){ Serial.println("SDHC"); } else { Serial.println("UNKNOWN"); } sd_sign = true; // sd initialization check passes Serial.println("Photos will begin in one minute, please be ready."); } void loop() { // Camera & SD available, start taking pictures if(camera_sign && sd_sign){ // Get the current time unsigned long now = millis(); //If it has been more than 1 minute since the last shot, take a picture and save it to the SD card if ((now - lastCaptureTime) >= 60000) { char filename[32]; sprintf(filename, "/image%d.jpg", imageCount); photo_save(filename); Serial.printf("Saved picture:%s\n", filename); Serial.println("Photos will begin in one minute, please be ready."); imageCount++; lastCaptureTime = now; } } } If you want you can change the time interval. Step 4: Upload and Test 🚀 Upload the Code: Connect your Xiao ESP32 S3 Sense to your computer, Select the correct COM port, and upload the code using the Arduino IDE. Test the Camera: Once the code is uploaded, the camera will start capturing images at regular intervals and saving them to the MicroSD card. You can open the serial terminal and look for the response. Step 5: Create the Timelapse Video 🎥 Retrieve Images: Remove the MicroSD card from the Xiao ESP32 S3 Sense and transfer the images to your computer. Compile the Timelapse Video: Use video editing software like Adobe Premiere Pro, Final Cut Pro, or free alternatives like OpenShot or Shotcut to compile the images into a timelapse video. Or you can simply use a python script to do that. Here is the Python code to convert jpeg to video: import cv2 import numpy as np import time import os nframes = 500 interval = 0.5 fps=100 print("XIAO ESP32 S3 Sense TimeLapser") # Define the path to the photos folder photos_path = "photos/" # Get the list of photo filenames photos = os.listdir(photos_path) # Sort the photos by name photos.sort() # Create a video writer object video = cv2.VideoWriter("video.avi", cv2.VideoWriter_fourcc(*"MJPG"), 100, (800, 600)) # Loop through the photos for photo in photos: # Read the photo as an image image = cv2.imread(photos_path + photo) # Resize the image to fit the video frame image = cv2.resize(image, (800, 600)) # Write the image to the video video.write(image) # Release the video writer object video.release() print("Video Build Completed") Final Output from Xiao ESP32 S3 Sense: Conclusion 🎉 Congratulations! You’ve successfully built a small timelapse camera using the Xiao ESP32 S3 Sense. This project can be expanded further by adding features like remote control, different capture intervals, or even uploading images to the cloud. Feel free to share your timelapse videos and any modifications you make to this project. Happy building! 🛠️
  9. In this project, we’ll integrate the M5Stack Barometric Pressure Unit (QMP6988) with the M5Stack Core2 using the UIFlow graphical programming language. This setup will allow us to measure atmospheric pressure and temperature, and display the data on the Core2’s screen. Let’s get started! 🚀 Materials Needed: M5Stack Core2 M5Stack Barometric Pressure Unit (QMP6988) Grove Cable USB-C Cable Computer with Internet access Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. Step 1: Setting Up Your Hardware Connect the Barometric Pressure Unit to the Core2: Use the Grove Cable to connect the Barometric Pressure Unit to one of the Grove ports on the M5Stack Core2. The Grove ports are located on the side of the Core2. Power Up the Core2: Connect the Core2 to your computer using the USB-C cable. Ensure the Core2 is powered on. Step 2: Setting Up UIFlow Burn UIFlow Firmware: Go to the M5Stack Official Website and download the M5Burner tool. Install M5Burner: Unzip the M5Burner archive and double-click the executable file to install it on your computer. Check the COM Port: Open the Device Manager (Windows) or System Information (macOS) to identify the COM port assigned to your Core2. Open M5Burner: Launch the M5Burner tool on your computer. Select the Firmware In M5Burner, select the latest version of the UIFlow firmware for M5Stack Core2. Configure the Settings: Select the correct COM port and set the baud rate. Burn the Firmware: Click the “Burn” button to start the firmware burning process. Wait for the process to complete. Restart the Core2: After burning the firmware, restart your M5Stack Core2 by pressing the red button. Connect to Wi-Fi: Follow the on-screen instructions to connect the Core2 to your Wi-Fi network. You may need to connect to the Core2’s hotspot and configure the Wi-Fi settings via a web browser. Obtain API Key: Once connected, the Core2 will display an API Key and a QR code. Note down the API Key for later use. Access UIFlow:. Open your web browser and navigate to UIFlow. Create an account or log in if you already have one. Select Your Device: In UIFlow, select the M5Stack Core2 as your device. Connect to Your Device: Click the settings button in the top right corner of the UIFlow page, enter the API Key obtained from your Core2, and click “OK” to save Step 3: Programming with UIFlow Initialize the Barometric Pressure Unit: In the UIFlow interface, go to the “Units” section and drag the “Barometer” block into the workspace. This block initializes the Barometric Pressure Unit. Read Pressure and Temperature: Drag the “Get Pressure” and “Get Temperature” blocks from the “Barometer” section into the workspace. These blocks will read the atmospheric pressure and temperature from the sensor. Display Data on the Screen: Go to the “Display” section and drag the “Label” block into the workspace. Use this block to create labels to display the pressure and temperature readings on the Core2 screen. Repeat the same step to add 3 more labels. UI Development: Now click on UI and here you can see all the label-related stuff. Just add these two cells and hit run. You will see this. Display sensor data: Now we can use the BPS unit options here. then hit run you will see this response in the M5Stack Core2. Create a Loop: To continuously update the readings, create a loop and place the “Get Pressure,” “Get Temperature,” and “Set Text” blocks inside this loop. add some time delay to avoid data transmission issues. Test the Setup:🌡️ Once the program is uploaded, the Core2 should start displaying its screen's atmospheric pressure and temperature readings. You can now monitor the weather conditions in real time! 🌡 Step 4: Enhancements and Customization Add More Sensors: You can enhance your weather station by adding more sensors, such as humidity or light sensors, to gather additional environmental data. Data Logging: Use the Core2’s storage capabilities to log the sensor data over time. This can help you analyze trends and patterns in the weather data. Cloud Integration: Integrate your weather station with cloud services to remotely monitor the data. UIFlow supports various cloud platforms for data storage and visualization. Conclusion: Congratulations! 🎉 You’ve successfully built a weather station using the M5Stack Core2 and the Barometric Pressure Unit. This project helps you understand the basics of atmospheric pressure and temperature measurement and introduces you to the powerful UIFlow graphical programming environment. Happy coding! 💻
  10. Let’s create an offline voice-controlled LED system using the DFRobot Beetle ESP32 C6 and the DFRobot Offline Voice Learning Sensor. This project combines hardware components and programming to create an interactive system that responds to voice commands. Here’s a detailed step-by-step guide: 1️⃣Project Overview We’ll build a voice-controlled LED system that turns on and off NeoPixel lights based on spoken commands. The DFRobot Gravity Offline Voice Recognition Sensor will listen for voice input, and the Beetle ESP32 C6 will process the commands and control the LED. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. 2️⃣Components Needed DFRobot Beetle ESP32 C6: This compact ESP32 board will serve as our microcontroller. DFRobot Gravity Offline Voice Recognition Sensor: An offline voice recognition module with built-in command words and self-learning capabilities. Breadboard and Jumper Wires: For connecting the components. 3️⃣Wiring Diagram Connect the DFRobot Gravity Sensor to the Beetle ESP32 C6 using jumper wires. 4️⃣ Install the Arduino IDE : If you haven’t already, download and install the Arduino IDE. 5️⃣Add the ESP32 Board to Arduino IDE: Follow these steps to add the ESP32 board to your Arduino IDE: Open the Arduino IDE. Go to File > Preferences. In the “Additional Boards Manager URLs” field, add the following URL: https://dl.espressif.com/dl/package_esp32_index.json Click OK. Go to Tools > Board > Boards Manager. Search for “esp32” and install the “esp32” package. Select the Beetle ESP32 C6 as your board under Tools > Board. 6️⃣Download the DFRobot Voice Recognition Library: Visit the DFRobot Voice Recognition Sensor tutorial for detailed steps. Download the DFRobot Voice Recognition Library from the DFRobot website. 7️⃣Write the Arduino Sketch: Create a new Arduino sketch (File > New). Copy and paste the following sample code into your sketch: #include "DFRobot_DF2301Q.h" DFRobot_DF2301Q_I2C DF2301Q; int led = 15; void setup() { Serial.begin(115200); pinMode(led, OUTPUT); while (!(DF2301Q.begin())) { Serial.println("Communication with device failed, please check connection"); delay(3000); } Serial.println("Begin ok!"); DF2301Q.setVolume(7); DF2301Q.setMuteMode(0); DF2301Q.setWakeTime(15); uint8_t wakeTime = 0; wakeTime = DF2301Q.getWakeTime(); Serial.print("wakeTime = "); Serial.println(wakeTime); DF2301Q.playByCMDID(23); // Common word ID } void loop() { uint8_t CMDID = 0; CMDID = DF2301Q.getCMDID(); Serial.print("CMDID = "); Serial.println(CMDID); if (CMDID == 5) { digitalWrite(led, HIGH); } if (CMDID == 6) { digitalWrite(led, LOW); } } 8️⃣Voice Commands: The DFRobot Gravity Sensor comes with 121 built-in fixed command words. You can also add 17 custom command words. For example: “Turn on the lights” “Change color to blue” “Dim the lights” 9️⃣Upload the Sketch: Connect your Beetle ESP32 C6 to your computer via USB. Select the Arduino IDE's appropriate COM port and board (ESP32 Dev Module). Click the Upload button to upload the sketch to your Beetle ESP32 C6. 🔟Test Your Voice-Controlled LED System: Power up your system. Speak the predefined voice commands to control the led ✅Conclusion With this setup, you’ll have an offline voice-controlled LED system that responds to your spoken commands. Feel free to expand the project by adding more custom commands or integrating other devices!
  11. The Raspberry Pi 5 is a powerful platform for various projects, including implementing large language models (LLMs) like OLLAMA. In this article, we’ll guide you through installing and using OLLAMA on your Raspberry Pi 5. What is OLLAMA?🤖 OLLAMA is not an LLM itself but a tool that facilitates the running of various open-source AI models on your device. It handles the downloading and operation of supported language models and provides an API for application interaction. Why Use OLLAMA on Raspberry Pi 5?🥷: Data Privacy: All data processing occurs locally, enhancing security. Offline Capabilities: Operates without an internet connection, ideal for remote areas. Real-time Processing: Local deployment can reduce latency compared to cloud-based services. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. Equipment Needed⚙️: Raspberry Pi 5 (8GB recommended) Micro SD Card with Raspberry Pi OS installed Stable internet connection for initial setup Basic familiarity with command-line operations 1️⃣ Updating Raspberry Pi OS: Update your Raspberry Pi’s OS to ensure all packages are current. sudo apt update sudo apt upgrade Verify that curl is installed: sudo apt install curl 2️⃣Run the OLLAMA Installer: Next, we need to download and install the Ollama on the Raspberry Pi. Navigate to the Ollama site and download the Linux version. Execute the following command in the terminal to install OLLAMA: curl -fsSL https://ollama.com/install.sh | sh 3️⃣Running OLLAMA: After installation, you can run OLLAMA using the command: ollama run phi --verbose Replace [model_name] with your chosen AI model. For instance, TinyLlama will be less resource-intensive than Llama3. Wait until the installation is done. Once the installation is done, now our LLM will wait for our questions. Just enter the questions and wait for the answer. 4️⃣Optimizing Performance: Memory Management: Run the Raspberry Pi in CLI mode without the desktop loaded to save resources. Performance Tuning: Adjust settings for better performance on limited hardware. Conclusion With OLLAMA, you can leverage the power of LLMs directly on your Raspberry Pi 5. Whether you’re a hobbyist or a developer, this setup allows you to maintain data privacy, work offline, and enjoy real-time processing. Follow the steps outlined above to get started with OLLAMA on your Raspberry Pi 5.
  12. As our population ages, ensuring the safety and well-being of seniors becomes increasingly important. A voice-controlled SOS system can provide peace of mind for both elders and their caregivers. In this project, we’ll create a personalized emergency response system that allows seniors to call for help using voice commands. Additionally, we’ll integrate Telegram alerts to notify caregivers or family members instantly. Project Components⚙️ Voice Recognition Module: We’ll use a voice recognition chip or module that responds to specific voice commands. When the user says a predefined phrase (e.g., “Help” or “Emergency”), the system will activate. Microcontroller (M5StickC): The brain of our system, responsible for processing voice commands and triggering alerts. Telegram Bot: We’ll set up a Telegram bot to send alerts to designated contacts. Telegram provides a secure and reliable platform for notifications. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. Step 1️⃣:Voice Recognition Module Setup🔊: Connect the voice recognition module to the M5StickC via the Grove interface. The Grove interface consists of a standardized 4-pin connector (GND, VCC, SDA, SCL). Connect the voice recognition module’s pins (VCC, GND, SDA, SCL) to the corresponding Grove pins on the M5StickC. Train the module with the chosen SOS phrases. In my case, I'm going to use the default wake word as a SOS command. Step 2️⃣:Microcontroller Configuration⌨️: First, we need to install the Voice Learning sensor's library to the Arduino IDE. Here is the simple Arduino sketch that can read the voice learning sensor's command and print the command ID. #include "DFRobot_DF2301Q.h" DFRobot_DF2301Q_I2C DF2301Q; void setup() { Serial.begin(115200); while( !( DF2301Q.begin() ) ) { Serial.println("Communication with device failed, please check connection"); delay(3000); } Serial.println("Begin ok!"); DF2301Q.setVolume(7); DF2301Q.setMuteMode(0); DF2301Q.setWakeTime(15); uint8_t wakeTime = 0; wakeTime = DF2301Q.getWakeTime(); Serial.print("wakeTime = "); Serial.println(wakeTime); DF2301Q.playByCMDID(23); // Common word ID } void loop() { uint8_t CMDID = 0; CMDID = DF2301Q.getCMDID(); if(0 != CMDID) { Serial.print("CMDID = "); Serial.println(CMDID); } delay(3000); } Here is the serial terminal response. Step 3️⃣:Setting up the Telegram Bot 🤖: Go to Google Play or App Store, download, and install Telegram. In my case, I'm using telegram web. First, search for “botfather” and click the BotFather as shown below. Next, start the BotFather, and use /newbot to create a new bot. Next, name your bot. Then, mention the username. Finally, it will show you the API key. Step 4️⃣: Creating a user for Telegram Bot 👤: Anyone that knows your bot username can interact with it. To make sure that we ignore messages that are not from our Telegram account (or any authorized users), you can get your Telegram User ID. In your Telegram account, search for “IDBot” Start a conversation with that bot and type /getid. You will get a reply with your user ID. Save that user ID, because you’ll need it later in this tutorial. Step 5️⃣:System Deployment🛜: Finally, upload the following sketch to the M5StickC and change the credentials as per your Bot setup. #include <WiFi.h> #include <WiFiClientSecure.h> #include <UniversalTelegramBot.h> #include <ArduinoJson.h> #include "DFRobot_DF2301Q.h" #include <M5StickC.h> DFRobot_DF2301Q_I2C DF2301Q; // Replace with your network credentials const char* ssid = "ELDRADO"; const char* password = "amazon123"; // Initialize Telegram BOT #define BOTtoken "6897873881" // your Bot Token (Get from Botfather) #define CHAT_ID "" WiFiClientSecure client; UniversalTelegramBot bot(BOTtoken, client); void setup() { Serial.begin(115200); M5.begin(); M5.Lcd.setRotation(3); M5.Lcd.fillScreen(BLACK); M5.Lcd.setSwapBytes(true); M5.Lcd.setTextSize(1); M5.Lcd.setCursor(7, 20, 2); M5.Lcd.setTextColor(TFT_GREEN, TFT_BLACK); // Attempt to connect to Wifi network: Serial.print("Connecting Wifi: "); Serial.println(ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); bot.sendMessage(CHAT_ID, "Bot started up", ""); while (!(DF2301Q.begin())) { Serial.println("Communication with device failed, please check connection"); delay(3000); } Serial.println("Begin ok!"); DF2301Q.setVolume(7); DF2301Q.setMuteMode(0); DF2301Q.setWakeTime(15); uint8_t wakeTime = 0; wakeTime = DF2301Q.getWakeTime(); Serial.print("wakeTime = "); Serial.println(wakeTime); DF2301Q.playByCMDID(23); // Common word ID } void loop() { uint8_t CMDID = 0; CMDID = DF2301Q.getCMDID(); if (0 != CMDID) { Serial.print("CMDID = "); Serial.println(CMDID); bot.sendMessage(CHAT_ID, "Alarm Triggered !!", ""); M5.Lcd.fillScreen(BLACK); M5.Lcd.setCursor(3, 2); M5.Lcd.print("Alarm Triggered !!"); } delay(5000); M5.Lcd.fillScreen(BLACK); M5.Lcd.setCursor(1, 3); M5.Lcd.print("System Online"); } Once you have uploaded the sketch look for the serial terminal response. Now let's test the system, just say the command word and look for the response. Here is the Telegram response. Conclusion✅ By combining voice control, Telegram alerts, and a user-friendly interface, our Voice-Controlled SOS System provides a simple yet effective solution for seniors. Whether they’re at home or outdoors, they can call for help with ease. Caregivers and family members can rest assured knowing that they’ll receive immediate notifications in case of an emergency. Let’s build a safer and more connected environment for our elders! 🗣️🆘📲
  13. In this tutorial, I will guide you on how to create a temperature and humidity monitoring system that can be controlled by voice using a FireBeetle and a DHT11 sensor. Imagine being able to ask your FireBeetle about the current temperature and getting a visual response! Let's dive into the details. 💡 Components Required: DFRobot FireBeetle 2 ES32 S3 DHT11 Temperature and Humidity Sensor DFRobot Gravity Offline Voice Recognition sensor Jumper Cables 🔌 Wiring Diagram: Connect the DHT11 sensor to the FireBeetle as follows: GND pin: Connect to GND (0V). VCC pin: Connect to VCC (5V or 3.3V). DATA pin: D5 If you’re using a DHT11 module, it may have a built-in resistor, eliminating the need for an external one. Connect the Offline Voice Recognition sensor to the FireBeetle as follows: GND pin: Connect to GND (0V). VCC pin: Connect to VCC (5V or 3.3V). DATA pin: SDA CLOCK pin:SCL Finally, connect the TFT screen to the FireBeetle directly via the connector interface. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. 1️⃣ Train the custom voice commands: This DFRobot Gravity Offline Voice Recognition Sensor sensor is designed for Arduino, Raspberry Pi, Python, and ESP32 platforms. It allows you to recognize voice commands without an internet connection and comes with built-in fixed command words as well as the ability to add custom commands. Here are the steps to train custom voice commands: First, connect the Voice Recognition sensor's VCC pin to 5V and GND to GND. Then wake up the sensor by saying "Hello Robot" Next, say "Learning command word", this will help us to add our own command words. Once the system ready, train with your custom commands. Here I have created two commands, one is what is the temperature? and the next one is what is the humidity? These commands have some specific ID. Normally the first command id is 5 then the following will be 6,7 and so on. In my case what is the temperature? is command is 5 and what is the humidity? is command is 6. 2️⃣ Install Required Libraries: In your Arduino IDE or other development environment, install the necessary libraries for the Gravity Voice Recognition Sensor. You can find the library on the DFRobot GitHub repository. As well as the DHT11 sensor. 3️⃣ Programming the FireBeetle: Write a program to interface with the sensor. You can use the provided example code or create your own. This code will get the DHT11 temp and humidity value. #include <dht11.h> dht11 DHT; #define DHT11_PIN 4 void setup(){ Serial.begin(9600); Serial.println("DHT TEST PROGRAM "); Serial.print("LIBRARY VERSION: "); Serial.println(DHT11LIB_VERSION); Serial.println(); Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)"); } void loop(){ int chk; Serial.print("DHT11, \t"); chk = DHT.read(DHT11_PIN); // READ DATA switch (chk){ case DHTLIB_OK: Serial.print("OK,\t"); break; case DHTLIB_ERROR_CHECKSUM: Serial.print("Checksum error,\t"); break; case DHTLIB_ERROR_TIMEOUT: Serial.print("Time out error,\t"); break; default: Serial.print("Unknown error,\t"); break; } // DISPLAT DATA Serial.print(DHT.humidity,1); Serial.print(",\t"); Serial.println(DHT.temperature,1); delay(2000); } Here is the complete sketch to configure DHT11 for voice recognition. #include <Wire.h> #include "DFRobot_GDL.h" #define TFT_DC D2 #define TFT_CS D6 #define TFT_RST D3 #include <DFRobot_DHT11.h> DFRobot_DHT11 DHT; #define DHT11_PIN D5 DFRobot_ST7789_240x320_HW_SPI screen(/dc=/TFT_DC,/cs=/TFT_CS,/rst=/TFT_RST); #include "DFRobot_DF2301Q.h" //I2C communication DFRobot_DF2301Q_I2C DF2301Q; void setup() { Serial.begin(115200); screen.begin(); Wire.begin(); // Init the sensor while ( !( DF2301Q.begin() ) ) { Serial.println("Communication with device failed, please check connection"); delay(3000); } Serial.println("Begin ok!"); DF2301Q.setVolume(7); DF2301Q.setMuteMode(0); DF2301Q.setWakeTime(15); uint8_t wakeTime = 0; wakeTime = DF2301Q.getWakeTime(); Serial.print("wakeTime = "); Serial.println(wakeTime); DF2301Q.playByCMDID(23); // Common word ID } void loop() { uint8_t CMDID = 0; CMDID = DF2301Q.getCMDID(); c if (0 != CMDID) { Serial.print("CMDID = "); Serial.println(CMDID); int16_t color = 0x00FF; screen.setTextWrap(false); screen.setRotation(1); screen.fillScreen(COLOR_RGB565_BLACK); screen.setTextColor(COLOR_RGB565_GREEN); screen.setFont(&FreeMono9pt7b); screen.setTextSize(1.5); screen.setCursor(0, 30); screen.println("CNID: "); screen.setCursor(130, 30); screen.setTextColor(COLOR_RGB565_RED); screen.println(CMDID); if (CMDID == 5) { Serial.print("CMDID = "); Serial.println(CMDID); DHT.read(DHT11_PIN); Serial.print("temp:"); Serial.print(DHT.temperature); Serial.print(" humi:"); Serial.println(DHT.humidity); int16_t color = 0x00FF; screen.setTextWrap(false); screen.setRotation(1); screen.fillScreen(COLOR_RGB565_BLACK); screen.setTextColor(COLOR_RGB565_GREEN); screen.setFont(&FreeMono9pt7b); screen.setTextSize(1.8); screen.setCursor(20, 50); screen.println("Tempearature: "); screen.setTextColor(COLOR_RGB565_RED); screen.setCursor(160, 50); screen.println(DHT.temperature); screen.setCursor(190, 50); screen.println(" C"); } if (CMDID == 6) { Serial.print("CMDID = "); Serial.println(CMDID); DHT.read(DHT11_PIN); Serial.print("temp:"); Serial.print(DHT.temperature); Serial.print(" humi:"); Serial.println(DHT.humidity); int16_t color = 0x00FF; screen.setTextWrap(false); screen.setRotation(1); screen.fillScreen(COLOR_RGB565_BLACK); screen.setTextColor(COLOR_RGB565_GREEN); screen.setFont(&FreeMono9pt7b); screen.setTextSize(1.8); screen.setCursor(20, 50); screen.println("Humidity: "); screen.setTextColor(COLOR_RGB565_RED); screen.setCursor(160, 50); screen.println(DHT.humidity); screen.setCursor(190, 50); screen.println(" %"); } } delay(1000); } 4️⃣ Testing and Refinement: Upload your program to the FireBeetle, select the correct COM port, and wait until it finishes the upload. Test the sensor by speaking the fixed command words and your custom commands. And look at the serial terminal for the response. Finally, you can see the DHT11 data on the TFT screen. 5️⃣ Use in Your Project: Now that your sensor recognizes custom voice commands, integrate it into your project. For instance, control home automation devices, trigger specific actions, or create interactive audio experiences. Remember that the sensor’s self-learning function allows you to train it with various sounds, not just voice. So, get creative! You can use whistles, snaps, or even cat meows as custom commands. 🎙️🔊 For more detailed information, refer to the DFRobot Wiki and explore the Hackster project. Happy hacking! 🚀
  14. In the world of embedded systems and IoT devices, power consumption is a critical factor that can make or break the success of a product. The Nordic Power Profiler Kit II (PPK 2) is an indispensable tool for developers looking to optimize the power usage of their devices. While the official nRF Connect Power Profiler provides a user-friendly GUI, there’s a growing need for automation in power monitoring. This is where Python comes into play, offering a way to control PPK 2 programmatically. Unofficial Python API for PPK 2 An unofficial Python API for PPK 2 has been developed to fill the gap left by the official tool. This API allows for automated power monitoring and data logging within Python applications, making it possible to integrate power profiling into automated test environments. Key Features Real-time power measurement: The API enables real-time measurement of device power consumption, which is crucial for identifying power spikes and optimizing energy usage. Data logging: It supports data logging in user-selectable formats, allowing for long-term power consumption analysis. Cross-platform support: The API is designed to work across different platforms, ensuring that developers can use it regardless of their operating system. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. Let's start with UNIHIKER: The UNIHIKER is a single-board computer that boasts a 2.8-inch touchscreen, providing a tactile and visual interface for your applications. It’s powered by a Quad-Core ARM Cortex-A35 CPU and comes with 512MB RAM and 16GB Flash storage. The board runs on Debian OS, ensuring a familiar and versatile environment for Linux enthusiasts In this tutorial, we are going to automate the power profiling with the UNIHIKER Single Board Computer. Install Python API in UNIHIKER: Connect UNIHER to the PC and open the Mind+ IDE. Next, connect the UNIHIKER to Mind+ via serial port. Next, run the following command in the terminal and install the ppk2 library. pip install ppk2-api Now you can see the zip file in the UNIHIKER file storage. Once installed, you can start by importing the necessary classes and initializing the PPK2_API object with the appropriate serial port. Here’s a basic example to get you started: import time from ppk2_api.ppk2_api import PPK2_API # Initialize the PPK2_API object with the correct serial port ppk2_test = PPK2_API("/dev/ttyACM3") # Replace with your serial port # Set up the power profiler ppk2_test.get_modifiers() ppk2_test.use_source_meter() # Set source meter mode ppk2_test.set_source_voltage(3300) # Set source voltage in mV # Start measuring ppk2_test.start_measuring() # Read measured values in a loop for i in range(0, 1000): read_data = ppk2_test.get_data() if read_data != b'': samples = ppk2_test.get_samples(read_data) print(f"Average of {len(samples)} samples is: {sum(samples)/len(samples)}uA") time.sleep(0.001) # Adjust time between sampling as needed # Stop measuring ppk2_test.stop_measuring() This script sets the PPK 2 to source meter mode, starts measuring, and prints out the average current consumption over several samples. It’s a simple yet powerful way to begin automating power profiling for your projects. Demo Let's unzip the zip file and open the folder so that you can see the example sketches. here is the example script. In this sketch, it will automatically detect the connected PPK2 devices and it will power up the DUT as well as measure the 100 samples. import time from ppk2_api.ppk2_api import PPK2_API from unihiker import GUI # Import the unihiker library import time # Import the time library from pinpong.board import Board # Import the Board module from the pinpong.board package from pinpong.extension.unihiker import * # Import all modules from the pinpong.extension.unihiker package ppk2s_connected = PPK2_API.list_devices() if(len(ppk2s_connected) == 1): ppk2_port = ppk2s_connected[0] print(f'Found PPK2 at {ppk2_port}') else: print(f'Too many connected PPK2\'s: {ppk2s_connected}') exit() ppk2_test = PPK2_API(ppk2_port, timeout=1, write_timeout=1, exclusive=True) ppk2_test.get_modifiers() ppk2_test.set_source_voltage(3300) ppk2_test.use_source_meter() # set source meter mode ppk2_test.toggle_DUT_power("ON") # enable DUT power ppk2_test.start_measuring() # start measuring for i in range(0, 100): read_data = ppk2_test.get_data() if read_data != b'': samples, raw_digital = ppk2_test.get_samples(read_data) print(f"Average is:{sum(samples)/len(samples)}uA") final=sum(samples)/len(samples) time.sleep(0.01) ppk2_test.toggle_DUT_power("OFF") # disable DUT power ppk2_test.stop_measuring() Conclusion The Nordic PPK 2, combined with the power of Python and UNIHIKER, opens up new possibilities for automated power profiling. Whether you’re looking to integrate power profiling into your CI/CD pipeline or simply want to streamline your testing process, the unofficial Python API for PPK 2 is a valuable addition to your toolkit. I hope this blog post provides a clear overview of how to control the Nordic Power Profiler Kit II with Python and UNIHIKER. If you have any questions or need further assistance, feel free to ask!
  15. Creating a voice-controlled lighting system can add a touch of magic to any environment. In this blog, we’ll explore how to integrate the DFRobot Gravity: Offline Language Learning Voice Recognition Sensor with a Neo Pixel light strip, all controlled by a Beetle ESP32 C3 microcontroller. Introduction to DFRobot Gravity Voice Recognition Sensor The DFRobot Gravity: Offline Voice Recognition Sensor is a powerful module designed for voice command projects. Here are its key features: Offline Operation: Unlike cloud-based solutions, this sensor works without an internet connection. It’s built around an offline voice recognition chip, making it ideal for applications where internet connectivity is not available or desired. Built-in Command Words: The sensor comes with 121 fixed command words preloaded. These cover a wide range of common instructions, eliminating the need for users to record their voices. Custom Commands: Additionally, the sensor supports the addition of 17 custom command words. This flexibility allows you to train it to recognize specific sounds or phrases, such as whistling, snapping, or even cat meows. Self-Learning Function: The self-learning feature enables you to teach the sensor new commands. For example, you could use it in an automatic pet feeder. When your cat emits a meow, the sensor recognizes it and triggers the feeder to provide food promptly. User-Friendly Design: With its straightforward interface, the sensor simplifies voice interaction projects. Whether you’re building smart home appliances, toys, lighting fixtures, or robotics, this sensor provides a flexible solution. Key Features: Offline Operation: Works without the need for an internet connection. Custom Commands: Supports adding custom voice commands. Compatibility: Can be used with Arduino, Raspberry Pi, Python, and Beetle ESP32 C3. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Also, check out this useful blog on PCBWay Plugin for KiCad from here. Using this plugin, you can directly order PCBs in just one click after completing your design in KiCad. Neo Pixel: A Symphony of Lights Neo Pixel LEDs are individually addressable RGB LEDs, which means each LED’s color and brightness can be controlled independently. This makes them ideal for creating dynamic and colorful lighting effects. Why Choose Neo Pixel? Individual Addressability: Control each LED separately. Vibrant Colors: Create a spectrum of colors with RGB LEDs. Energy Efficient: Low power consumption with bright output. The Beetle ESP32 C3 Controller: The Brain Behind the Operation The Beetle ESP32 C3 is a small, powerful development board ideal for IoT projects. It features: A RISC-V 32-bit single-core processor for efficient performance. A coin-sized design, making it highly portable. Up to 13 digital I/O ports for various connections. Onboard battery management for direct li-ion battery connection. Wi-Fi and Bluetooth 5 (LE) support for versatile networking. Compatibility with Arduino IDE, ESP-IDF, and MicroPython, and supports C and Python programming. An expansion board for additional power sources and a GDI for screens. Operates at 3.3V with a Type-C input of 5V DC and a charging current of 400mA. Suitable for a wide range of temperatures, from -40 to 105°C. It’s a compact yet feature-rich board that’s adaptable for a variety of applications. Advantages of Beetle ESP32 C3: Connectivity: Wi-Fi and Bluetooth ready. Powerful: Enough processing power to handle complex tasks. Versatile: Compatible with various programming environments. Bringing It All Together To create a voice-controlled Neo Pixel light system, we’ll need to connect the DFRobot Gravity sensor to the Beetle ESP32 C3 and then to the Neo Pixel strip. The Beetle ESP32 C3 will listen to voice commands through the sensor and control the Neo Pixel lights accordingly. Adding Custom Commands in DFRobot Gravity Voice Recognition Sensor Let’s dive into the process of adding custom command words: First, let's upload the following sketch to the Beetle board, this sketch will show you the exact command ID which is related to the custom voice instructions. /*! * @file i2c.ino * @brief Control the voice recognition module via I2C * @n Get the recognized command ID and play the corresponding reply audio according to the ID; * @n Get and set the wake-up state duration, set mute mode, set volume, and enter the wake-up state * @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) * @licence The MIT License (MIT) * @author [qsjhyy]([email protected]) * @version V1.0 * @date 2022-12-30 * @url https://github.com/DFRobot/DFRobot_DF2301Q */ #include "DFRobot_DF2301Q.h" //I2C communication DFRobot_DF2301Q_I2C DF2301Q; void setup() { Serial.begin(115200); // Init the sensor while( !( DF2301Q.begin() ) ) { Serial.println("Communication with device failed, please check connection"); delay(3000); } Serial.println("Begin ok!"); /** * @brief Set voice volume * @param voc - Volume value(1~7) */ DF2301Q.setVolume(4); /** * @brief Set mute mode * @param mode - Mute mode; set value 1: mute, 0: unmute */ DF2301Q.setMuteMode(0); /** * @brief Set wake-up duration * @param wakeTime - Wake-up duration (0-255) */ DF2301Q.setWakeTime(15); /** * @brief Get wake-up duration * @return The currently-set wake-up period */ uint8_t wakeTime = 0; wakeTime = DF2301Q.getWakeTime(); Serial.print("wakeTime = "); Serial.println(wakeTime); /** * @brief Play the corresponding reply audio according to the command word ID * @param CMDID - Command word ID * @note Can enter wake-up state through ID-1 in I2C mode */ // DF2301Q.playByCMDID(1); // Wake-up command DF2301Q.playByCMDID(23); // Common word ID } void loop() { /** * @brief Get the ID corresponding to the command word * @return Return the obtained command word ID, returning 0 means no valid ID is obtained */ uint8_t CMDID = 0; CMDID = DF2301Q.getCMDID(); if(0 != CMDID) { Serial.print("CMDID = "); Serial.println(CMDID); } delay(3000); } Now let's talk to our sensor and add custom voice commands. First, we need to use this "Learning command word" command to add a new command. Here I have added 4 different commands. These are the commands and their related command IDs. Lights on = 5 Lights off = 6 Lights to red = 8 Lights to green = 7 Integrate Neo Pixels with Voice Sensor Here’s a simple example that tests our neo pixel led: // NeoPixel Ring simple sketch (c) 2013 Shae Erisson // Released under the GPLv3 license to match the rest of the // Adafruit NeoPixel library #include <Adafruit_NeoPixel.h> #ifdef __AVR__ #include <avr/power.h> // Required for 16 MHz Adafruit Trinket #endif // Which pin on the Arduino is connected to the NeoPixels? #define PIN 0 // On Trinket or Gemma, suggest changing this to 1 // How many NeoPixels are attached to the Arduino? #define NUMPIXELS 8 // Popular NeoPixel ring size // When setting up the NeoPixel library, we tell it how many pixels, // and which pin to use to send signals. Note that for older NeoPixel // strips you might need to change the third parameter -- see the // strandtest example for more information on possible values. Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); #define DELAYVAL 500 // Time (in milliseconds) to pause between pixels void setup() { // These lines are specifically to support the Adafruit Trinket 5V 16 MHz. // Any other board, you can remove this part (but no harm leaving it): #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000) clock_prescale_set(clock_div_1); #endif // END of Trinket-specific code. pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) } void loop() { pixels.clear(); // Set all pixel colors to 'off' // The first NeoPixel in a strand is #0, second is 1, all the way up // to the count of pixels minus one. for(int i=0; i<NUMPIXELS; i++) { // For each pixel... // pixels.Color() takes RGB values, from 0,0,0 up to 255,255,255 // Here we're using a moderately bright green color: pixels.setPixelColor(i, pixels.Color(0, 150, 0)); pixels.show(); // Send the updated pixel colors to the hardware. delay(DELAYVAL); // Pause before next pass through loop } } Here is the neo-pixel response. Finally, let's integrate the voice sensor with our neo-pixel. #include "DFRobot_DF2301Q.h" #include <Adafruit_NeoPixel.h> #define PIN 0 // Neo Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, PIN, NEO_GRB + NEO_KHZ800); //I2C communication DFRobot_DF2301Q_I2C DF2301Q; void setup() { Serial.begin(115200); strip.begin(); strip.setBrightness(100); strip.show(); while ( !( DF2301Q.begin() ) ) { Serial.println("Communication with device failed, please check connection"); delay(3000); } Serial.println("Begin ok!"); DF2301Q.setVolume(7); DF2301Q.setMuteMode(0); DF2301Q.setWakeTime(15); uint8_t wakeTime = 0; wakeTime = DF2301Q.getWakeTime(); Serial.print("wakeTime = "); Serial.println(wakeTime); DF2301Q.playByCMDID(23); // Common word ID } void loop() { uint8_t CMDID = 0; CMDID = DF2301Q.getCMDID(); if (0 != CMDID) { Serial.print("CMDID = "); Serial.println(CMDID); } if (CMDID == 5) { strip.clear(); // Set all pixel colors to 'off' for (int i = 0; i < 12; i++) { // For each pixel... strip.setPixelColor(i, strip.Color(255, 255, 255)); strip.show(); } } else if (CMDID == 6) { strip.clear(); for (int i = 0; i < 12; i++) { // For each pixel... strip.setPixelColor(i, strip.Color(0, 0, 0)); strip.show(); } } else if (CMDID == 7) { strip.clear(); for (int i = 0; i < 12; i++) { // For each pixel... strip.setPixelColor(i, strip.Color(255, 0, 0)); strip.show(); } } else if (CMDID == 8) { strip.clear(); for (int i = 0; i < 12; i++) { // For each pixel... strip.setPixelColor(i, strip.Color(0, 255, 0)); strip.show(); } } } This script sets up the Beetle ESP32 C3 to control a Neo Pixel strip and changes the color based on voice commands received from the DFRobot Gravity sensor. Conclusion Integrating the DFRobot Gravity Voice Recognition Sensor with Neo Pixel lights controlled by a Beetle ESP32 C3 offers endless possibilities for creating interactive and responsive environments. Whether it’s for home automation, art installations, or educational purposes, this combination of technology brings both functionality and creativity to your projects. I hope this blog post inspires you to create your voice-controlled lighting system. If you have any questions or need further guidance, feel free to reach out!
×
  • Create New...