The mode selector is now complete! The button switches through the three LEDs (modes). After five seconds, the LED fades away to a dim setting so that we can conserve power in the long run.
|
Cleaned-up LED and pushbutton system. |
The last step will be to clean up the code (for modularity).
Arduino code for the LED system integrated with the moisture sensor reading is given below:
//initialize constants
const int buttonPin = 2;
const int LED1 = 11;
const int LED2 = 10;
const int LED3 = 9;
const int moistureSensor = 0;
const unsigned long deBounceDelay = 200;
const unsigned long moistureDelay = 5000;
//initialize variables
int buttonState = 0;
int lastButtonState = 0;
int mode=1;
int fadeValue;
int moistureReading = 0;
unsigned long deBounceTimer = 0;
unsigned long moistureTimer = 0;
unsigned long startTime;
//set-up interrupt
void setup() {
//initialize each of the three LED pins as outputs
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
//initialize the pushButton pin as an input
pinMode (buttonPin, INPUT);
//initialize serial communication; mid-range data rate 9600 bps
Serial.begin(9600);
//attachInterrupt(0, off, RISING);
}
void loop() {
buttonCheck();
switch (mode) {
case 1:
off();
digitalWrite(LED1, HIGH);
startTime = millis();
fadeValue = 255;
while(mode==1) {
buttonCheck();
readMoisture();
if((fadeValue>55)&&((millis()-startTime) > 5000)) {
for(fadeValue = 255; fadeValue >=50; fadeValue -=5) {
analogWrite(LED1, fadeValue);
delay(30);
}
}
}
break;
case 2:
off();
digitalWrite(LED2, HIGH);
startTime = millis();
fadeValue = 255;
while(mode==2) {
buttonCheck();
readMoisture();
if((fadeValue>55)&&((millis()-startTime) > 5000)) {
for(fadeValue = 255; fadeValue >=50; fadeValue -=5) {
analogWrite(LED2, fadeValue);
delay(30);
}
}
}
break;
case 3:
off();
digitalWrite(LED3, HIGH);
startTime = millis();
fadeValue = 255;
while(mode==3) {
buttonCheck();
readMoisture();
if((fadeValue>55)&&((millis()-startTime) > 5000)) {
for(fadeValue = 255; fadeValue >=50; fadeValue -=5) {
analogWrite(LED3, fadeValue);
delay(30);
}
}
}
break;
}
}
void buttonCheck() {
buttonState = digitalRead(buttonPin);
if (!buttonState&&lastButtonState&&(millis()-deBounceTimer)>deBounceDelay){
mode++;
if(mode>3)mode=1;
lastButtonState = buttonState;
deBounceTimer = millis();
}
if (buttonState&&!lastButtonState&&(millis()-deBounceTimer)>deBounceDelay){
lastButtonState = buttonState;
deBounceTimer = millis();
}
}
void readMoisture() {
if ((millis()-moistureTimer)>moistureDelay){
moistureReading = analogRead(moistureSensor);
moistureTimer=millis();
Serial.print("moisture sensor reads ");
Serial.println( moistureReading);
}
}
void off() {
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
}