Ok. This is my final code:
const int motor1 = 3;
const int motor2 = 4;
const int piezo = 0; // the piezo is connected to analog pin 0
// these variables will change:
int sensorReading = 0; // variable to store the value read from the sensor pin
int sensorMax = 0;
int sensorMin = 1023;
int threshold;
void setup() {
pinMode(13, OUTPUT);
pinMode(motor1, OUTPUT);
pinMode(motor2, OUTPUT);
Serial.begin(57600); // use the serial port
//CALIBRATION:
digitalWrite(13, HIGH);
while (millis() < 3000)
{
threshold = analogRead(piezo);
// record the maximum sensor value
if (threshold > sensorMax) {
sensorMax = threshold;
}
if (threshold < sensorMin) {
sensorMin = threshold;
}
}
// signal the end of the calibration period
digitalWrite(13, LOW);
digitalWrite(motor1, LOW);
digitalWrite(motor2, LOW);
threshold = sensorMax;
Serial.println (sensorMax);
Serial.println (sensorMin);
}
void loop()
{
// read the sensor and store it in the variable sensorReading:
sensorReading = analogRead(piezo);
Serial.println(sensorReading);
//I say..if <= sensorMin run one motor; if >= threshold run all
if ((sensorReading >= 350) && (sensorReading <= 500))
{
Serial.println ("Blow");
Serial.println (threshold);
digitalWrite (motor1,HIGH);
delay (1000);
digitalWrite (motor1, LOW);
}
else
{
if (sensorReading > 550)
{
Serial.println ("Spin");
Serial.println(sensorMin);
digitalWrite (motor1,HIGH);
digitalWrite (motor2,HIGH);
delay (1000);
digitalWrite (motor1, LOW);
digitalWrite (motor2, LOW);
}
}
delay(300);
}
In the code, I am defining 2 'if' conditions - One to run one motor, and another to run two motors together. Well, when the code is uploaded, though the whole setup kind of works the way I want it to, the action (blowing on to the sensor) and the reaction (the motor(s) running) do not accurately sync. My question is, playing with numbers (of the sensorReading) in the boundary conditions is the only possible way to make the if conditionals work, or is there any other accurate way to sync the action and reaction?