Seizure alarm for bed

Hello, Thanks for taking the time to read and hopefully help my son. I've been tinkering with Ardunio for a few years now. However, this project isn't as simple as it seemed. My son is 4.5 years old and has been having seizures since he was 6 months old. We need to make sure he isn't having them at night in case we don't wake up. I want to make device that can sense when he is having one and will sound an alarm. I've seen a really good post on this and copied the build. However, I have only UNO on hand and they used a MINI. That aside, I want to have TWO sensors in one. We have a motion mat that sounds an alarm if he should stops breathing/moving in his sleep. After 15 seconds of none movement, it beeps one time. after 25 seconds the alarm sounds until movement is sensed. I would like to combine both alarm types into this device.

device outline,

Device will have on and off switch. Should have bright LED used as indicator when normal movement is sensed (blink/flash whenever movement is sensed). Will also have loud beeper or buzzer. Buzzer should sound for short burst if no movement is sensed after 15 seconds. Next, buzzer should sound if no movement is sensed for a total elapsed time of 25 seconds. Buzzer should shut off if movement is sensed for over 5 seconds and return to "normal standby". Sensitivity will need to be adjustable so it can be fine tuned for the environment being used in.

second part of the code will be for sensing seizures. Alarm should sound if a seizure is sensed (more then normal movement). This type of movement will be a constant jerking/shacking type of movement. Sensitivity of this movement will need to be adjustable as well. If alot of movement is sensed (seizure) for more than 15 seconds the alarm should sound "until" normal movement is sensed for 15 seconds. System goes back to standby.

I am using the"KNOCK" example to start and have everything wired up and ready to go. Here is the code I and using but I am lost when it comes to adding a new set of perimeters.

Please help us so we can have piece of mind at night and hopefully get a regular nights sleep.

Thanks.

*/


// these constants won't change:
const int ledPin = 13;      // led connected to digital pin 13
const int knockSensor = A0; // the piezo is connected to analog pin 0
const int threshold = 1000-;  // threshold value to decide when the detected sound is a knock or not


// these variables will change:
int sensorReading = 0;      // variable to store the value read from the sensor pin
int ledState = LOW;         // variable used to store the last LED status, to toggle the light

void setup() {
  pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
  Serial.begin(9600);       // use the serial port
}

void loop() {
  // read the sensor and store it in the variable sensorReading:
  sensorReading = analogRead(knockSensor);

  // if the sensor reading is greater than the threshold:
  if (sensorReading >= threshold) {
    // toggle the status of the ledPin:
    ledState = !ledState;
    // update the LED pin itself:
    digitalWrite(ledPin, ledState);
    // send the string "Knock!" back to the computer, followed by newline
    Serial.println("Knock!");
  }
  delay(100);  // delay to avoid overloading the serial port buffer
}

Arduino code should be much the same between Mini and Uno. The wiring may be different to get things connected to the equivelant pins.

What is the output of the sensor mat? Is it digital (an on/off switch) or analog (a variable voltage)? Is there a single output or multiple? If you can post a link to a datasheet it will make it easier for people to help you.

What are the consequences if the device fails?

Am I reading this correctly?

You have only one input device, that is the motion mat.
You have two output devices for notification ( bright LED and a buzzer).

Depending on the length and intensity of activity the motion mat detects, you want to select one of several different types/levels of notification.

You want to (somehow) tune the sensitivity of the system ( say length of non-activity before an alarm is raised etc.)

If that is the case, it is certainly relatively straightforward problem to solve.

Thanks for the replies! As for the consequences if it fails I have no real concern. We try a record and aid my son's seizers and this would only allow us to monitor him while we are sleeping. He isn't in any real risk (so they say) but we do have meds and oxegen we can give him if they last longer than three minutes. Most nights he sleeps between us which helps us keep an eye on him but also keeps him from getting a full night's sleep. Surely if my wife or myself rolls over, he wakes up and has to fall back to sleep. Lack of sleep for him means more seizures the followjng day. Not a good cycle! We are hoping to put his bed next to ours so he is close to use but not influenced by us. The alarm would greatly help us on every level.

The sensor is simple but very accurate at its job. This is the info.
This basic piezo sensor from Measurement Specialties is often used for flex, touch, vibration and shock measurements. A small AC and large voltage (up to +/-90V) is created when the film moves back and forth. A simple resistor should get the voltage down to ADC levels. Can also be used for impact sensing or a flexible switch.

6v6gt, you have the idea 100%. I was hoping to have a hand with the code.

I suggest starting with a simple data logging sketch that simply records the output of the sensor against time. Either an SD card or maybe via serial to a laptop. That way you will build up an idea of what the signal looks like and be able to code up a solution to distinguish between normal and abnormal movements.

I guess that you have already wired it up according to the scheme in https://www.arduino.cc/en/Tutorial/Knock and it looks like you've been experimenting with the threshold value. So it all works ?

The +/- 90 volts sounds a bit alarming for an arduino input and I'm not sure how much the 1M ohm resistor across the sensor output reduces the risk of damage. I'd be tempted to put 2 diodes across the output in opposite directions to reduce the voltage to about 0.7 volts but maybe you get better suggestions here. Ideal would also be a datasheet for the sensor.

Anyway, as rw950431 has suggested, the next step is to understand what the sensor is delivering and how you can interpret it for your project.

I guess that what is important here is not the voltage you get but the number of pulses. Since the cycles are relatively short, it is probably enough to start with printing data to the serial console to see what it looks like.

So first I'd simply count the number of pulses in each say 3 second time period, using a variant of the sketch you have supplied. The 3 seconds is to allow a few time periods per breathing cycle, then see what the output looks like. Hopefully you can then distinguish the breathing activity from any background noise. A seizure would be identified by a large (yet to be determined) consecutive periods of "high" activity.

The next step would then be to build the notification/alarming part.

*/


// these constants won't change:
const int ledPin = 13;      // led connected to digital pin 13
const int knockSensor = A0; // the piezo is connected to analog pin 0
const int threshold = 1000-;  // threshold value to decide when the detected sound is a knock or not

unsigned long timeWindowStart = 0 ;
integer pulseCount = 0 ;


// these variables will change:
int sensorReading = 0;      // variable to store the value read from the sensor pin
int ledState = LOW;         // variable used to store the last LED status, to toggle the light

void setup() {
  pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
  Serial.begin(9600);       // use the serial port
}

void loop() {
  // read the sensor and store it in the variable sensorReading:
  sensorReading = analogRead(knockSensor);

  // if the sensor reading is greater than the threshold:
  if (sensorReading >= threshold) {
     pulseCount ++ ;
     // toggle the status of the ledPin:
     ledState = !ledState;
     // update the LED pin itself:
     digitalWrite(ledPin, ledState);
  }
  if ( millis() - timeWindowStart > 3000UL ) {  // 3 second time window
    Serial.print( "Number of pulses received in time window = " ) ;
    Serial.println( pulseCount ) ;
    timeWindowStart = millis() ;
    pulseCount = 0 ;
  }
  
}

Ok back at the project tonight. I really appreciate everyone's help! So far, I have everything wired up as per the "knock" sensor. from what can measure with my ohm meter, the sensor works like a solid state pot. If i bump it lightly, it show very little resistance, the harder I bump it the more resistance I read. No motion shows an open.

I copied the code 6v6gt provided but it shows but it has an error message.

Arduino: 1.6.10 (Windows 8.1), Board: "Arduino/Genuino Uno"

sketch_jul26c:5: error: expected unqualified-id before '/' token

 */

  ^

sketch_jul26c:5: error: expected constructor, destructor, or type conversion before '/' token

sketch_jul26c:11: error: expected primary-expression before ';' token

 const int threshold = 1000-;  // threshold value to decide when the detected sound is a knock or not

                            ^

sketch_jul26c:14: error: 'integer' does not name a type

 integer pulseCount = 0 ;

 ^

C:\Users\rodger\Documents\Arduino\sketch_jul26c\sketch_jul26c.ino: In function 'void setup()':

sketch_jul26c:22: error: 'ledPin' was not declared in this scope

   pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT

           ^

C:\Users\rodger\Documents\Arduino\sketch_jul26c\sketch_jul26c.ino: In function 'void loop()':

sketch_jul26c:32: error: 'pulseCount' was not declared in this scope

      pulseCount ++ ;

      ^

sketch_jul26c:36: error: 'ledPin' was not declared in this scope

      digitalWrite(ledPin, ledState);

                   ^

sketch_jul26c:40: error: 'pulseCount' was not declared in this scope

     Serial.println( pulseCount ) ;

                     ^

exit status 1
expected unqualified-id before '/' token

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I also have a buzzer on Digpin 12 that will need to be included in the code.

As for picking up background noise. Our house has finished concrete floors and my sons bed is solid wood. The only motion will be coming from my son. We have used a motion mat like this one for years. It really helped when our other son started walking, we would know if he got up at night. It has a sensor setting via a pot to adjust the level needed. We started out very sensitive and fine tuned it over a few nights. Having both seizure and none movement alarm would be a nice way to go. After its up and working I plan on setting up wifi with data logging and mobile alerts.

http://www.angelcarebaby.com/item/usa-infant-movement-sensor-pad-with-sound-monitor-ac601/#.V5qoF_krLIU

This is one of the posts I have been reading about. However, i cant even seem to get this to work;(

My/our version will/should be much better with some fine tuning.

Ah yes. The code you supplied in the OP had a stray */ at the top which I did not remove. It also had a stray - after the 1000.
pulseCount should be data type int and not integer. Sorry.

cool got that part working! i had the */ and - fixed but I didn't see the int part..thanks!

where will the buzzer fit into all this? I have it on pin 12. combining both functions with two outputs is a bit over my head.

is this line what I would change if I want more delay in pulses sensed before sounding alarm?
if ( millis() - timeWindowStart > 3000UL ) {  // 3 second time window

for none motion/stop breathing I would like a short buzz after 15 seconds on no movement. after 10 more seconds the buzzer should sound until normal movement for 5 seconds is sensed again.

for seizure alarm, the buzzer should sound if a higher amount of movement is sensed for 15 seconds. alarm should sound until normal movement is sensed for 1 minute or system is reset

the LED should flicker as it does whenever any movement is sensed and maybe stay full on when any alarm is going off.

maybe down the road I can add a relay on pin 11 so the lights in the room turn on of the alarm is sounding? just thinking out-loud...

The problem is divided into two parts:
(1) understanding what the sensor delivers and how it can be used to interpret the various states (background noise, normal activity, seizure activity, child not in bed etc,)
(2) how these states are notified/alarmed.

We are still at stage (1). The statement with 3000 mS is the collection period of the data.

You've given various information about the output of the sensor:
(a) A small AC and large voltage (up to +/-90V) is created when the film moves back and forth.
(b) the sensor works like a solid state pot.
As has been pointed out a couple of times to you, a datasheet or similar description would really help.
Can you supply this ?

Hello again! Sorry for the delay! My son just spent the last few days in the hospital. He's ok now but we live our lives minute by minute anymore.

Ok so here is the data sheet for the piezo. I was wrong in saying it acted like a potentiometer, it actually has its own voltage output. The 90v is cut down with the 1 megohm resistor so it can be safely used.

Since been in contact with the person mentioned in a previous post. He is the one who made a "seizure alarm". He used the mini and is making sure the code he wrote will work with UNO. This is only one part but more importantly it may shed some light on how he is using the sensor inputs. Hope to have time each night to pick at this until it's under his bed..thanks again everyone!

May be a bit late to this one…

Considered a bracelet type device with an accelerometer?
Sparkfun’s Triple Axis Accelerometer

It uses 40uA in measuring mode and takes 2-3.6V volts (ideal for a small battery like the CR2032) and has an SPI/I2C interface with readily available libraries.

A small IC, such as the Attiny84 series could be used as the MCU. They run on CR2032 batteries quite happily.

A 433Mhz Tx/Rx could be used as the wireless link. Have the Rx in the same room (close to your son/the bracelet) as it will have very short range at less than 3V!

The attiny84 can use very low power:
Watchdog Mode Power Usage

The Attiny84 could wake up every few seconds, check the accelerometer, if it is over a certain amount, take more measurements (to identify whether its a seizure or just him changing position).
If it looks like a seizure (multiple high ish readings over x time) then send something via the 433Mhz Tx module.

The Rx module will pick this up and sound an alarm? Wiring could be done or use another arduino as like a wireless repeater.

The Sensor document which you supplied is quite comprehensive and refers to several different products, but it gives a general idea and example circuits.

When you get the MINI code, please publish it here (with the author’s permission) together with the link to the original post you found which describes it .

Unless the author used some special features like say analog inputs A6 or A7 which are not available on the Uno, there should be no difference in the code. For downloading sketches, the Uno is easier because of its built in USB.

Below, I have drafted the parts of a possible solution which fits what you’ve already told us.

The Sensor Analyser (appears in the pseudo code below) is a code module which reads the sensor, interprets the current activity state according to the definitions below, and maintains certain state variables which are used be the remaining code. It is the key part of your solution. I’ve attempted to define it below and I’ve included the pseudo code for the alarming/notification part based on the requirements from your earlier posts. I hope I’ve interpreted it correctly. I’ve stated where I have made assumptions.

activity State Definitions

(These are to be adjusted depending on what the sensor can deliver - here assuming digital pulses which are polled in the loop)
HIGH : sensor detected > B pulses in the last x seconds. Remains in this state for 15 seconds after pulse intensity drops below threshold.
NORMAL : sensor detected between A and B pulses in the last x seconds
PASSIVE : sensor detected < A pulses in the last x seconds. Immediately cancels a HIGH state run on.
UNKNOWN : sensor not yet stable (after start up)

Sensor Analyser Output

  1. activityState (can be HIGH NORMAL PASSIVE UNKNOWN)
  2. thisActivityStateStartTimeMs (the start time (millis()) of this activty state )
  3. movementDetectedToggle (changes state 0/1 each time a movement is detected)
Pseudo Code (ie not yet C/C++): 

loop() {
  
 call SensorAnalyser()  // could instead be called from a pin change interrupt.

 If ( movementDetectedToggle != movementDetectedToggleLast ) {
   flash bright LED for (say) 100 Ms   
   movementDetectedToggleLast = movementDetectedToggle 
 }

 If ( activityState == PASSIVE ) {
   if ( thisActivityStateStartTimeMs > 25-x  seconds ago ) {
        Buzzer Continuous Tone
   } 
   elseif ( thisActivityStateStartTimeMs > 15-x seconds ago ) {
        Buzzer intermittent Tone
   } 
 }
 elseif (  activityState == HIGH ) {
     Buzzer Continuous Tone
 }
        elseif (  activityState == NORMAL ) {
     Buzzer cancel (if required)
}

6v6gt thank you for putting so much effort into this project! Sorry it’s been a few days since my last post. My son finaly,…after 14 months of failed attempts to have his tonsil’s and adenoids removed was healthy enough to have the surgery yesterday. This may prevent him from getting sick so easy and should in turn reduce the amount of seizures he has.

As for the seizure alarm code. I have been speaking to the writer via email. He sent me a revised code for the uno. I tried it out and it does work (well the light goes on and off) but not what I was hoping for.

this is the code I was sent

/* Knock Sensor
  
   This sketch reads a piezo element to detect a knocking sound. 
   It reads an analog pin and compares the result to a set threshold. 
   If the result is greater than the threshold, it writes
   "knock" to the serial port, and toggles the LED on pin 13.
  
   The circuit:
	* + connection of the piezo attached to analog in 0
	* - connection of the piezo attached to ground
	* 1-megohm resistor attached from analog in 0 to ground

   http://www.arduino.cc/en/Tutorial/Knock
   
   created 25 Mar 2007
   by David Cuartielles <http://www.0j0.org>
   modified 30 Aug 2011
   by Tom Igoe
   modified again 1 June 2015
   by Chad Hebert
   
   This example code is in the public domain.

 */
 

// these constants won't change:
const int ledPin = 13;      // led connected to digital pin 13
const int knockSensor = A0; // the piezo is connected to analog pin 0
const int threshold = 20
;  // threshold value to decide when the detected sound is a knock or not


// these variables will change:
int sensorReading = 0;      // variable to store the value read from the sensor pin
int ledState = LOW;         // variable used to store the last LED status, to toggle the light

void setup() {
 pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
 Serial.begin(9600);       // use the serial port
}

void loop() {
  // read the sensor and store it in the variable sensorReading:
  sensorReading = analogRead(knockSensor);    
  
  // if the sensor reading is greater than the threshold:
  if (sensorReading >= threshold) {
    // toggle the status of the ledPin:
    ledState = !ledState;   
    // update the LED pin itself:        
    digitalWrite(ledPin, ledState);
    // send the string "Knock!" back to the computer, followed by newline
    Serial.println("Knock!");         
  }
  delay(100);  // delay to avoid overloading the serial port buffer
}

I will have more time tomorrow to look at the code and instructions you provided.

Code is not very good. It misses “knocks” and is quite insensitive.
Try this sketch.
Leo…

// knock sensor/alarm
// Piezo, with 1Megohm load resistor across, connected to A0 and ground
// optional 5volt buzzer on pin 13

int threshold = 100; // alarm threshold from 1 (very sensitive) to 1022 <<<<<<<<
int alarmDuration = 100; // alarm duration in milliseconds <<<<<<<<

const byte piezoPin = A0;
int rawValue; // raw A/D readings
int piezoValue; // peak value
const byte onboardLED = 13; // onboard LED and/or buzzer

void setup() {
  analogReference(INTERNAL); // remove this line if too sensitive
  Serial.begin(9600); // serial monitor for raw piezo output
  pinMode (onboardLED, OUTPUT);
}

void loop() {
  // reset
  piezoValue = 0;
  // read
  for (int x = 0; x < 250; x++) { // multiple A/D readings
    rawValue = analogRead(piezoPin);
    if (rawValue > piezoValue) {
      piezoValue = rawValue; // store peaks
    }
  }
  // print
  if (piezoValue > 0) {
    Serial.print(F("Piezo value is "));
    Serial.println(piezoValue);
  }
  // action
  if (piezoValue > threshold) {
    Serial.print(F("Knock was over the threshold of "));
    Serial.println(threshold);
    digitalWrite (onboardLED, HIGH);
    delay(alarmDuration);
    digitalWrite (onboardLED, LOW);
  }
}

OK, finally have a few hours to try some things out. My sons been in the hospital 3 times since his surgery a few weeks ago. He's doing pretty good so that's great!

I just tried the code Wawa posted. It works much better and I feel like we are on the right track.

one thing I am noticing is that it doesn't have a delay for a said amount of time. It may be a minor adjustment but I'm not sure what value to change.

so far I can set the sensitivity via threshold as well as how long the alarm sounds for.

I take it this is the code for sensing a seizure and is still missing the "none" movement part. Working in steps should help makes things a bit easier so I'm all for that.

The seizure alarm should work as follows.

  1. sense normal movement while sleeping. the code works great for sensing/reporting movement and the sensitivity is easily adjusted.

  2. If the normal movement is higher than expected (seizure) for more than 10 seconds the alarm should sound for a said amount of time (at least one minute) . this is the part of the code that is missing so far. as it stands,

  3. I would like to add an LED on say pin 12 that blinks/flashes with all movement. This will allow us to be sure the device is working at all times.

  4. If alarm sounds, maybe a relay on pin 11 can trigger on and turn a lamp on to light the room?

thanks again for helping with this project!

This might do what you want.
Tested, but it might need some polishing.
Leo…

// knock sensor/alarm
// Piezo, with 1Megohm load resistor across, connected to A0 and ground
// 5volt buzzer on pin 10

const int alarmThreshold = 100; // alarm threshold from 1 (very sensitive) to 1022
const int alarmDuration = 10000; // alarm duration in milliseconds
const byte eventThreshold = 50; // number of events before alarm | 1-255

byte piezoPin = A0;
byte ledPin = 9; // external LED
byte buzzerPin = 10; // alarm buzzer
byte lightPin = 11; // room light relay module
byte buttonPin = 12; // button to turn the light off
// timed events
unsigned long currentMillis;
unsigned long previousMillis;
unsigned long currentAlarm;
unsigned long interval = 1000;
int rawValue; // raw A/D readings
int piezoValue; // peak value
byte ledValue = 0; // brightness
byte eventCounter = 0; // knock events over the threshold
boolean ledState;
boolean alarmState;
boolean alarmLockout;
boolean lightState;

void setup() {
  analogReference(INTERNAL); // remove this line if too sensitive
  Serial.begin(115200); // serial monitor for raw piezo output
  pinMode(ledPin, OUTPUT); // pin 9
  pinMode(buzzerPin, OUTPUT); // pin 10
  digitalWrite(lightPin, HIGH); // assumes normally high relay module with opto isolation
  pinMode(lightPin, OUTPUT); // on pin 11
  pinMode(buttonPin, INPUT_PULLUP); // light off button from pin 12 to ground
  Serial.println(F("Knock Sensor"));
  Serial.println(F("============"));
}

void loop() {
  currentMillis = millis(); // update every loop
  piezoValue = 0; // reset before measuring
  // events countdown to zero
  if (currentMillis - previousMillis >= interval) {
    if (eventCounter > 0) {
      eventCounter --;
      Serial.print(F("Event counter is "));
      Serial.println(eventCounter);
    }
    previousMillis = currentMillis;
  }
  // read sensor
  for (int x = 0; x < 250; x++) { // multiple A/D readings
    rawValue = analogRead(piezoPin);
    if (rawValue > piezoValue) {
      piezoValue = rawValue; // store peaks
    }
  }
  // action
  if (piezoValue == 0 && ledState) { // if no movement and LED is on
    analogWrite(ledPin, 0); // turn LED off
    ledState = LOW; // remember LED is now off
  }
  if (piezoValue > 0) { // if there is any movement
    Serial.print(F("Piezo value is "));
    Serial.println(piezoValue); // print the value
    ledValue = map(piezoValue, 0, 1023, 0, 255); // map to PWM range
    analogWrite(ledPin, ledValue); // LED brightness depends on knock intensity
    if (!ledState) {
      ledState = HIGH; // remember LED is now on
    }
  }
  if (piezoValue > alarmThreshold) { // if movement is over the threshold
    Serial.print(F("Knock was over the threshold of "));
    Serial.println(alarmThreshold); // prints threshold
    if (eventCounter < eventThreshold) { // add event to the event counter | with limit
      eventCounter ++;
    }
    Serial.print(F("Event counter is "));
    Serial.println(eventCounter);
  }
  if (eventCounter >= eventThreshold) { // if event count reaches the threshold
    if (!alarmState && !alarmLockout) { // turn alarm on | once
      digitalWrite(buzzerPin, HIGH); // turn the alarm on
      alarmState = HIGH; // remember it
      currentAlarm = currentMillis;
      Serial.println(F(">>>> ALARM ON <<<<"));
    }
    if (!lightState) {  // if light is off
      digitalWrite(lightPin, LOW); // assumes opto relay with active low
      lightState = HIGH; // remember light is on
      Serial.println(F(">>>> LIGHTS ON <<<<"));
    }
  }
  if (alarmState && currentMillis >= currentAlarm + alarmDuration) { // alarm duration
    digitalWrite(buzzerPin, LOW); // turn the alarm on
    alarmState = LOW; // remember it
    alarmLockout = HIGH; // not re-triggering
  }

  if (digitalRead(buttonPin) == LOW && lightState) { // if lightoff button is pushed and the light was on
    digitalWrite(lightPin, HIGH); // turn light off
    lightState = LOW; // remember it
    digitalWrite(buzzerPin, LOW); // turn the alarm off if it's still on
    alarmState = LOW; // remember it
    alarmLockout = LOW; // alarm is possible again
    eventCounter = 0;
  }
}

I installed the LED and that works perfectly. I can't get the buzzer to sound however. I tinkered with some of the values with no luck. The light in the UNO does stay on for the amount of time specified when alot of activity is sensed. Hope that info helps narrow the alarm issue down some. I didn't have a chance to install the relay or light off button yet either. I should have a few hours tonight to work on this again and complete the hardware side of things.