I would like to proto thread two functions to run pseudo-simultaneously. One function takes the input of a force sensor and moves a servo accordingly, and the other takes the input of a gyroscope (MPU650) and moves a different sensor accordingly. Below is my code where I attempt to use timers to handle this.
#include <Wire.h>
#include <Servo.h>
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Servo.h"
int FSR_Pin = A0;
bool isClosed = false;
unsigned long lastMillis = 0;
unsigned long lastMillis2 = 0;
MPU6050 mpu;
int16_t ax, ay, az;
int16_t gx, gy, gz;
Servo handServo;
Servo wristServo;
int pos = 0;
int val;
int prevVal;
void setup(){
Serial.begin(9600);
handServo.attach(9);
Wire.begin();
Serial.begin(38400);
Serial.println("Initialize MPU");
mpu.initialize();
Serial.println(mpu.testConnection() ? "Connected" : "Connection failed");
wristServo.attach(8);
}
void handleFingers () {
int FSRReading = analogRead(FSR_Pin);
Serial.println(FSRReading);
if (FSRReading > 9) {
if (pos < 90) {
handServo.write(pos);
pos ++;
}
isClosed = true;
} else if (isClosed == true && FSRReading < 10) {
pos = 0;
handServo.write(pos);
isClosed = false;
}
}
void handleWrist() {
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
val = map(ay, -17000, 17000, 0, 179);
if (val != prevVal)
{
wristServo.write(val);
prevVal = val;
}
}
void loop(){
if (millis() - lastMillis > 1000) {
handleFingers ();
}
lastMillis = millis();
if (millis() - lastMillis2 > 1000) {
handleWrist();
}
lastMillis2 = millis();
}
When I run the code above, the servos move a few degrees each and then do nothing at all. It appears that none of the servos are responsive to the sensor feedback. Something is wrong with my timing or my method of proto threading. I would really appreciate your help, thanks.