I wonder if there is a good way to use the same variable value between two different if-statements within the loop().
Within the Servomotor section of the code, I want to use the value from the first if-statement's RewardTime within the next if-statement's RewardTime. Thus far, I cannot find a way to do it. (Since there is no communication between these variables right now, the RewardTime remains 0).
I'd appreciate a certain guidance in this matter.
#include <Servo.h> // Library required for the servomotor (Make sure to download if not in the library)
#include <Button.h> // Library required for the microswitch (Make sure to download if not in the lbrary)
// PARAMETERS
// COPY THESE VALUES IN PROCESSING CODE MANUALLY
// Explanation: To prevent possible Arduino-Processing overflow. Do not want too much information flow between Arduino and Processing.
const float Scale = 1 * 1000; // milliseconds
const float Base = 1 * 1000; // milliseconds
Servo Servo1;
int servoPin = 9; // Declare the Servo pin
Button button(7); // Declare the microswitch pin (Can be varied from setup to setup)
unsigned long previousMillis = 0;
bool switching = false;
int State = LOW;
char BirdSings = 0;
//static float RewardTime = 0;
void setup() {
Servo1.attach(servoPin);
analogWrite(9, 0);
Serial.begin(9600);
button.setDebounceTime(100); // set debounce time to 100 milliseconds
}
void loop(){
// MICROSWITCH
// Get onset and offset times of when the bird arrives and leaves the perch
button.loop();
if(button.isPressed())
Serial.println(1);
if(button.isReleased())
Serial.println(0);
// SERVOMOTOR
// Get times when the feeder is covered (food present) and uncovered (food not present)
unsigned long currentMillis = millis();
while (Serial.available() > 0) {
unsigned long currentMillis = millis();
if (Serial.read() == '\n') { // When there is a song
//Serial.println(2); // Food is uncovered
previousMillis = currentMillis; // 0 becomes the current milli
static float RewardTime = (Serial.parseFloat() * Scale) + Base; // CALCULATE THE RewardTime HERE
Serial.println(RewardTime);
if (State == LOW)
State = HIGH;
else
State = LOW;
}
}
if (State == HIGH && switching == false){
Servo1.write(0); // 0 degree
unsigned long secondCurrentMillis = millis();
if (secondCurrentMillis - previousMillis > RewardTime) { // USE THE ABOVE RewardTime HERE
switching = true;
previousMillis = secondCurrentMillis;
if (State == LOW)
State = HIGH;
else
State = LOW;
}
}
if(State == LOW && switching == true){
Servo1.write(90); // 90 degrees
switching = false;
//Serial.println(3); // Food is covered
}
}