unsigned long period1StartMillis; //start counting period1 time
unsigned long period2StartMillis; //start counting period2 time
unsigned long currentMillis;
const unsigned long fanPeriod1 = 2000; //fan duration
const unsigned long fanPeriod2 = 4000; //fan duration
const int BUTTON1_PIN = A1; // Arduino pin connected to button's pin
const int BUTTON2_PIN = A2; // Arduino pin connected to button's pin
const int LED1_PIN = 2; // Arduino pin connected to LED's pin
const int LED2_PIN = 3; // Arduino pin connected to LED's pin
const int ANALOG_PIN = 5; // Arduino pin connected to analog output pin
// variables will change:
int led1State = 0; // the current state of LED1
int led2State = 0; // the current state of LED2
int lastButton1State; // the previous state of button
int currentButton1State; // the current state of button
int lastButton2State; // the previous state of button
int currentButton2State; // the current state of button
void setup() {
pinMode(BUTTON1_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
pinMode(BUTTON2_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
pinMode(LED1_PIN, OUTPUT); // set arduino pin to output mode
pinMode(LED2_PIN, OUTPUT); // set arduino pin to output mode
digitalWrite(LED1_PIN, led1State);
digitalWrite(LED2_PIN, led2State);
}
void loop()
{
currentMillis = millis();
lastButton1State = currentButton1State; // save the last state
lastButton2State = currentButton2State; // save the last state
//Period1 (duration1):
currentButton1State = digitalRead(BUTTON1_PIN); // read new state Button #1
if (lastButton1State == 1 && currentButton1State == 0)
{
digitalWrite(LED1_PIN, 1); // LED#1 turn on
digitalWrite(LED2_PIN, 0);
analogWrite(ANALOG_PIN, 128); // set analog to 50%
period1StartMillis = currentMillis; //save the time that the state change occured
period2StartMillis = 0; // turn period 2 off
}
if (period1StartMillis && currentMillis - period1StartMillis >= fanPeriod1) // check if time has run out
{
digitalWrite(LED1_PIN, 0);
analogWrite(ANALOG_PIN, 0); // set analog to 0% This is the PROBLEM #1
period1StartMillis = 0;
}
//Period2 (duration2):
currentButton2State = digitalRead(BUTTON2_PIN); // read new state Buttom #2
if (lastButton2State == 1 && currentButton2State == 0)
{
digitalWrite(LED2_PIN, 1); //LED#2 turn on
digitalWrite(LED1_PIN, 0);
analogWrite(ANALOG_PIN, 255);
period2StartMillis = currentMillis; //save the time that the state change occured
period1StartMillis = 0; // turn period 1 off
}
if (period2StartMillis && currentMillis - period2StartMillis >= fanPeriod2) // check if time has run out
{
digitalWrite(LED2_PIN, 0);
analogWrite(ANALOG_PIN, 0); // set analog to 0% This is the PROBLEM #2
period2StartMillis = 0;
}
}