Friday, December 27, 2024

Building a 4x4x4 LED Cube Controlled with STM32F401

LED cubes are an excellent way to learn about electronics, microcontroller programming, and creative visual effects. This project involves building a 4x4x4 LED matrix and controlling it with an STM32F401 microcontroller. The 4x4x4 LED cube consists of 64 LEDs arranged in 4 layers, with each layer containing 16 LEDs. Using multiplexing, we light up individual LEDs or create dynamic patterns without requiring 64 GPIO pins.


How the 4x4x4 LED Cube Works

  1. Hardware Layout:

    • The cube is structured in a grid where each LED is connected to a row and column.
    • Each layer has a common cathode, and the columns connect the anodes.
  2. Multiplexing Control:

    • Only one layer is powered at a time, and the LEDs within that layer are controlled using the column connections.
    • By rapidly switching between layers (persistence of vision), we create the illusion that all LEDs are on simultaneously.
  3. STM32 Control:

    • GPIO pins control the rows and columns, while timer interrupts or DMA handle multiplexing efficiently.

Components Required

  1. STM32F401 Development Board (e.g., Nucleo F401RE)
  2. 64 LEDs
  3. 16 Resistors (for current limiting)
  4. 4 NPN transistors (for layer switching)
  5. 4x4x4 LED matrix structure
  6. Breadboard and wires

Circuit Design

LED Cube Connections

  • Anodes (Columns):
    Each column is connected to a GPIO pin through a current-limiting resistor.
  • Cathodes (Layers):
    Each layer is connected to the collector of an NPN transistor. The transistor base is controlled by a GPIO pin through a resistor.

STM32 Connections

  • Use 16 GPIO pins for columns.
  • Use 4 GPIO pins for layers via transistors.
  • Configure additional pins for debugging or input (optional).

Code Implementation

STM32CubeIDE Setup

  1. GPIO Configuration:

    • Set 16 pins as outputs for controlling columns.
    • Set 4 pins as outputs for layer selection (with transistors).
  2. Timers:

    • Use a timer to manage layer switching (e.g., every 2 ms).
  3. Interrupts or DMA:

    • For efficient LED control, use interrupts or DMA to update the column data.

Example Code

#include "stm32f4xx_hal.h"

#define NUM_LAYERS 4
#define NUM_COLUMNS 16

uint16_t column_data[NUM_LAYERS][NUM_COLUMNS] = {
    {0x1, 0x2, 0x4, 0x8, ...}, // Pattern for Layer 0
    {0x10, 0x20, 0x40, 0x80, ...}, // Pattern for Layer 1
    ...
};

volatile uint8_t current_layer = 0;

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
    if (htim->Instance == TIM3) { // Timer 3 handles multiplexing
        // Turn off all layers
        HAL_GPIO_WritePin(GPIOx, LAYER_PINS, GPIO_PIN_RESET);
        
        // Set column data for the current layer
      for (int col = 0; col < NUM_COLUMNS; col++) {
        HAL_GPIO_WritePin(GPIOx, COLUMN_PINS[col], 
        (column_data[current_layer][col]) ? GPIO_PIN_SET : GPIO_PIN_RESET);
        }
        
        // Turn on the current layer
        HAL_GPIO_WritePin(GPIOx, LAYER_PINS[current_layer], GPIO_PIN_SET);
        
        // Move to the next layer
        current_layer = (current_layer + 1) % NUM_LAYERS;
    }
}

int main(void) {
    HAL_Init();
    SystemClock_Config();
    
    // Initialize GPIO and Timer
    MX_GPIO_Init();
    MX_TIM3_Init();
    
    HAL_TIM_Base_Start_IT(&htim3); // Start timer with interrupt
    
    while (1) {
        // Main loop can be used for updating patterns or other logic
    }
}

Pattern Generation

Patterns are defined by updating the column_data array. Examples include:

  1. Static Patterns: Light up specific LEDs.
  2. Dynamic Patterns: Rotate LEDs in a wave, spiral, or bounce effect.
  3. 3D Animations: Create flowing shapes, letters, or symbols.

Tools and Techniques

  1. STM32CubeMX: Configure GPIO pins and timers easily.
  2. HAL Library: Simplifies hardware interaction.
  3. Debugging: Use a serial interface or LEDs to debug patterns.

Videos

1. Prototype Testing Video




Conclusion

Building a 4x4x4 LED cube using STM32F401 is a rewarding project that combines hardware design, microcontroller programming, and creative coding. With multiplexing, we efficiently control all LEDs with minimal GPIO usage, creating mesmerizing visual effects. This project is a stepping stone to creating larger LED cubes or integrating more advanced features like Bluetooth control or music synchronization.

Take the first step, and let your imagination light up!

DPOAE-Based Ear Testing Using MATLAB and Amplifier

Distortion Product Otoacoustic Emissions (DPOAE) testing is a non-invasive way to assess cochlear health. This technique uses sound frequencies to stimulate the inner ear and measures the resulting otoacoustic emissions, which indicate whether the cochlea is functioning properly. In this project, I developed a custom DPOAE testing device using an amplifier for sound generation and a MATLAB app for signal processing.


Understanding DPOAE Testing

DPOAEs occur when two pure tones (frequencies f1f_1 and f2f_2) are presented to the ear. These tones interact in the cochlea, producing distortion products—new frequencies that are not part of the original tones. The most prominent distortion product is 2f1f22f_1 - f_2, which is generated by the cochlear nonlinearities. Detecting these emissions helps evaluate the integrity of outer hair cells in the cochlea.


Why Two Frequencies?

The cochlea responds differently to various frequencies due to its tonotopic organization, where specific regions resonate at specific frequencies:

  1. Primary Tones:

    • f1f_1 and f2f_2 are two closely spaced frequencies where f1f_1 (lower frequency) is slightly less than f2f_2.
    • These tones stimulate overlapping regions of the cochlea.
  2. Interaction Zone:

    • When the two frequencies are played simultaneously, they interact nonlinearly in the cochlea, creating distortion products.
    • The distortion product 2f1f22f_1 - f_2 is used because it is robust and easily measurable in healthy ears.

System Design

Hardware Components

  1. Amplifier:

    • Amplifies the generated audio signals to ensure the tones are strong enough to stimulate the cochlea.
    • Ensures minimal distortion in the generated signals.
  2. Ear Probe:

    • Plays the tones into the ear canal and captures the emitted DPOAE signals using a sensitive microphone.

MATLAB App

The MATLAB app handles the generation, playback, and analysis of the DPOAE signals.

  1. Tone Generation:

    • Generates two pure tones f1f_1 and f2f_2 with precise frequency and intensity.
  2. Signal Analysis:

    • Records the sound from the ear canal.
    • Performs FFT (Fast Fourier Transform) to analyze the frequency spectrum and detect the presence of 2f1f22f_1 - f_2.

MATLAB Implementation

Tone Generation and Playback

fs = 44100; % Sampling frequency
t = 0:1/fs:1; % Time vector

f1 = 1000; % First tone frequency in Hz
f2 = 1200; % Second tone frequency in Hz

% Generate tones
tone1 = 0.5 * sin(2 * pi * f1 * t);
tone2 = 0.5 * sin(2 * pi * f2 * t);

% Play tones simultaneously
sound(tone1 + tone2, fs);

Recording and FFT Analysis

% Record the signal from the microphone
recObj = audiorecorder(fs, 16, 1);
disp('Recording... Speak into the microphone.');
recordblocking(recObj, 2); % Record for 2 seconds
disp('Recording complete.');

% Get recorded data
recordedSignal = getaudiodata(recObj);

% Perform FFT
N = length(recordedSignal);
f = (0:N-1)*(fs/N); % Frequency vector
fftSignal = abs(fft(recordedSignal));

% Plot frequency spectrum
plot(f, fftSignal);
xlabel('Frequency (Hz)');
ylabel('Amplitude');
title('Frequency Spectrum');

% Highlight DPOAE at 2f1-f2
dpoae_freq = 2*f1 - f2;
disp(['Expected DPOAE Frequency: ', num2str(dpoae_freq), ' Hz']);

How It Works

  1. Tone Playback:
    The MATLAB app generates and plays two tones, f1f_1 and f2f_2, through an amplifier and into the ear canal.

  2. Cochlear Response:
    The cochlea vibrates in response to these tones, producing the distortion product 2f1f22f_1 - f_2.

  3. Signal Capture:
    The emitted DPOAE signal is captured by the ear probe and fed back into the MATLAB app for analysis.

  4. FFT Analysis:
    The app performs FFT on the recorded signal to analyze its frequency spectrum and detect the presence of the DPOAE at 2f1f22f_1 - f_2.


Applications

  • Hearing Screening: Identify cochlear health in newborns and individuals exposed to loud environments.
  • Clinical Diagnostics: Diagnose hearing loss caused by outer hair cell dysfunction.
  • Research: Study the mechanics of the cochlea and auditory system.

Videos

1. Working Video

DPOAE PASS (IN THIS VIDEO AM SHOWING IF I BLOCK THE MICRIOHONE SPEAKERS WILL PLAY THE SOUND AND FULL REFLECTION WILL BE THERE SO WE WILL GET THE ALL GREEN WHICH MEANS EARS  HAVE NO ISSUE ):






DPOAE REFER 
(IN THIS VIDEO AM SHOWING AM NOT  BLOCK THE MICRIOHONE SPEAKERS WILL PLAY THE SOUND AND BECAUSE OF ZERO REFLECTION WE WILL GET THE ALL RED WHICH MEANS EARS  HAVE ISSUE ):
:





2. 3D CIRCUIT DESIGN 



Conclusion

This DPOAE testing system combines MATLAB's powerful signal processing capabilities with a custom-built amplifier and ear probe to assess cochlear health effectively. By detecting 2f1f22f_1 - f_2 distortion products, we gain valuable insights into the auditory system's functionality, paving the way for advancements in hearing diagnostics and research.

Motion Detection Using RF Transmitter and Receiver with Arduino and Python

 


In the world of IoT and automation, motion detection is a fundamental concept used in security systems, smart homes, and more. In this project, we create a motion detection system using an RF transmitter and receiver. The transmitter detects motion using an IR sensor and sends the data wirelessly to the receiver. An Arduino connected to the receiver processes this data and communicates with a Python script via PySerial to control a computer screen or change tabs dynamically.


Project Overview

This system detects motion and triggers an action on a connected computer. The components work together as follows:

  1. Transmitter Side:

    • An IR sensor detects if someone crosses its path.
    • The RF transmitter sends a signal (1 or 0) to the receiver.
  2. Receiver Side:

    • An RF receiver captures the signal and sends it to an Arduino.
    • The Arduino communicates with a Python script via PySerial.
    • Python interprets the signal to shift tabs or change the screen.

Components Required

  1. Arduino Board
  2. RF Transmitter and Receiver Module (433 MHz)
  3. IR Sensor (e.g., IR Proximity Sensor or IR LED and Photodiode Pair)
  4. Computer with Python Installed
  5. Jumper Wires
  6. Breadboard

Circuit Diagram











Transmitter Side:

  • Connect the IR sensor’s VCC, GND, and output to the RF transmitter module.
  • The RF transmitter is powered by 5V from the Arduino or an external source.

Receiver Side:

  • The RF receiver’s data pin connects to a digital pin on the Arduino (e.g., Pin 2).
  • The Arduino communicates with the computer via a USB cable.

Arduino Code

The Arduino listens for signals from the RF receiver and sends the data to the Python script.

const int receiverPin = 2; // RF receiver data pin

void setup() {
  Serial.begin(9600);
  pinMode(receiverPin, INPUT);
}

void loop() {
  int motionDetected = digitalRead(receiverPin);
  if (motionDetected == HIGH) {
    Serial.println("1"); // Send 1 if motion is detected
  } else {
    Serial.println("0"); // Send 0 if no motion
  }
  delay(100); // Slight delay to prevent spamming
}

Python Script

The Python script uses PySerial to read data from the Arduino and control the screen or tabs accordingly.

import serial
import time
import pyautogui  # For controlling the screen

# Configure serial communication
arduino = serial.Serial('COM3', 9600)  # Replace 'COM3' with your Arduino's port
time.sleep(2)  # Wait for Arduino to initialize

def change_tab():
    pyautogui.hotkey('ctrl', 'tab')  # Simulates a tab switch in browsers

while True:
    if arduino.in_waiting > 0:
        data = arduino.readline().decode('utf-8').strip()
        print(f"Received: {data}")
        if data == "1":
            print("Motion detected! Changing tab...")
            change_tab()
        elif data == "0":
            print("No motion detected.")

How It Works

  1. Motion Detection:
    The IR sensor detects motion when someone crosses its path and sends a HIGH signal to the RF transmitter.

  2. Wireless Communication:
    The RF transmitter sends this signal wirelessly to the RF receiver.

  3. Arduino Processing:
    The Arduino reads the signal from the receiver and transmits the corresponding data (1 or 0) to the connected computer via USB.

  4. Python Automation:
    The Python script monitors the serial input. If it receives a 1, it triggers a screen action like switching tabs using the pyautogui library. If it receives a 0, no action is taken.


Applications

  1. Home Automation: Automatically shift screens based on motion detection in different rooms.
  2. Security Systems: Alert systems when unauthorized motion is detected.
  3. Interactive Displays: Use motion detection for dynamic content switching on screens.

Videos

1. Working Video



2. Prototype Testing Video




Conclusion

This project showcases a simple yet effective way to integrate hardware and software for real-time motion detection and response. By combining RF communication, Arduino, and Python, we’ve created a system that can be scaled for various applications, from smart homes to interactive displays. Dive into this project and explore the endless possibilities of automation!

Tesla coil

 

Unlocking the Potential of a Tesla Coil: Driving Wireless Power with a TV Transformer and ZVS Driver

The Tesla coil, invented by Nikola Tesla in 1891, is a marvel of engineering that demonstrates the fascinating principles of resonant inductive coupling and high-frequency power transmission. One of its exciting applications is wireless power transfer, which is as relevant today as ever, given our growing demand for innovative power delivery methods. In this blog, we’ll delve into how to build and power a Tesla coil using a TV transformer and a Zero Voltage Switching (ZVS) driver to create a simple yet effective wireless power supply.


Understanding the Tesla Coil

A Tesla coil comprises two main components:

  1. Primary Coil and Capacitor: These form a resonant LC circuit driven by an external power source.
  2. Secondary Coil and Topload: The secondary coil, coupled inductively to the primary, steps up voltage to incredibly high levels, with the topload serving as a capacitor for energy storage.

The system generates high-frequency alternating currents, creating a high-voltage field capable of wireless power transmission.


Why Use a TV Transformer and ZVS Driver?

The combination of a TV transformer and a ZVS driver is an excellent choice for beginners and hobbyists looking to drive a Tesla coil. Here’s why:

  • TV Transformer: A high-voltage flyback transformer from an old CRT TV can step up voltage efficiently and is readily available.
  • ZVS Driver: The ZVS driver ensures efficient energy transfer to the transformer with minimal heat loss by switching the voltage at zero crossing points. This results in reduced stress on components and higher reliability.

Building the Tesla Coil Setup

Materials Required

  1. Tesla coil (secondary and primary windings)
  2. TV flyback transformer
  3. ZVS driver circuit
  4. Power source (12V to 24V DC, depending on the ZVS driver rating)
  5. High-voltage diodes and capacitors (optional for additional filtering)
  6. Heat sink for the ZVS driver
  7. Wires and connectors
  8. Tools: Soldering kit, multimeter, and safety gloves

Step-by-Step Guide

  1. Prepare the Tesla Coil:

    • Wind the secondary coil using fine magnet wire on a PVC pipe.
    • Create the primary coil using thicker wire and mount it around the base of the secondary coil.
    • Attach a topload (e.g., a metallic toroid or aluminum sphere) to the secondary coil.
  2. Set Up the ZVS Driver:

    • Assemble the ZVS driver circuit or use a pre-built module.
    • Ensure the driver is rated for the voltage and current requirements of your TV transformer.
  3. Connect the TV Flyback Transformer:

    • Identify the primary winding of the flyback transformer and connect it to the ZVS driver’s output terminals.
    • Leave the secondary winding as-is; it will generate high voltage to power the Tesla coil.
  4. Integrate the Tesla Coil with the Transformer:

    • Connect the high-voltage output of the flyback transformer to the Tesla coil’s primary coil. Ensure proper insulation to handle the high voltage.
  5. Power the System:

    • Connect the ZVS driver to a DC power source.
    • Use a multimeter to verify connections and check for short circuits before powering on.
  6. Test the Tesla Coil:

    • Turn on the power and observe the Tesla coil in action. You should see high-voltage arcs from the secondary coil and topload.



Working video 






Safety Precautions

  • Always handle high-voltage components with care.
  • Use insulated tools and wear gloves when working with the setup.
  • Ensure the work area is dry and free of conductive materials.
  • Keep a safe distance from the Tesla coil when operating to avoid electrical shock.

Applications and Beyond

This Tesla coil setup is a demonstration of wireless power transfer, which can power small fluorescent lights or act as a base for experiments in electromagnetism. It’s a stepping stone toward understanding more advanced concepts like energy harvesting, wireless charging, and even radio transmission.

By integrating a TV flyback transformer and a ZVS driver, you’re not only building a cost-effective and efficient Tesla coil driver but also diving into the legacy of Tesla’s groundbreaking work.


Conclusion

The synergy of a Tesla coil, TV transformer, and ZVS driver exemplifies how simple components can create a fascinating demonstration of wireless power. This setup is a great educational tool and a fun project for electronics enthusiasts. Whether you’re exploring the principles of high-voltage engineering or simply enjoying the spectacle of dancing electrical arcs, this project offers a rewarding experience.

Dive into the world of wireless 

Controlling devices with esp32 integrated with web site

 

ESP32 IoT Project

Overview

This project demonstrates how to manage Wi-Fi connections and interact with a server using an ESP32. The goal is to provide an efficient solution for handling dynamic Wi-Fi connections and device control through HTTP requests. We also include methods for resetting Wi-Fi credentials and troubleshooting common issues.


Wi-Fi Manager with AutoConnect and Reset Option

The ESP32 uses the WiFiManager library to simplify the Wi-Fi setup process. The following code demonstrates how to enable AutoConnect with an option to reset the Wi-Fi settings by holding a button for more than two seconds.

Example Code

#include <WiFiManager.h>  // https://github.com/tzapu/WiFiManager
#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

// Replace with the server URL
const char* serverURL = "http://your-server.local/ESP32_MySql_Database/Final/get_device_status.php";

int ledPin = 2;  // GPIO for the LED
int devicePins[] = {2, 4, 5};  // Array to control multiple devices (one GPIO per device)
int resetButtonPin = 0;  // GPIO pin for reset button
unsigned long buttonPressTime = 0;
bool resetWiFi = false;

void setup() {
    Serial.begin(115200);

    // Initialize reset button pin
    pinMode(resetButtonPin, INPUT_PULLUP);

    // Check if reset button is held down
    if (digitalRead(resetButtonPin) == LOW) {
        buttonPressTime = millis();
        while (digitalRead(resetButtonPin) == LOW) {
            if (millis() - buttonPressTime > 2000) {
                resetWiFi = true;
                break;
            }
        }
    }

    // Initialize WiFiManager
    WiFiManager wm;
    if (resetWiFi) {
        wm.resetSettings();  // Reset Wi-Fi settings
        Serial.println("Wi-Fi settings reset. Restarting...");
        ESP.restart();
    }

    // Attempt to auto-connect to WiFi with WiFiManager
    bool res = wm.autoConnect("AutoConnectAP", "password"); // AP name and password

    if (!res) {
        Serial.println("Failed to connect to Wi-Fi");
        ESP.restart();
    } else {
        Serial.println("Connected to Wi-Fi!");
    }

    // Initialize device pins
    for (int pin : devicePins) {
        pinMode(pin, OUTPUT);
        digitalWrite(pin, LOW);
    }
}

void loop() {
    // Ensure Wi-Fi is still connected
    if (WiFi.status() == WL_CONNECTED) {
        HTTPClient http;
        http.begin(serverURL);
        int httpResponseCode = http.GET();

        if (httpResponseCode == 200) {
            String response = http.getString();
            Serial.println("Received response:");
            Serial.println(response);

            // Parse JSON
            DynamicJsonDocument doc(1024);
            deserializeJson(doc, response);

            // Control each device based on the JSON response
            for (JsonObject device : doc.as<JsonArray>()) {
                int id = device["id"];
                int status = device["status"];

                // Control devices within devicePins array bounds
                if (id <= sizeof(devicePins) / sizeof(devicePins[0])) {
                    digitalWrite(devicePins[id - 1], status == 1 ? HIGH : LOW);
                    Serial.print("Device ");
                    Serial.print(id);
                    Serial.print(" Status: ");
                    Serial.println(status == 1 ? "ON" : "OFF");
                }
            }
        } else {
            Serial.print("Error code: ");
            Serial.println(httpResponseCode);
        }
        http.end();
    } else {
        Serial.println("Wi-Fi not connected");
    }

    delay(5000);  // Check every 5 seconds
}

PHP Script for Server-Side Handling

The server-side PHP script handles incoming HTTP requests and returns the status of connected devices as JSON. Below is an example of a PHP script to interact with the database and return device status:

Example PHP Code

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "esp32_database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, status FROM devices";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $devices = array();

    while ($row = $result->fetch_assoc()) {
        $devices[] = $row;
    }

    header('Content-Type: application/json');
    echo json_encode($devices);
} else {
    echo "[]";  // Empty JSON array if no data is found
}

$conn->close();
?>

Working Video:



Troubleshooting Tips

  • Ensure the ESP32 and server are on the same network.

  • Use the actual IP address of the server if http://mycomputer.local does not resolve.

  • Verify that the PHP script is hosted correctly on the server (e.g., using XAMPP or a similar tool).

  • Check for any firewall or network restrictions.

Electronic Dice With 7 – Segment Display

Aim The Aim of this project is to learn, study and create different ICs in digital logic and designing and create a unique project. This pro...