// import a library for an LCD
#include <LiquidCrystal.h>
// LCD setup
const int RS = 11,
E = 12,
D4 = 6,
D5 = 5,
D6 = 4,
D7 = 3;
LiquidCrystal lcd(RS,E,D4,D5,D6,D7);
const int LCD_COLS = 16;
const int LCD_ROWS = 2;
const int LCD_2_ROW_START_COL = 3;
// array with pin numbers
const int pinNrsArray[] = {8, 7, 2};
const char *const pinColors[] = {"red", "yellow", "green"};
// length counter for the above array
const int amountOfPinsUsed = (sizeof(pinNrsArray) / sizeof(pinNrsArray[0]));
// diodes counter
int x = 0;
// init diode status
bool isLightOn = false;
// time counter initial values
unsigned long previousMillis = 0;
const long interval = 2000;
unsigned long currentMillis = 0;
// set up the app
void setup() {
// lcd printing init
lcd.begin(16,2);
// set cursor at the beginning (col, row)
lcd.setCursor(0,0);
lcd.print("Light status");
// declare using pins
for (int i = 0; i < amountOfPinsUsed; i++) {
pinMode(pinNrsArray[i], OUTPUT);
}
}
// main loop for creating diodes pulses
void loop() {
currentMillis = millis();
diodePulses(pinNrsArray[x]);
}
// turn the light on and off
// light is connected with a specific pin
void diodePulses(int pinNr) {
// do not execute further code if basic condition not met
// => less calculations in the loop
int millisDifference = currentMillis-previousMillis;
if (millisDifference >= interval) {
// time counting using basic (2s) & twice (4s) interval value
// with handling the case where the loop might be delayed for some reason
bool shouldLightOn = !isLightOn
&& ( millisDifference == interval
|| millisDifference < (interval*2) );
bool shouldLightOff = isLightOn
&& millisDifference >= (interval*2);
if (shouldLightOn || shouldLightOff) {
diodePulseToggle(pinNr);
}
if (shouldLightOff) {
// change saved previous time counter only if diode light goes off
previousMillis = currentMillis;
// change the diode counter value
x++;
if(x >= amountOfPinsUsed) x=0;
}
}
}
// switch the light of a diode
// write status on the LCD
void diodePulseToggle(int pinNr) {
isLightOn = !digitalRead(pinNr);
// change status of the diode
digitalWrite(pinNr, isLightOn);
writeLCDMessage(isLightOn);
//delay(2000);
}
// set cursor below the initially written "Lightstatus "
// and write status of the specific diode
void writeLCDMessage(bool isLightOn) {
lcd.setCursor(LCD_2_ROW_START_COL, 1);
lcd.print(" ");
lcd.setCursor(LCD_2_ROW_START_COL, 1);
lcd.print(String(pinColors[x]) + ": " + (isLightOn ? "ON" : "OFF"));
}