I have recently started a project to make a robotic arm and have run into a problem. We need a 180 rotation 25kg servo to run simultaneously with an emg sensor, while still constantly checking the sensor. But with this code it is stopping the data coming out of the sensor and executing the servo's command, which makes the arduino read the data incredibly slowly and very late. If anyone has any suggestions on how to get this to work that would be appreciated.
#include <Servo.h>
Servo myServo;
int emgPin = A0;
int emgVal = 0;
void setup() {
// put your setup code here, to run once:
myServo.attach(5);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
emgVal = analogRead(emgPin);
Serial.println(emgVal);
delay(100);
if(emgVal>400;emgVal<1024){
myServo.write(0);
delay(10);
}
else{
myServo.write(180);
}
}
Following the good advice of @J-M-L to not use delay() (note the servo library you used probably used delay()) and @Etienne_74 to use internal timing to drive your servo without blocking mpu access to your sensor, I cobbled a simulation with some explanation in the comments.
You can see two events in the simcode... you need to discover where to insert your sensor-reading code, but it should not be difficult.
I made slight modifications to @xfpd code : I toggled pin D13 up and down for each Loop and added a Logic Analyzer to visualize the signal (or timings) with PulseView.
EDIT : I also added the servo pulse for comparison and centered the pot for "ease of use"
=> the up/down toggle takes 2 x 125ns (a digitalWrite() would have taken 2 x 1.75µs) and a complete loop takes 153.375µs (+ 2 x 125ns). That is the max jitter for the servo signal.
To be tested with interrupt and, even better, with hardware PWM...