New Multi-Sensor Environmental Monitoring Solution: The Perfect Combination of Raspberry Pi 4B and STC8G

The Raspberry Pi 4B and STC8G microcontroller work together to create a new intelligent environmental monitoring system, easily achieving three main functions: displaying current video surveillance images and temperature and humidity data on a web page, and automatically saving recordings when an object enters the monitored area. How is this done? Let’s take a look at the author’s design approach!

Project View:

https://www.eetree.cn/project/4076

1

Project Introduction

The system uses the Raspberry Pi 4B as the main controller, utilizing a USB camera for video capture, and builds a local area network video server using the Flask framework, supporting real-time viewing of surveillance footage through a web browser.

The STC8G microcontroller is responsible for collecting data from the DHT11 temperature and humidity sensor and the HC-SR04 ultrasonic sensor, transmitting the data in real-time to the Raspberry Pi via the UART serial communication protocol. When a sudden change in ultrasonic distance value is detected (indicating an object entering the monitored area), the system automatically triggers a GPIO-controlled alarm indicator light and saves the video from 6.66 seconds prior to the trigger. The web server is built using the Flask framework, providing not only real-time video streaming but also temperature and humidity value display, event time recording, and historical video download functionality.

New Multi-Sensor Environmental Monitoring Solution: The Perfect Combination of Raspberry Pi 4B and STC8G

2

System Architecture Design

New Multi-Sensor Environmental Monitoring Solution: The Perfect Combination of Raspberry Pi 4B and STC8G

Raspberry Pi 4B: Video capture module, web service module, data processing module, object detection event response module.

STC8G: Sensor collection module, communication module, object detection event trigger module.

System Collaboration Mechanism: The Raspberry Pi and STC8G establish a serial communication link through a USB-TTL converter. The Raspberry Pi polls to receive sensor data packets and updates the web interface. When an ultrasonic event is triggered, the STC8G transmits the event signal to the Raspberry Pi, which then starts the video saving thread, achieving a closed-loop event response between the hardware and software layers.

3

Software Implementation & Key Code Explanation

New Multi-Sensor Environmental Monitoring Solution: The Perfect Combination of Raspberry Pi 4B and STC8G

⚪ Web Service Module

1. Purpose: To build a Flask-based web service system that provides a user interaction interface and data API, achieving visual interaction for the monitoring system.

2. Functions:

🔹 Main Page Route (/):

  • Dynamically render HTML templates to display real-time video, sensor data, and event records.

  • Automatic refresh mechanism (30-second interval).

  • Video file list sorted in reverse chronological order, with download links.

🔹 Video Stream Route (/video_feed): Push MJPEG format video stream, supporting cross-platform browser access.

🔹 File Download Route (/download/<filename>): Provide secure video file download service.

🔹 Time Synchronization Interface (/get_time): Returns the current standard time of the server.

3. Output:

  • Dynamic web page: HTML page containing real-time video stream, temperature and humidity data, and event records.

  • HTTP response: Video stream data packets (multipart/x-mixed-replace type).

  • File transfer: AVI format video file download service.

@app.route('/')
def index():    # Get the list of saved video files    videos = []    for f in sorted(os.listdir(VIDEO_DIR), reverse=True):        if f.endswith('.avi'):            timestamp = datetime.strptime(f[6:-4], "%Y%m%d_%H%M%S")            videos.append({                'filename': f,                'time': timestamp.strftime("%Y-%m-%d %H:%M:%S"),                'url': url_for('download_video', filename=f)  # Generate download URL            })    server_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")    current_tem, current_hum = sensor_vals.tem, sensor_vals.hum    return render_template_string('''        &lt;html&gt;        &lt;head&gt;            &lt;title&gt;Video Surveillance&lt;/title&gt;            &lt;meta http-equiv="refresh" content="30"&gt;  &lt;!-- Auto refresh every 30 seconds --&gt;        &lt;/head&gt;        &lt;body&gt;            &lt;h1&gt;Real-time Video Stream&lt;/h1&gt;            &lt;img src="/video_feed" style="width:640px; height:480px;"&gt;            &lt;h2&gt;Sensor Data Refresh Time {{server_time}} &lt;/h2&gt; &lt;!-- Add sensor data this way --&gt;            &lt;h3&gt;Current Temperature{{ current_tem }}℃, Current Humidity{{ current_hum }}%&lt;/h3&gt;            &lt;h2&gt;Event Records (Total {{ videos|length }} items)&lt;/h2&gt;            &lt;h3&gt;Click event name to download the video&lt;/p&gt;            &lt;ul&gt;            {% for video in videos %}                &lt;a href="{{ video.url }}" download                 style="margin-left: 20px; text-decoration: none;"&gt;                &lt;button style="padding: 3px 8px; background: white; color: black; border: none; border-radius: 3px;"&gt;                    {{ video.time }}                &lt;/button&gt;                &lt;br&gt;                &lt;/a&gt;            {% endfor %}            &lt;/ul&gt;            &lt;h3&gt;Others&lt;/h3&gt;        &lt;/body&gt;        &lt;/html&gt;    ''', videos=videos, server_time=server_time, current_tem=current_tem, current_hum=current_hum) # Register variables to be [email protected]('/video_feed')
def video_feed():    return Response(video_stream.gen_frames(),                    mimetype='multipart/x-mixed-replace; boundary=frame')@app.route('/get_time')
def get_time():    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")@app.route('/download/&lt;filename&gt;')
def download_video(filename):    # Security verification    if '..' in filename or filename not in os.listdir(VIDEO_DIR):        abort(404)    return send_from_directory(VIDEO_DIR, filename,                              as_attachment=True)

⚪ Object Detection Event Response Module

1. Purpose: To respond to the trigger signal from the ultrasonic sensor and execute video saving operations, achieving event-driven video archiving.

2. Functions:

🔹 Event Monitoring:

  • Monitor the trig state changes of the data processing module.

  • Activate response when the minimum trigger interval (30 seconds) is met.

🔹 Video Saving:

  • Create a separate thread to execute the recording task.

  • Extract the last 100 frames (approximately 6.6 seconds) from the circular buffer.

  • Generate a standard AVI file (XVID encoding, 15FPS, 640×480 resolution).

  • The filename includes the event time (format: event_20240516_142643.avi).

🔹 File Management:

  • Store videos in a specified directory.

  • Automatically maintain a downloadable file list.

3. Output:

  • Event video file: Standard AVI format video file (including 6 seconds of video before the event).

  • Web event record: Downloadable link list with timestamps.

def monitor_pipe(pipe_path, recorder):    print(f'pipe_path={pipe_path}')    if not os.path.exists(pipe_path):        os.mkfifo(pipe_path)    while True:        with open(pipe_path, 'r') as pipe:            while True:                line = pipe.readline().strip()                sensor_vals.process(line)                if sensor_vals.trig:  # Detected trigger mark                    threading.Thread(target=recorder.start_recording).start()                time.sleep(0.1)

The code section has omitted some content; interested readers can access the complete content by clicking “Read the original article”.

4

Function Demonstration

In the web browser page screenshot, in addition to the real-time monitoring video, other information (temperature, humidity, time of object entering the monitored area) updates every 30 seconds. Clicking on the event time allows downloading the video from 6.66 seconds prior to the event. The attachment event_20250319_122919.avi is the recorded video.

New Multi-Sensor Environmental Monitoring Solution: The Perfect Combination of Raspberry Pi 4B and STC8G

Image showing the hardware device and real-time video stream in the same frame. The project hardware system (camera with black casing, Raspberry Pi, breadboard) is displayed on the table. The web page on the left shows the video stream, while the camera captures the project hardware system, and the web page on the right displays the current time, consistent with the video stream timestamp.

New Multi-Sensor Environmental Monitoring Solution: The Perfect Combination of Raspberry Pi 4B and STC8G

Image showing downloadable surveillance video. The attachment event_20250328_121432.avi is the complete video, recording approximately 6 seconds of data before an object entered the monitored area (indicated by the light on the breadboard).

New Multi-Sensor Environmental Monitoring Solution: The Perfect Combination of Raspberry Pi 4B and STC8G

5

Problems Encountered and Solutions

This project uses a small tungsten filament bulb as an indicator light, which requires a minimum working current of 20mA and is not suitable for direct driving by the STC8G. After consideration, I used a 9018 transistor to drive the tungsten bulb, solving the problem of insufficient output current from the microcontroller.

6

Project Summary

This system has high practicality and scalability, and can be widely applied in smart homes, warehouse security, environmental monitoring, and other IoT scenarios. By integrating video surveillance, environmental sensing, and event response functions, the system achieves comprehensive monitoring and intelligent management of the environment, providing a reliable technical solution for IoT applications.

7

Attachment Download

The author has open-sourced detailed information on Electronic Forest, and you can access all content by clicking “Read the original article”!

New Multi-Sensor Environmental Monitoring Solution: The Perfect Combination of Raspberry Pi 4B and STC8GNew Multi-Sensor Environmental Monitoring Solution: The Perfect Combination of Raspberry Pi 4B and STC8G

Click “Read the original article” to design your project!

Leave a Comment