I would like to control 3 MG995 servo motors with 3 FSR.
if sensor is fully press the servo will be at 90 degree. if fsr is not press the servo will be at 0 degree.
It is the first time I'm working with servo motors. I am not sure my code is the best for what want. Any advice?
project wired as follow:
here is my code:
#define NUM_INPUTS 2
#include <Servo.h>
const byte SIG_pins[] = { A0, A1, A2 };
int heartbeatLED = 13;
const byte filter = 3; //adjust as needed
const byte pressThreshold = 10;
int lastValue[NUM_INPUTS];
bool muxIsOn[NUM_INPUTS];
Servo servos[NUM_INPUTS];
// define servo pins
const byte servoPins[] = { 9, 10, 11 };
//timing variables
unsigned long previousMillis = 0;
unsigned long heartbeatMillis;
unsigned long interval = 20;
// servo angles for each FSR
int servoAngles[] = { 0, 0, 0 };
//********************************************^************************************************
void setup() {
Serial.begin(115200);
pinMode(heartbeatLED, OUTPUT);
for (byte i = 0; i < NUM_INPUTS; i++) {
pinMode(SIG_pins[i], INPUT);
servos[i].attach(servoPins[i]); // attach servo to corresponding pin
}
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
readValues();
checkHeartbeatTIMER();
controlServos();
}
}
//// functions ////
void readValues() {
for (byte i = 0; i < NUM_INPUTS; i++) {
//read the stabilized analog
int SensorValue = 1023 - analogRead(SIG_pins[i]);
//has analog value changed more than the filter amount ?
if (abs(lastValue[i] - SensorValue) > filter) {
if (lastValue[i] != SensorValue) {
//update to the new value
lastValue[i] = SensorValue;
Serial.print("sensor");
Serial.print(i + 1);
Serial.print(" ");
Serial.println(SensorValue);
// check if FSR is pressed or not
if (SensorValue >= pressThreshold) {
int servoAngle = map(SensorValue, pressThreshold, 1023, 0, 90);
servoAngles[i] = servoAngle;
Serial.print("ch");
Serial.print(i + 1);
Serial.print(" servo angle: ");
Serial.println(servoAngle);
} else {
servoAngles[i] = 0;
}
}
}
}
}
void controlServos() {
for (byte i = 0; i < NUM_INPUTS; i++) {
servos[i].write(servoAngles[i]);
}
}
void checkHeartbeatTIMER() {
//********************************* heartbeat TIMER
//is it time to toggle the heartbeatLED ?
if (millis() - heartbeatMillis >= 500ul) {
//restart this TIMER
heartbeatMillis = millis();
//toggle the heartbeatLED
digitalWrite(heartbeatLED, !digitalRead(heartbeatLED));
}
} //END of checkHeartbeatTIMER()