Skip to content

11. Embedded Networking and Communications

Group assignment:

  • Send a message between two projects
  • Document your work to the group work page and reflect on your individual page what you learned

This is the link to the group assignment.

Individual assignment:

  • design, build and connect wired or wireless node(s) with network or bus addresses and a local input and/or output devices

Connecting the Doppler to the Rasberry PI 4

Connecting the doppler to the rasberry pi was a very part to the creating of my magic mirror. I don’t think it will be my hardest part of my final project, but it will definitely be one of the hardest. The first partof this was to write the code and figure out the doppler. All my work for the doppler can be found on my input week.

Plugging in the Doppler to the Rasberry Pi

The first thing I did was plug in the dopper into the rasberry pi. Rather plugging it into a different computer, I believed that it would be easier to connect the dopller to the magic mirror (which I was wrong). I also decided todo that because that is where the doppler was going to be plugged into on the final result so it was bette to go ahead and do that.

Downloading Arduino

Since the Rasberry Pi is like a computer that uses linx but my code was in arduino, I needed to download arduino on the rasberry pi. The only problem with doing that is that there is a limited amount of storage that I have on the Pi and downloading the Arduino takes up alot of that. I decided to go ahead and do it otherwise because I came to the conclussion that I wouldn’t need to download anything else so it was ok. Downloading the arduino wasn’t the same proccess as a normal computer. Below are my chat Conversations to download it.

ChatGPT Conversations for Downloading Arduino

Steps for Downloading

At first I attempt to download arduino the way chat told me to but that did work so I attempted the old fashon way.

1) I went to the Arduino website under the download spot also found here. Under this I downloaded the Linux ARM 64-bit.

2) Once I downloaded that I followed the directions that were given to me

3) Then once I followed the directions, Arduino began to be downloaded. The one thing to keep in mind is that downloading Arduino takes up alot of storage. I dont need the rest of the storage for so I was able to download.

Creating Code to the Radar Doppler

I had already made the code for the doppler found in my input week.

Than I emailed the code from my personal computer to my self. Then on the rasberry pi, I went to the internet and went to gmail. And then I went into my email and downloaded my code. Once I downloaded my code, I added it to the Arduino that I downloaded. Then I plugged in the doppler straight into the rasberry pi so that it would connect to the Arduino.

Code for Doppler Radio

include

include

// WiFi Configuration const char WIFI_SSID = “YOUR_WIFI_SSID”; // Replace with your actual WiFi name const char WIFI_PASSWORD = “YOUR_WIFI_PASSWORD”; // Replace with your actual WiFi password

// Raspberry Pi Server Configuration const char* RASPBERRY_PI_IP = “192.168.1.100”; // Replace with your actual Raspberry Pi IP const int SERVER_PORT = 5000; // Match this with your Flask server port

// Doppler Radar Sensor Pin const int DOPPLER_PIN = D0; // Change if your sensor is connected to a different pin

// Debounce settings unsigned long lastTriggerTime = 0; const unsigned long DEBOUNCE_TIME = 5000; // 5 seconds between triggers

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

// Setup sensor pin pinMode(DOPPLER_PIN, INPUT);

// Connect to WiFi Serial.println(“Connecting to WiFi…”); WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(“.”); }

Serial.println(“\nWiFi Connected!”); Serial.print(“IP: “); Serial.println(WiFi.localIP());

// Test the connection to server testServerConnection(); }

void testServerConnection() { HTTPClient http; String url = “http://” + String(RASPBERRY_PI_IP) + “:” + String(SERVER_PORT) + “/test”;

Serial.print(“Testing connection to server: “); Serial.println(url);

http.begin(url); int httpCode = http.GET();

if (httpCode > 0) { Serial.print(“Server responded with code: “); Serial.println(httpCode); String response = http.getString(); Serial.print(“Response: “); Serial.println(response); } else { Serial.print(“Connection failed, error: “); Serial.println(http.errorToString(httpCode)); }

http.end(); }

void triggerMirror() { HTTPClient http; String url = “http://” + String(RASPBERRY_PI_IP) + “:” + String(SERVER_PORT) + “/trigger”;

Serial.print(“Motion detected! Sending request to: “); Serial.println(url);

http.begin(url); int httpCode = http.GET();

if (httpCode > 0) { Serial.print(“HTTP response code: “); Serial.println(httpCode); String response = http.getString(); Serial.println(response); } else { Serial.print(“HTTP request failed: “); Serial.println(http.errorToString(httpCode)); }

http.end(); }

void loop() { // Check WiFi connection if (WiFi.status() != WL_CONNECTED) { Serial.println(“WiFi disconnected. Reconnecting…”); WiFi.reconnect(); delay(1000); return; }

// Read motion sensor int motionState = digitalRead(DOPPLER_PIN);

// If motion detected and debounce time passed unsigned long currentTime = millis(); if (motionState == HIGH && (currentTime - lastTriggerTime > DEBOUNCE_TIME)) { triggerMirror(); lastTriggerTime = currentTime; }

delay(100); // Small delay to reduce CPU usage }

Things to Change

  • YOUR_WIFI_SSID with your actual WiFi name
  • YOUR_WIFI_PASSWORD with your actual WiFi password
  • 192.168.1.100 with your Raspberry Pi’s IP address

Looking Up IP To look up the IP adress of your rasberry pi you can use the following command:

hostname -I

Creating the Flask File

To make a new file in the terminal of the Raspberry Pi, I used the following command. This is the file for the flask. nano ~/MagicMirror/mirror_server.py

To find the right Path: find /home -name MagicMirror -type d

What is Flask?

Flask is a micro web framework for Python that allows you to build web applications quickly and with minimal setup. It’s lightweight and flexible, making it easy to scale from a simple prototype to a full-fledged web application. Flask provides you with tools and libraries to build and manage HTTP requests, web pages, and APIs.

Why would you want to use Flask?

You would use Flask in scenarios where you want to:

1) Create a web application: Flask can be used to build a variety of web applications, ranging from simple APIs to full-fledged websites with dynamic content.

2) Set up a simple HTTP server: If you need to interact with other programs (like turning on a display or triggering processes) via a browser or an HTTP request, Flask provides an easy way to expose those functionalities over the web.

3) Create a web API: Flask can be used to create APIs (Application Programming Interfaces) that allow other applications or devices to interact with your software.

4) Build on top of Python: Since Flask is Python-based, you get the power and flexibility of Python combined with the simplicity of Flask’s web routing.

Explaining the Code

from flask import Flask

This imports the Flask class from the Flask library. You use this class to create your web app.

import os

The os module allows you to interact with the operating system. In this case, it’s used to turn the display on/off.

import subprocess

The subprocess module lets you run system commands and external programs. In this case, it is used to check if a process (Magic Mirror) is running and start it if needed.

app = Flask(__name__)

Here, you’re creating an instance of the Flask application.

Flask(__name__)

This tells Flask to look for files and resources in the current directory and sets up the app to handle incoming web requests.

@app.route('/test')

This decorator tells Flask that when the user visits the /test URL, the function test() should be called.

def test():

This function is called when someone visits the /test route. It returns a simple string “Connection successful!” to the user, confirming that the web app is up and running.

@app.route('/trigger')

This route listens for HTTP requests to /trigger. When this URL is visited, it runs the trigger() function.

os.system('vcgencmd display_power 1')

This command turns on the Raspberry Pi’s display using the vcgencmd utility. The vcgencmd command controls various Pi hardware features, and here display_power 1 turns the display on.

subprocess.run("pgrep -f 'node'")

This line checks if any process involving node (Node.js) is running. Since Magic Mirror is a Node.js app, we are using pgrep -f ‘node’ to search for any running node processes. If no process is found, the stdout will be empty (b’‘).

shell=True

This tells Python to run the command in a shell (like running a command in the terminal). It’s necessary for some commands to run correctly.

stdout=subprocess.PIPE

This captures the standard output of the command (if there is any), which we check later to determine if Magic Mirror is running.

stderr=subprocess.PIPE

This captures any error output generated by the command.

These print statements help with debugging. They show the output (stdout and stderr) of the pgrep command, so you can see whether it finds any processes and if there are any errors.

if check_process.stdout == b''

This checks if pgrep didn’t find any process running. If the output is empty (b’‘), we proceed to start Magic Mirror.

subprocess.Popen()

This starts a new process. It runs the command cd /path/to/magicmirror && npm start, which changes the directory to your Magic Mirror installation and runs npm start to launch the Magic Mirror application. It runs in the background.

return "Display turned on and Magic Mirror started!"

If the process isn’t running, it starts Magic Mirror and returns this message.

else:

If pgrep finds a running node process (meaning Magic Mirror is already running), it returns “Display turned on, Magic Mirror already running!”.

except Exception as e:

If there’s an error in the process (e.g., starting Magic Mirror or running the command), the exception will be caught, and an error message is returned.

app.run(host='0.0.0.0', port=5000)

This starts the Flask web server. host=‘0.0.0.0’ makes the app accessible from any IP address, and port=5000 sets the server to run on port 5000. This means you can access your app on your Raspberry Pi’s IP address, like http://:5000.

Why Use Flask in This Scenario?

1) Control Hardware via Web Interface: You want to control your Raspberry Pi (turn on the display, start Magic Mirror) through a web interface. Flask provides a lightweight way to expose this functionality over HTTP. 2) Ease of Development: Flask is simple to set up and doesn’t require complex configuration. It allows you to focus on the core functionality (controlling Magic Mirror and the display).

Access Anywhere: With Flask, you can access your Raspberry Pi’s functionality from any device with a web browser. You don’t need to interact directly with the Pi’s terminal.

This is the code for the flask.

from flask import Flask
import os
import subprocess
import time


app = Flask(__name__)


# Global flag to check if Magic Mirror is already running
mirror_running = False
last_trigger_time = 0
TRIGGER_COOLDOWN = 60  # Set a cooldown time of 60 seconds to prevent multiple triggers


@app.route('/test')
def test():
    return "Connection successful!"


@app.route('/trigger')
def trigger():
    global mirror_running, last_trigger_time

    # Check if enough time has passed since the last trigger
    current_time = time.time()
    if current_time - last_trigger_time < TRIGGER_COOLDOWN:
        return "Magic Mirror is already running or recently started. Please wait before triggering again."


    # Turn on the display
    os.system('vcgencmd display_power 1')


    try:
        # Check if any Node.js process is running
        print("Checking for running Node.js processes...")
        check_process = subprocess.run(
            "pgrep -f 'node'",  # Check for any running Node.js process
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )


        # Debugging: Print the output of pgrep
        stdout = check_process.stdout.decode().strip()
        stderr = check_process.stderr.decode().strip()


        print("Process check stdout:", stdout)
        print("Process check stderr:", stderr)


        # If a Node.js process is running, kill it before restarting Magic Mirror
        if stdout != '':  # Process is running (stdout will have a PID)
            pid = stdout
            print(f"Node.js process found with PID {pid}. Killing the process...")
            os.system(f"kill -9 {pid}")  # Forcefully kill the process


        # Start Magic Mirror if it's not already running
        if not mirror_running:
            print("Starting Magic Mirror...")
            process = subprocess.Popen(
                "cd /home/elhah/MagicMirror && npm run start",  # Adjust path to your Magic Mirror installation
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )


            # Capture stdout and stderr for debugging
            stdout, stderr = process.communicate()
            print("Magic Mirror stdout:", stdout.decode())
            print("Magic Mirror stderr:", stderr.decode())


            # Set the flag that Magic Mirror is running and update the last trigger time
            mirror_running = True
            last_trigger_time = current_time
            return "Display turned on and Magic Mirror started!"


        else:
            return "Magic Mirror is already running!"

    except Exception as e:
        return f"Display turned on, but error starting Magic Mirror: {str(e)}"




if __name__ == '__main__':
    # Make sure to run on all network interfaces
    app.run(host='0.0.0.0', port=5000, debug=True)  # debug=True to see error logs in terminal

Running the Flask File

To run the flask file I use the following command:

python3 mirror_server.py

Then as the flask is running, I uploaded the code from arduino code to the seeed and then went to the URL.

On the URL website you could see the process of the doppler sensing the motion of my hand. Then you could see it connecting to the IP adress and then it worked.

Below is a video of it working:

Reflection

Individual Assignment

This week really helped me for my final project. This week helped me get a lot done towards my final project. It was very hard but I ad proud of it.

Group Assignment

The group assignment was very easy and straight forward which made me like this week. Using the wired way to send to each other is easier than using wifi.


Last update: August 10, 2025