Amadej PavšičMihaJSGašper Oblak
Published

Postchair - an AIoT device for bettering your posture

Relieving back pain one Arduino at a time. Reliable, cheap and easy to use solution, based on AIoT.

IntermediateWork in progress339
Postchair - an AIoT device for bettering your posture

Things used in this project

Hardware components

Nano 33 BLE Sense
Arduino Nano 33 BLE Sense
×1

Software apps and online services

Arduino IDE
Arduino IDE
Edge Impulse Studio
Edge Impulse Studio
Visual Studio Code Extension for Arduino
Microsoft Visual Studio Code Extension for Arduino

Hand tools and fabrication machines

elastic waistband

Story

Read more

Code

Arduino Library with our ML model

Arduino
Add it to Arduino IDE.
No preview (download only).

Web App

JavaScript
Start Web App on local server.
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title></title>
  <link href="index.css" rel="stylesheet" />
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>

<body>

  <div id = "page-title-div">

    <h1 id = "title">
      Posture check
    </h1>
  
  </div>

  <div id = "page-info-div">

    <button data-toggle="modal" data-target="#exampleModalCenter" id = "info-btn"><img src = "img/info-button.svg" id = "info-btn-img"></button>
  
  </div>
  
  <div id = "fullscreencontainer">

    <button onclick="onButtonClick()" id = "startposturecheckbtn"><img src = "img/start-button.svg" id = "start-btn-img"></button>

    <!-- Loading circle -->
    <div class="lds-ellipsis"><div id = "displayLoad"></div><div></div><div></div><div></div></div>
    
    <div id = "posture-display">
      <button onclick="onStopClick()" id = "stopbtn" style = "display: none;"><img src = "img/stop-button.svg" id = "stop-btn-img"></button>
      
      <h4 id = "postureStatus">
      
      </h4>

    </div>
    
  </div>

  <div id="sound"></div>


  <!-- INFO MODAL -->
  <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLongTitle">HOW TO USE</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span id= "close-mod" aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <ol>
            <li>
              Plug in your <b> Arduino </b>
            </li>
            <li>
              Press the <b>start</b> button
            </li>
            <li>
              Pay attention to the <b>backrgound color / sounds</b> that notify you about your posture
              <ul>
                <li>
                  <span style = "color: #6CEB6A;">Green:</span> Your posture is perfect
                </li>
                <li>
                  <span style = "color: #F25E5E;">Red:</span> Your posture is not as it should be
                </li>
                <li>
                  <span style = "color: #F2C95E;">Yellow:</span> Uncertain
                </li>
              </ul>
            </li>
            <li>
              Press the <b>stop</b> button when you want to stop
            </li>
          </ol>

        </div>
        
      </div>
    </div>
  </div>
  

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>


  <script>
    let BUFFER = [];
    let iBuf = 0;
    let length = 20; //(/2 == sekunde)
    let n_filter = 15;

    for(let i = 0; i < length; i++) {
        BUFFER.push(-1);
    }

    function onButtonClick() {

      const startBtn = document.getElementById("startposturecheckbtn");
      const loadAnim = document.getElementById("displayLoad");
      const stopBtn = document.getElementById("stopbtn");
      const postStat = document.getElementById("postureStatus");
      
      startBtn.disabled = true;
      
      
      startBtn.style.display = "none";
      loadAnim.style.display = "block";
      


      console.log('Requesting Bluetooth Device...');
      navigator.bluetooth.requestDevice({
        acceptAllDevices: true,
        optionalServices: ['757ab0ec-a387-11eb-bcbc-0242ac130000']})
      .then(device => {
        console.log('Connecting to GATT Server...');
        return device.gatt.connect();
      })
      .then(server => {
        console.log('Getting Posture Service...');
        return server.getPrimaryService('757ab0ec-a387-11eb-bcbc-0242ac130000');
      })
      .then(service => {
        console.log('Getting Posture Characteristic...');
        return service.getCharacteristic('757ab0ec-a387-11eb-bcbc-0242ac130001');
      })
      .then(characteristic => {
        console.log("Entering Reading loop.");
        readValueContinuous(characteristic);
        stopBtn.disabled = false;
        loadAnim.style.display = "none";
        stopBtn.style.display = "block";
        postStat.style.display = "block";
      })
      .catch(error => {
        console.log('Argh! ' + error);
      });
    };

    function onStopClick(){
      window.location.reload();
    }

    function readValueContinuous(characteristic){
      console.log('Reading Posture...');
      characteristic.readValue().then(value => {
        posture = value.getUint8(0);
        console.log(posture);
        determinePosture(posture);
        setTimeout(readValueContinuous(characteristic), 500);
      })
    };

    function sleep(milliseconds) {
      const date = Date.now();
      let currentDate = null;
      do {
        fullscreencontainer.style.backgroundColor = "#F25E5E";
        document.getElementById("postureStatus").innerHTML = "Bad posture!";
        currentDate = Date.now();
      } while (currentDate - date < milliseconds);
    }

    function determinePosture(postureInt) {
      BUFFER[iBuf] = postureInt;
      console.log("trenutna drža: ", postureInt);
      if (iBuf == length-1) iBuf=0;
      else iBuf++;
      let postureInterval = checkBuf();
      switch(postureInterval) {
        case 1:
          fullscreencontainer.style.backgroundColor = "#6CEB6A";
          document.getElementById("postureStatus").innerHTML = "Good posture.";
          break;

        case 0:
          fullscreencontainer.style.backgroundColor = "#F25E5E";
          document.getElementById("postureStatus").innerHTML = "Bad posture!";
          // Sound notificaton - Currently not in use
          // var mp3 = '<source src="sfx/bad.mp3" type="audio/mpeg">';
          // document.getElementById("sound").innerHTML = '<audio autoplay="autoplay">' + mp3 + "</audio>";
          
          // sleep(2000);
          break;

        case 4:
          fullscreencontainer.style.backgroundColor = "#F2C95E";
          document.getElementById("postureStatus").innerHTML = "Uncertain.";
          // circle1.style.fill='#';
          break;

        default:
          fullscreencontainer.style.backgroundColor = "#5ED8F2";
          document.getElementById("postureStatus").innerHTML = "Wait, please be patient...";
          // circle1.style.fill='black';
          
         
      }
    }

    function checkBuf() {
      let counter_arr = [0, 0, 0, 0]
      console.log("BUFFER: ", BUFFER);
      for(var i = 1; i < length; i++){
        if (BUFFER[i] == 1) counter_arr[0]++;
        else if (BUFFER[i] == 0) counter_arr[1]++;
        else if (BUFFER[i] == 4) counter_arr[2]++;
        else if (BUFFER[i] == -1) counter_arr[3]++;
      }
      var max = counter_arr.reduce(function(a, b) {
          return Math.max(a, b);
      });
      var indexOfMaxValue = counter_arr.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);
      if (max >= n_filter){
        return BUFFER[indexOfMaxValue];
      }
      else return -1;
    }
  </script>


  

  <!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>

Arduino code

Arduino
Code to be uploaded to Arduino Nano 33 BLE Sense.
Needs library with our model to run properly!
/* Edge Impulse Arduino examples
 * Copyright (c) 2021 EdgeImpulse Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/* Includes ---------------------------------------------------------------- */
#include <postchair_v2_inference.h>
#include <Arduino_LSM9DS1.h>

// BLE INICIALIZATION //
#include <ArduinoBLE.h>

// BLE Posture Service
BLEService postureService("757ab0ec-a387-11eb-bcbc-0242ac130000");

// BLE Posture Characteristic
BLECharacteristic postureChar("757ab0ec-a387-11eb-bcbc-0242ac130001", BLERead | BLEWrite, 1);

int oldPostureLevel = -1;

/* Constant defines -------------------------------------------------------- */
#define CONVERT_G_TO_MS2    9.80665f

#define RED 22     
#define BLUE 24     
#define GREEN 23
#define LED_PWR 25

/* Private variables ------------------------------------------------------- */
static bool debug_nn = false; // Set this to true to see e.g. features generated from the raw signal
static uint32_t run_inference_every_ms = 200;
static rtos::Thread inference_thread(osPriorityLow);
static float buffer[EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE] = { 0 };
static float inference_buffer[EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE];

/* Forward declaration */
void run_inference_background();

/**
* @brief      Arduino setup function
*/
void setup()
{
    pinMode(RED, OUTPUT);
    pinMode(BLUE, OUTPUT);
    pinMode(GREEN, OUTPUT);
    pinMode(LED_PWR, OUTPUT);
    // put your setup code here, to run once:
    Serial.begin(115200);
    while (!Serial);
    Serial.println("Edge Impulse Inferencing Demo");

    pinMode(LED_BUILTIN, OUTPUT); // initialize the built-in LED pin to indicate when a central is connected

    if (!IMU.begin()) {
        ei_printf("Failed to initialize IMU!\r\n");
    }
    else {
        ei_printf("IMU initialized\r\n");
    }

    if (EI_CLASSIFIER_RAW_SAMPLES_PER_FRAME != 3) {
        ei_printf("ERR: EI_CLASSIFIER_RAW_SAMPLES_PER_FRAME should be equal to 3 (the 3 sensor axes)\n");
        return;
    }

    inference_thread.start(mbed::callback(&run_inference_background));


// BLE SETUP //
    // begin initialization
  if (!BLE.begin()) {
    Serial.println("starting BLE failed!");

    while (1);
  }

  /* Set a local name for the BLE device
     This name will appear in advertising packets
     and can be used by remote devices to identify this BLE device
     The name can be changed but maybe be truncated based on space left in advertisement packet
  */
  BLE.setLocalName("PostureMonitor");
  BLE.setAdvertisedService(postureService); // add the service UUID
  postureService.addCharacteristic(postureChar); // add the posture characteristic
  BLE.addService(postureService); // Add the posture service
  postureChar.writeValue(byte(oldPostureLevel)); // set initial value for this characteristic

  /* Start advertising BLE.  It will start continuously transmitting BLE
     advertising packets and will be visible to remote BLE central devices
     until it receives a new connection */

  // start advertising
  BLE.advertise();

  Serial.println("Bluetooth device active, waiting for connections...");

  // 

  
}

/**
* @brief      Printf function uses vsnprintf and output using Arduino Serial
*
* @param[in]  format     Variable argument list
*/
void ei_printf(const char *format, ...) {
   static char print_buf[1024] = { 0 };

   va_list args;
   va_start(args, format);
   int r = vsnprintf(print_buf, sizeof(print_buf), format, args);
   va_end(args);

   if (r > 0) {
       Serial.write(print_buf);
       //postureChar.writeValue(print_buf);
   }
}

/**
 * @brief      Run inferencing in the background.
 */
void run_inference_background()
{
    // wait until we have a full buffer
    delay((EI_CLASSIFIER_INTERVAL_MS * EI_CLASSIFIER_RAW_SAMPLE_COUNT) + 100);

    // This is a structure that smoothens the output result
    // With the default settings 70% of readings should be the same before classifying.
    ei_classifier_smooth_t smooth;
    ei_classifier_smooth_init(&smooth, 10 /* no. of readings */, 7 /* min. readings the same */, 0.8 /* min. confidence */, 0.3 /* max anomaly */);

    while (1) {
        // copy the buffer
        memcpy(inference_buffer, buffer, EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE * sizeof(float));

        // Turn the raw buffer in a signal which we can the classify
        signal_t signal;
        int err = numpy::signal_from_buffer(inference_buffer, EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE, &signal);
        if (err != 0) {
            ei_printf("Failed to create signal from buffer (%d)\n", err);
            return;
        }

        // Run the classifier
        ei_impulse_result_t result = { 0 };

        err = run_classifier(&signal, &result, debug_nn);
        if (err != EI_IMPULSE_OK) {
            ei_printf("ERR: Failed to run classifier (%d)\n", err);
            return;
        }

        // print the predictions
        ei_printf("Predictions ");
        ei_printf("(DSP: %d ms., Classification: %d ms., Anomaly: %d ms.)",
            result.timing.dsp, result.timing.classification, result.timing.anomaly);
        ei_printf(": ");

        

        // ei_classifier_smooth_update yields the predicted label
        const char *prediction = ei_classifier_smooth_update(&smooth, &result);
        ei_printf("|%s|", prediction);

        int good = 1;
        int bad = 0;
        int uncertain = 4;
        int elses = -1;
        char *check = "gbu";

        turnOffLED();
        
        // če direkt kopiraš iz serial monitorja npr "good-posture-amadej" in tle prilepiš, pol dela (?!)
        // zato sem šel raje na prvo črko samo, ki pa ni tolk straightforward, zato je še ta char *check
        
        if(prediction[0] == check[0]){
          postureChar.writeValue(byte(1));
          turnOffLED();
          digitalWrite(RED, HIGH);
          
        } else if (prediction == "uncertain") {
          postureChar.writeValue(byte(4));
          turnOffLED();
          digitalWrite(RED, HIGH);
          digitalWrite(GREEN, HIGH);
          
        } else if (prediction[0] == check[1]){
          postureChar.writeValue(byte(0));
          turnOffLED();
          digitalWrite(GREEN, HIGH);
          
        } else {
          turnOffLED();
          postureChar.writeValue(byte(-1));
        }
        //
        // print the cumulative results
        ei_printf(" [ ");
        for (size_t ix = 0; ix < smooth.count_size; ix++) {
            ei_printf("%u", smooth.count[ix]);
            if (ix != smooth.count_size + 1) {
                ei_printf(", ");
            }
            else {
              ei_printf(" ");
            }
        }
        ei_printf("]\n");

        delay(run_inference_every_ms);
    }

    ei_classifier_smooth_free(&smooth);
}

/**
* @brief      Get data and run inferencing
*
* @param[in]  debug  Get debug info if true
*/
void loop()
{
    BLEDevice central = BLE.central();

    if (central) {
      Serial.print("Connected to central: ");
      // print the central's BT address:
      Serial.println(central.address());
      // turn on the LED to indicate the connection:
      digitalWrite(LED_BUILTIN, HIGH);
  
    
    
      while (central.connected()) {
          // Determine the next tick (and then sleep later)
          uint64_t next_tick = micros() + (EI_CLASSIFIER_INTERVAL_MS * 1000);
    
          // roll the buffer -3 points so we can overwrite the last one
          numpy::roll(buffer, EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE, -3);
    
          // read to the end of the buffer
          IMU.readAcceleration(
              buffer[EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE - 3],
              buffer[EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE - 2],
              buffer[EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE - 1]
          );
    
          buffer[EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE - 3] *= CONVERT_G_TO_MS2;
          buffer[EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE - 2] *= CONVERT_G_TO_MS2;
          buffer[EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE - 1] *= CONVERT_G_TO_MS2;
    
          // and wait for next tick
          uint64_t time_to_wait = next_tick - micros();
          delay((int)floor((float)time_to_wait / 1000.0f));
          delayMicroseconds(time_to_wait % 1000);
          
            // when the central disconnects, turn off the LED:
            
          
    
      }  
      digitalWrite(LED_BUILTIN, LOW);
      Serial.print("Disconnected from central: ");
      Serial.println(central.address());
    }
}

void turnOffLED(){
  digitalWrite(RED, LOW);
  digitalWrite(GREEN, LOW);
  digitalWrite(BLUE, LOW);
}


#if !defined(EI_CLASSIFIER_SENSOR) || EI_CLASSIFIER_SENSOR != EI_CLASSIFIER_SENSOR_ACCELEROMETER
#error "Invalid model for current sensor"
#endif

Credits

Amadej Pavšič

Amadej Pavšič

1 project • 2 followers
MihaJS

MihaJS

1 project • 2 followers
21 year old student from Slovenia.
Gašper Oblak

Gašper Oblak

1 project • 2 followers

Comments