Struggling with code for Prosthetic Arm [Read problem in post]

Hey everyone.

I’m currently working on a robotic prosthetic arm. I am using a Myoware muscle sensor as the input. This sensor will read values from the muscles of the remaining limb and then command the prosthetic arm to move accordingly. Now, here’s what I want the arm to do - The sensor has values from 0 to 4.5V. The reading is between 0-0.5V when the muscle is at rest. However, when the muscle is flexed, you get a ‘pulse’ that spikes the reading to 2.5V or more. What I want to do is to instruct the servos to close the arm in one pulse and open the arm in the next pulse. Its exactly like this video - [Check 2:28] An Affordable 3D-Printed Arm - YouTube

The issue I’m facing is that the servo always goes back to 0 as soon as the pulse disappears. I want the servo to move to 180 once the pulse is detected and STAY IN THAT POSITION until the next pulse is detected. I’m a complete noob at programming. Here’s the code I wrote -

#include <Servo.h>

Servo servo1;
int sensorValue;
float threshold = 2.5;

void setup() {
Serial.begin(9600);
servo1.attach(9);
}

void loop() {

int sensorValue = analogRead(A0);

float voltage = sensorValue * (5.0 / 1023.0);

Serial.println(voltage);

if(voltage > threshold) {
servo1.write(180);
delay(2000);
if (voltage > threshold) {
servo1.write(0);
}
else {
servo1.write(180);
}
}
else {
servo1.write(0);
}
delay(2000);
Serial.println(voltage);
}

This piece of code doesn’t work as intended. The servo moves to 180 when the muscle is flexed but returns to 0 as soon as the flex is over (as soon as the pulse disappears). I want it to wait at 180 until the next pulse comes. It should move back to 0 only after the next pulse is detected. How do I write the code for that?
The way the arm moves in the above video is exactly what I want. I have the sensor, servo and arm ready. Only the code is an issue. It’ll be very helpful if someone could help me with the code.

Thanks a lot for your time!

Try this. Declare a new global variable named moved and set it to false

if (voltage has become greater than threshold) // See below how to do this
{
  if (moved == false)
  {
    servo1.write(180);
    moved = true;
  }
  else
  {
    servo1.write(0);
    moved = false;    
  }
    delay(2000);
}

You will need to use the technique in the StateChangeDetection example in the IDE to detect when the voltage [u]becomes[/u] greater than the threshold rather than when it [u]is[/u] greater than the threhold