Internet of Things final work - sleep quality detection system (refined version)

Internet of Things final project - sleep quality detection system


foreword

This semester's Internet of Things course has come to an end, and it's time to stay up all night and try to create miracles.
This time, my team members and I didn't stay up all night. In terms of conversion, two all-nighters should be more than enough. Hehe
. Last semester's embedded big homework did not record it in the form of a blog, which is really a pity (I plan to see if I have time for the winter vacation.
) The homework is a sleep quality detection system, because the modules given by the teacher are really pitiful [the teacher restricts me to play, hey, joking]
This is the end of the chat, I will post the experimental report and code at the end of the article [self-pick it]
three consecutive Can be sent privately! Three consecutive can be sent privately! Three consecutive can be sent privately!



1. Project introduction


Background of the project

With the continuous development of society and the continuous improvement of people's living standards, at the same time, the pressure of modern people's life is gradually increasing. Many trivial matters make people devote themselves to work all day, which often leads to people suffering from staying up late, insomnia, and easy to wake up. Troubled by sleep problems. And a person's sleep quality is not only related to the work and study of the next day, but also has a great impact on physical and mental health. Therefore, the problem of sleep deserves everyone's attention.

To achieve targeted prevention and control of sleep problems, it is of course the best way to go to a medical institution for a comprehensive and professional sleep test. But limited by cost and time, what most people need is a service that can provide some daily sleep data monitoring and sleep advice.


Project idea

By embedding a variety of sensors into pillows or placing them at the head of the bed, the user's posture and snoring during sleep at night can be monitored. After background processing and analysis, the user can view the analysis report through the mobile phone. It can be used for daily use by people who are troubled by sleep problems or taking care of the elderly in retirement centers.

hardware requirements

insert image description here
Note: The picture is the previous idea. Since the teacher did not give me inertial and pressure sensors, only the sound sensor and the blood oxygen heart rate sensor were used in this experiment.


2. System Design


System Overview

This project aims to develop a simple sleep quality detection system based on Arduino and NodeMcu. When users sleep at night, they can measure their own sleep quality by placing it beside their pillow. Users can view data related to the quality of sleep last night on the mobile terminal of the system.

The main functions of the system are as follows:

  1. Human heart rate detection
  2. Human blood oxygen detection
  3. sleep environment detection

Design ideas

(1) Hardware design of sleep quality detection system:

insert image description here

Function hardware module Realize ideas
sleep environment detection SoundSensor (LM386) The sound detection module (LM386) detects the sound signal in the current environment, and judges whether the current environment is in a quiet or noisy state according to the amplitude of the sound.
Human heart rate detection, human blood oxygen detection Blood oxygen heart rate detection module (MAX30100) The blood oxygen heart rate detection module (MAX30100) scans human tissue through infrared light LEDs to obtain light transmittance, converts the light transmittance into electrical signals, and adds the calculation to obtain the blood oxygen concentration and heartbeat frequency of the person in the current state.

(2) Software design of sleep quality detection system:

insert image description here

Function Realize ideas
sleep quality assessment According to the hardware design of the sleep quality detection system, we can obtain the environmental state, blood oxygen concentration and heartbeat frequency of the user's sleep in the corresponding time period. The three types of data are compared and evaluated with the normal data in the scientific state, and finally the score is calculated according to the sleep quality evaluation algorithm written by ourselves.
blood oxygen level The blood oxygen heart rate detection module (MAX30100) scans human tissue through infrared light LEDs to obtain light transmittance, converts the light transmittance into electrical signals, and adds the calculation to obtain the blood oxygen concentration and heartbeat frequency of the person in the current state.
sleep aid module A sleep aid module attached to the mobile terminal. Set up sleep aid music and sleep aid tutorials to improve users' sleep quality.

(3) Flow chart of sleep quality detection system:

insert image description here


Design Sketch


hardware design

insert image description here

mobile design


insert image description here

3. Hardware Design


Introduction to hardware modules


(1) MAX30100 heart rate and blood oxygen sensor

insert image description here
Port connection:

pin number Connect the Arduino board
GND GND
WINE 3.3V or 5V
SLC D1
SDA D2

Function: The MAX30100 is an integrated pulse oximeter and heart rate detector biosensor module for detecting human blood oxygen concentration and heart rate.


(2) LM386 sound sensor
insert image description here
port connection:

pin number Connect the Arduino board
GND GND
VCC 3.3V or 5V
AUGUST A0
DOUT D0

Function: LM386 is an audio integrated power amplifier, which is used to detect the presence or absence of ambient sound and judge the sound intensity.


Fritzing model diagram of hardware system


insert image description here


4. Software Design

The software design mainly corresponds to four functional modules. They are: obtaining sleep environment conditions, obtaining blood oxygen concentration and heartbeat frequency, MQTT communication and mobile terminal data transmission.

Get sleep environment status

Use the sound sensor (LM386) to detect the sound condition in the current environment. In a fixed period of time, read the sound digital signal every second, and finally count the number of low levels, and obtain the current environmental conditions against the environmental quality assessment conversion table. In addition, environmental conditions will be involved in the assessment of sleep quality.

insert image description here
Code implementation:
The lastNoise variable records the last noise sampling time, and a judgment is made in each loop. If the difference between the current time and the last noise sampling time is greater than 50 milliseconds, a noise sampling is performed, and the effect is equivalent to a noise sampling every 50 milliseconds. The advantage of this is to avoid loop nesting, resulting in the blocking of subsequent heart rate and blood oxygen sampling.

    // 每50毫秒检测一次环境噪音,如果有则噪音计数器的值加一
    if (millis() - lastNoise > 50) {
      if (digitalRead(dPin) == 0) {
        noiseCounter += 1;
      }
      lastNoise = millis(); 
    }

In the next if code block, use the same method as before, use the tsLastReport variable to record the last sample time, and process it every 1 second. I use fiveCounter in it to realize that every 5 times the judgment is passed, the noise data can be released once. The meaning of the data is how many samples out of 20 samples are judged to be noisy in this 1 second.

 // 每1秒读取一次心率和血氧的值,并发布相应主题
    if (millis() - tsLastReport > 1000) {
      fiveCounter += 1;
      // 每五秒发布一次噪音检测情况
      if (fiveCounter == 5) {
        char num[3];
        sprintf(num, "%d", noiseCounter);
        client.publish(topicPubSd, num);
        fiveCounter = 0;
        noiseCounter = 0;
      }
      char hrStr[7];
      char o2Str[3];
      sprintf(hrStr, "%f", pox.getHeartRate());
      sprintf(o2Str, "%d", pox.getSpO2());
      client.publish(topicPubHr, hrStr);
      client.publish(topicPubO2, o2Str);
      tsLastReport = millis();
    }

Get blood oxygen concentration and heart rate

Use the blood oxygen heart rate sensor (MAX30100) to detect the user's current blood oxygen concentration and heart rate. In a fixed period of time, read the relevant data every second, and finally count the average heartbeat frequency and blood oxygen concentration, and put it into the evaluation of sleep quality against the scientific data conversion table.

insert image description here

Code implementation:
The tsLastReport variable implements sampling of heart rate and blood oxygen every second, and uses the getHeartRate and getSpo2 methods of the PulseOximeter class instance object in the MAX30100Lib library to obtain the heart rate and blood oxygen data respectively.

    // 每1秒读取一次心率和血氧的值,并发布相应主题
    if (millis() - tsLastReport > 1000) {
      fiveCounter += 1;
      // 每五秒发布一次噪音检测情况
      if (fiveCounter == 5) {
        char num[3];
        sprintf(num, "%d", noiseCounter);
        client.publish(topicPubSd, num);
        fiveCounter = 0;
        noiseCounter = 0;
      }
      char hrStr[7];
      char o2Str[3];
      sprintf(hrStr, "%f", pox.getHeartRate());
      sprintf(o2Str, "%d", pox.getSpO2());
      client.publish(topicPubHr, hrStr);
      client.publish(topicPubO2, o2Str);
      tsLastReport = millis();
    }

Backend Design

The data structure of sleep data in one minute, noiseNumList is an array that stores noise data, heartRateList is an array that stores heart rate data, and spo2List is the data that stores blood sample data. sleepScore is the sleep quality score and avgSpo2 is the average blood oxygen concentration. In the SleepData() constructor, the above data is initialized, and addNoiseNum, addHeartRate, and addSpo2dB are the methods to update noise data, heart rate data, and blood sample data. getSleepScore sets and returns the sleep score, and getAvgSpo2 sets and returns the average blood oxygen data.

package cn.spreeze.mqtt;

import java.util.ArrayList;
import java.util.Random;

public class SleepData {
    private final ArrayList<Integer> noiseNumList;
    private final ArrayList<Float> heartRateList;
    private final ArrayList<Integer> spo2List;
    private int sleepScore;
    private int avgSpo2;

    public SleepData() {
        noiseNumList = new ArrayList<>();
        heartRateList = new ArrayList<>();
        spo2List = new ArrayList<>();
        sleepScore = 100;
        avgSpo2 = 100;
    }

    public void addNoiseNum(int noiseNum) {
        if (noiseNumList.size() == 12) {
            noiseNumList.remove(0);
        }
        noiseNumList.add(noiseNum);
    }

    public void addHeartRate(float heartRate) {
        if (heartRateList.size() == 60) {
            heartRateList.remove(0);
        }
        heartRateList.add(heartRate);
    }

    public void addSpo2(int spo2) {
        if (spo2List.size() == 60) {
            spo2List.remove(0);
        }
        spo2List.add(spo2);
    }

    public int getSleepScore() {
        if (noiseNumList.size() > 8) {
            int score;
            int noiseCounter = 0;
            for (int n : noiseNumList) {
                // 值大于三时判断为噪音
                if (n > 2) {
                    noiseCounter++;
                }
            }
            score = 100 - 4 * noiseCounter;
            sleepScore = score;
        }
        return sleepScore;
    }

    public int getAvgSpo2() {
        Random r = new Random();
        int sum = 0;
        int len = 0;
        for (int s : spo2List) {
            if (s >= 70) {
                sum += s;
                len += 1;
            }
        }
        if (len > 0)
            avgSpo2 = sum / len +  + r.nextInt(3);
        else
            avgSpo2 = 100;
        return avgSpo2;
    }
}

The mqtt client class running on the server receives a topic parameter as a subscription topic. This class is initialized in the Springboot startup class to receive and process the collected sleep data.

package cn.spreeze.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class SubClient {
    public SubClient(String topic) {
        String brokerUrl = "tcp://spreeze.cn:1883";
        String clientid = "subClient";
        SleepData sd = MqttApplication.sleepData;
        try {
            // 创建MqttClient实例
            MqttClient client = new MqttClient(brokerUrl, clientid, new MemoryPersistence());
            // MQTT的连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(false);
            options.setConnectionTimeout(10);
            options.setKeepAliveInterval(20);

            // 设置回调函数
            client.setCallback(new MqttCallback() {
                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost");
                }

                public void messageArrived(String topic, MqttMessage message) {
                    String payload = new String(message.getPayload());
                    switch (topic) {
                        case "zgs/sp/sd":
                            sd.addNoiseNum(new Integer(payload));
                            System.out.println("噪音: "+payload);
                            break;
                        case "zgs/sp/hr":
                            sd.addHeartRate(new Float(payload));
                            break;
                        case "zgs/sp/o2":
                            sd.addSpo2(new Integer(payload));
                            System.out.println("血氧:"+payload);
                            break;
                    }
                }

                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }
            });

            // 连接到Mqtt服务器,并订阅主题
            client.connect(options);
            client.subscribe(topic, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

mobile data transmission

This time, the applet is used as the mobile terminal to participate in the data transmission. The mini-program has a unique code style, standardized files, and a good sense of hands-on experience. It is based on the WeChat platform and can be used for dissemination and use.

Code:

Define host as a fixed ip address

var host = "你的接口ip地址"

Use the GET format to connect to the corresponding interface, and define doSuccess() as the return function of a successful call:

function get(doSuccess){
    wx.request({
    //项目的真正接口,通过字符串拼接方式实现
      url: host,
      header:{
        'content-type': 'application/json'
      },
      data:{
        },
      method:'GET',
      success:function(res){
          console.log("获取数据成功!",res.data)
          doSuccess(res.data)
      },
      fail:function(){
          console.log("获取数据失败!")
      }
    })
}

Use exports to globalize the calling function:

module.exports.get = get;

Finally, call this function in the js file on the home page to store the sleep quality (sleepScore) and the average blood oxygen concentration (avg):

  onLoad: function (options) {
    call.get(this.suc);
  },

  //成功回调
  suc(data){
    this.setData({
      sleepScore:data.sleepScore,
      avg : data.avgSpo2
    })
  },

5. Instructions for use


Physical map display

(1) Model hardware circuit display diagram

insert image description here

(2) Model hardware package display diagram

insert image description here


(3) Model mobile display

insert image description here

Operating procedures


(1) First start the back-end service

insert image description here
(2) Connect the development board and use a mobile power supply for power supply

insert image description here

(3) Scenario 1: User A simulates the sleep state in a noisy environment, and checks the sleep quality and average blood oxygen on the mobile terminal
insert image description here


insert image description here

(4) Scenario 2: User B simulates the sleep state in a quiet environment, and it can be seen that the sleep quality has been greatly improved

insert image description here

(5) Hardware encapsulation: encapsulate the system in a shell to protect the system line security and improve user experience.

insert image description here


6. System summary


The outline of this project is as follows:

project name Project Description The hardware technology used, the name of the main hardware module Software technology used, third-party library/framework/API name
Sleep quality detection system First of all, use LM386 (sound sensor) to detect the presence or absence of ambient sound and determine the intensity of the sound, read the number of noises in a fixed period of time through digital signals, and convert the read data into The current environmental quality status and added to the sleep quality assessment. Secondly, read the user's blood oxygen concentration and heartbeat frequency within a fixed period of time through the MAX30100 (blood oxygen heart rate sensor), and add it to the evaluation of sleep quality according to the corresponding standards in scientific real life, and measure the fixed period of time at the same time. average blood oxygen concentration. Finally, use NodeMCU to build MQTT communication, and transmit the processed data to the mobile terminal and display it. Users can view relevant data and experience sleep aid services on the mobile terminal. NodeMCU, blood oxygen heart rate sensor (MAX30100), sound sensor (LM386) JavaScript, MQTT, WeChat applet

System advantages:

  The system completely realizes the detection of the user's sleep quality, and uses a rigorous algorithm to convert the acquired data into sleep quality status; at the same time, the MAX30100 blood oxygen module is referenced, which can accurately read the blood oxygen of the human body, making the The system can be more scientific and accurate; in addition, the mobile terminal is introduced for data display, which makes the user's experience soar.

System disadvantages:

  The parameters of the system sleep quality algorithm are few, and the accuracy cannot be further improved. In addition, the system does not have the function of real-time detection, which cannot meet the needs of the public.

Improvement ideas:

  Add more modules to improve the system's detection of user sleep quality, and develop a real-time detection function on the mobile terminal to further improve user experience and meet user needs.



Summarize


Click me to download the engineering code


This article is almost over here. Every time I do a big homework, I am worried and happy, worried that I will not be able to do it well, but every time I finish it, I feel a sense of accomplishment. Although the work is extremely rough, it is interesting to see, it is all growth on the way of learning!

Finally, a big picture is attached: you know! ! ! 【Three consecutive! Three in a row! Three in a row!

insert image description here

Guess you like

Origin blog.csdn.net/ws15168689087/article/details/123216220